Skip to content

Instantly share code, notes, and snippets.

@disconnect3d
Last active November 15, 2016 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save disconnect3d/ba119ab126c6978aefe484058d490abd to your computer and use it in GitHub Desktop.
Save disconnect3d/ba119ab126c6978aefe484058d490abd to your computer and use it in GitHub Desktop.
"First steps programming exercise to add two binary numbers" lol
def add(b1, b2):
result = []
carry = 0
for i, j in zip(reversed(b1), reversed(b2)):
tmp = int(i) + int(j) + carry # 0, 1, 2
#print("i=%s, j=%s, carry=%d" % (i, j, carry))
carry = tmp / 2
tmp = tmp % 2
#print("new tmp=%d carry=%d" % (tmp, carry))
result.append(tmp)
if carry:
result.append('1')
result = ''.join(map(str, reversed(result)))
print("%s + %s = %s" % (b1, b2, result))
import itertools
nums = [''.join(i) for i in itertools.product('01', repeat=4)]
for bin1, bin2 in itertools.combinations_with_replacement(nums, r=2):
add(bin1, bin2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment