def in_binary(n):
if n == 0:
return [] # base case
else:
digit = n & 0x1 # bit mask
return in_binary(n >> 1) + [digit] # recursion
def from_binary(b):
# add value of each digit, using enumerate to get its place
# list comprehensions are Pythonic
return sum([(2**place) * value
for place, value in enumerate(b)])
two = in_binary(2)
print from_binary(two + two)
ZGVmIGluX2JpbmFyeShuKToKICAgIGlmIG4gPT0gMDoKICAgICAgICByZXR1cm4gW10gIyBiYXNlIGNhc2UKICAgIGVsc2U6CiAgICAgICAgZGlnaXQgPSBuICYgMHgxICMgYml0IG1hc2sKICAgICAgICByZXR1cm4gaW5fYmluYXJ5KG4gPj4gMSkgKyBbZGlnaXRdICMgcmVjdXJzaW9uCgpkZWYgZnJvbV9iaW5hcnkoYik6CiAgICAjIGFkZCB2YWx1ZSBvZiBlYWNoIGRpZ2l0LCB1c2luZyBlbnVtZXJhdGUgdG8gZ2V0IGl0cyBwbGFjZQogICAgIyBsaXN0IGNvbXByZWhlbnNpb25zIGFyZSBQeXRob25pYwogICAgcmV0dXJuIHN1bShbKDIqKnBsYWNlKSAqIHZhbHVlCiAgICAgICAgICAgICAgICBmb3IgcGxhY2UsIHZhbHVlIGluIGVudW1lcmF0ZShiKV0pCgp0d28gPSBpbl9iaW5hcnkoMikKcHJpbnQgZnJvbV9iaW5hcnkodHdvICsgdHdvKQ==