-9

我想添加 2 个二进制数,但是我的程序无法正常工作。请查看我的代码并在任何错误中告诉我。谢谢。这是代码:

import time
n=0
while n!=1:
    error1=True
    while error1:
        try:
            bin2dec = raw_input("Please enter a binary number: ")
            bin2dec2 = raw_input("Please enter a binary number: ")
            error1=False
        except NameError:
            print"Enter a Binary number. Please try again.\n"
            time.sleep(0.5)
        except SyntaxError:
            print"Enter a Binary number. Please try again.\n"
            time.sleep(0.5)


    decnum=0

    for i in bin2dec: 
        decnum = decnum * 2 + int(i)

    decnum2=0

    for i in bin2dec2: 
        decnum2 = decnum2 * 2 + int(i)
        dectotal=decnum+decnum2
        b = ''            
        b = str(dectotal % 2) + b
        dectotal >>= 1
        print b,
    print"<<This is your answer"
4

1 回答 1

1

The following code should fit your requirements quite nicely, while being much, much shorter:

print (lambda x,y: bin(int(x,2)+int(y,2))[2:])(raw_input(),raw_input())

The following would be even better:

a="Enter Number";ri=raw_input;print "Sum: "+(lambda x,y: bin(int(x,2)+int(y,2))[2:])(ri(a+' 1: '),ri(a+' 2: '))

Since you can't use bin or dec, try the following. It doesn't use bin, and doesn't use dec. It also doesn't use variable assignment, def statements, multiple statements, or int. In fact, it doesn't even use built-in addition, multiplication or division for the numbers themselves:

print "Sum: "+(lambda q: "".join(reversed([ (lambda n: n[0+(None!=q.__setitem__(0,n[1]))])
((lambda x,y,z: (lambda v: (str(v%2),str(v/2)))
((ord(x)-48)+(ord(y)-48)+(ord(z)-48)))(x,y,q[0])) 
for x,y in reversed(zip(raw_input("Enter Number 1: ").zfill(16),
raw_input("Enter Number 2: ").zfill(16)))])))(['0'])

Note that while this works, and I would encourage you to examine it, if you submit it as an exam answer, I am not responsible for any loss of points or injury to you by angry examiners.

于 2013-06-13T19:33:23.190 回答