【问题标题】:Adding program doesn't work添加程序不起作用
【发布时间】:2015-02-04 05:49:12
【问题描述】:

我正在尝试用 Python 编写一个简单的二进制加法程序(我知道 Python 已经可以做到,我只是在练习基本的计算概念)。我让它工作得很好,唯一奇怪的是,当一个数字比另一个数字长并且从 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"))

如果您运行程序,将打印以下数字:

10101111
100001
10
1000
1000
100101000

倒数第二行应该返回000101000,但它却返回1000。但是,如果数字从 1 开始,它就可以正常工作,正如我们在最后一行中看到的那样。

谁能知道为什么会这样?

非常感谢。

【问题讨论】:

    标签: python binary add turing-machines


    【解决方案1】:

    改变

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

    您的条件意味着 python 应该比较 ascii 值而不是它的长度。如您所知,0 小于 1,在这种特殊情况下,它不会给您所期望的。长度比较是你想要的。

    正如 Marcin 所建议的,有更好的方法来做到这一点。

    【讨论】:

      【解决方案2】:

      这不是您的问题的直接答案,即为什么您的特定代码不起作用,而是您的 add 函数的替代实现。它可能对您检查代码结果或其他有类似问题的人有用。

      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"))
      

      输出是:

      0010101111
      0000100001
      0000000010
      0000001000
      0000101000
      0100101000
      

      【讨论】:

        【解决方案3】:
        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)     
        

        如果 name == 'ma​​in':

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-12-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-12-13
          • 1970-01-01
          相关资源
          最近更新 更多