You've got enumerate
wrong. It starts form the MSB, so
for i, bit in enumerate('110'):
print (i, bit)
would yield (0, 1), (1, 1), (2, 0)
, not (0, 0), (1, 1), (2, 1)
.
Aside from that, some style suggestions:
- Please avoid using
;
in python. Search forCompound statements
on the page - Use list comprehensions if possible
- Either the comment is wrong, or you forgot to mention that you
multiply
operates on lists. If former - remove it, it's very confusing. If latter - your existing code wont work at all as there are no<<
operator defined on lists.
So, multiply
better written and fixed:
def multiply(a,b):
bitsa = reversed("{0:b}".format(a))
g = [(b<<i)*int(bit) for i,bit in enumerate(bitsa)]
return reduce(lambda x,y: x+y,g)
Also, as a final suggestion, why wouldn't you allow python do the things for you? It has built-in support for arbitrary long integers, so all your examples are equvivalent to just a*b
, or, if you want the result to be in binary form "{0:b}".format(a*b)