简体   繁体   English

添加程序不起作用

[英]Adding program doesn't work

I'm trying to write a simple binary adding program in Python (I know Python can do it already, I'm just doing it to practice basic computing concepts). 我试图用Python编写一个简单的二进制添加程序(我知道Python已经可以做到,我只是在实践基本的计算概念而已)。 I got it to work pretty well, the only thing that is weird is that when one of the numbers is longer than the other and starts in 0, the program doesn't return the expected result: 我使它运行得很好,唯一奇怪的是,当一个数字比另一个数字长并且以0开始时,程序不会返回预期的结果:

#Binary Adding Machine
def add(a,b):
    #create empty variables
    result=""
    state=0
    #equalize string lengths
    if a>=b:
        c=a
        b="0"*(len(a)-len(b))+b
    else:
        c=b
        a="0"*(len(b)-len(a))+a
    #add strings together into result, in reverse order
    for i in range(1,(len(c)+1)):
        if state==0:
            if a[-i]==b[-i]=="0":
                result+="0"
                state=0
            elif ((a[-i]=="0" and b[-i]=="1") or (a[-i]=="1" and b[-i]=="0")):
                result+="1"
               state=0
            elif a[-i]==b[-i]=="1":
                result+="0"
                state=1
        elif state==1:
            if a[-i]==b[-i]=="0":
                result+="1"
                state=0
            elif ((a[-i]=="0" and b[-i]=="1") or (a[-i]=="1" and b[-i]=="0")):
                result+="0"
                state=1
            elif a[-i]==b[-i]=="1":
                result+="1"
                state=1
    #add another "1" if final state is 1
    if state==1:
        result+="1"
        state=0
    #reverse string
    return result[::-1]

print(add("110101","1111010"))
print(add("1","100000"))
print(add("1","1"))
print(add("100","100"))
print(add("000100100","100"))
print(add("100100100","100"))

If you run the program the following numbers will be printed: 如果运行该程序,将打印以下数字:

10101111
100001
10
1000
1000
100101000

The second to last line should return 000101000 but instead it returns 1000 . 倒数第二行应返回000101000但应返回1000 It works fine if the number starts in 1, though, as we can see in the last line. 但是,如果数字从1开始,效果很好,正如我们在最后一行看到的那样。

Can anyone recognize why this is happening? 谁能知道为什么会这样吗?

Thank you very much. 非常感谢你。

change 更改

if(a >= b) to if(len(a) >= len(b))

your condition means that python is supposed to compare ascii values and not its length. 您的情况意味着python应该比较ascii值而不是其长度。 As you know 0 is less than 1, in that particular case it won't give you what you expect. 如您所知,0小于1,在这种情况下,它将无法满足您的期望。 Length comparison is what you want. 长度比较是您想要的。

And as Marcin suggested, there are better ways to do this. 正如Marcin建议的那样,有更好的方法可以做到这一点。

This is not a direct answer to your problem, ie why your specific code does not work, but rather an alternative implementation of your add function. 这不是您问题的直接答案,即为什么您的特定代码不起作用,而是您add函数的替代实现。 It might be useful to you for checking results of your code, or for others who have similar problem. 这对于检查代码结果或其他有类似问题的人可能很有用。

def add2(a,b):
    return "{0:010b}".format(int(a,2) + int(b,2))


print(add2("110101","1111010"))
print(add2("1","100000"))
print(add2("1","1"))
print(add2("100","100"))
print(add2("000100100","100"))
print(add2("100100100","100"))

The output is: 输出为:

0010101111
0000100001
0000000010
0000001000
0000101000
0100101000
def add(a,b):
'''add two binary numbers'''
if len(a) > len(b):
    high =  list(a)
    low  =  list(b)
else:
    high =   list(b)
    low  =   list(a) 
# using integers
low     =   map(int,low)
high    =   map(int,high)
# turn
low.reverse()
high.reverse()    

for x in range(len(low)):
    ''' add one too the longer 'number' in the position x, 
        if the smaller number contains an 1 in the same position
    '''
    if low[x] == 1:
        high[x] += 1
''' if in the bigger number is a two, add 1 to the higher position and set it to zero
    if no higher position exists, create one.
'''
for y in range(len(high)):
    if high[y] > 1:
        try:
            high[y+1] +=1
            high[y]   = 0
        except:
            high.append(1)
            high[y]   = 0
'''turn, make strings and return one string'''
high.reverse()
high = map(str,high)
return ''.join(high)     

if name == ' main ': 如果name ==' main ':

print(add("110101","1111010"))
print(add("1","100000"))
print(add("1","1"))
print(add("100","100"))
print(add("000100100","100"))
print(add("100100100","100"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM