0

So in uni we learned how to multiplicate 2 binary codes. After trying in Python and getting the right result, i wanted to know if i can improve my code with less if statements or if i made any major mistakes without recognising.

l1 = [1,1,0,1,1]
l2 = [1,0,0,0,0]
brack = 0

result = []
for i in range(len(l1)):
    if l1[i] + l2[i] == 2:
        result.append(0)
        brack +=1
    elif (l1[i] + l2[i] == 1) and (brack == 0):
        result.append(1)
    elif (l1[i] + l2[i] == 1) and (brack == 1):
        result.append(0)
        brack -= 1
    elif(l1[i] + l2[i] == 0) and (brack == 1):
        result.append(0)
        brack -= 1
    elif(l1[i] + l2[i] == 0) and (brack == 0):
        result.append(0)
if (result[-1] == 0):   
    result.append(1)      
    
print(result)
2
  • Isn't this binary addition? Commented Oct 6, 2022 at 13:07
  • Yes binary addition of the two lists Commented Oct 6, 2022 at 14:23

1 Answer 1

1

You should be able to make the bitwise addition without any ifs, but rather using modulo and division:

l1 = [1,1,0,1,1]
l2 = [1,0,0,0,0]
brack = 0

result = []
for i in range(len(l1)):
    s = l1[i] + l2[i] + brack
    result.append(s % 2)
    brack = s / 2
if (brack > 0):   
    result.append(1)      
    
print(result)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.