2015-02-04 2 views
1

파이썬에서 간단한 바이너리 추가 프로그램을 작성하려고합니다. 파이썬이 이미 그것을 할 수 있다는 것을 알고 있습니다. 기본적인 컴퓨팅 개념을 연습하기 위해 노력하고 있습니다.프로그램 추가가 작동하지 않습니다.

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

당신이 만약 : 나는 이상한 유일한 것은 숫자 중 하나가 더 이상 다른보다 0에서 시작하는 경우, 프로그램이 예상 된 결과를 반환하지 않는다는 것입니다 꽤 잘 작동있어 다음 번호가 인쇄됩니다 프로그램 실행 : 마지막 줄에

10101111 
100001 
10 
1000 
1000 
100101000 

두 번째 000101000를 반환해야합니다을 대신 그것은 1000를 반환합니다. 하지만 우리가 마지막 줄에서 볼 수 있듯이 숫자가 1에서 시작하면 제대로 작동합니다.

왜 이런 일이 발생하는지 알고 있습니까?

대단히 감사합니다.

답변

2

변화

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

당신의 상태는 파이썬이 길이를 ASCII 값을 비교하는 가정 및되지 않음을 의미합니다. 0이 1보다 작다는 것을 알다시피, 그 특별한 경우에 그것은 당신에게 당신이 기대하는 것을주지 않을 것입니다. 길이 비교는 원하는 것입니다.

Marcin이 제안했듯이이를 수행하는 더 좋은 방법이 있습니다.

0

이것은 사용자의 특정 코드가 작동하지 않는 이유, 즉 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 
0
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)  

이름 경우 == '주요'

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