Last active
November 15, 2016 20:18
-
-
Save disconnect3d/ba119ab126c6978aefe484058d490abd to your computer and use it in GitHub Desktop.
"First steps programming exercise to add two binary numbers" lol
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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