teamathematic teamathematic - 6 months ago 26
Python Question

Where am I going wrong in this python code for CLRS exercise 2.1-4

So the problem is:
"Consider a problem of adding two n-bit binary integers, stored in two n-element arrays A and B. The sum of the two integers should be stored in binary form in an (n+1)-element array C. State the problem formally and write pseudocode for adding the two integers."

and my python code for this problem is:

A = [1,0,1,1,0,1,0]
B = [1,1,1,0,1,0,0]
n = len(A)
C = [0,0,0,0,0,0,0,0]

for i in range(0, n):
C[i] = A[i] + B[i] + C[i]
if C[i] == 2:
C[i] = 0
C[i+1] == 1
elif C[i] == 3:
C[i] = 1
C[i+1] = 1


print C


Also I have taken the least significant digits on the left which I can reverse after I've done the calculation.

I cant figure out what the mistake is please help!

Answer

C[i+1] == 1 does a comparison, not an assignment.

Comments