I made a simple algorithm for converting an integer into binary, and returning the binary as a string. Currently the bits are added to the front of a list. Would it be more efficient (in terms of either time or space) to concatenate strings at each step instead of appending to a list? Why/why not?
def toBinary(n):
l = []
while n > 0:
bit = n%2
n = math.floor(n/2)
l = [bit]+l
return ''.join(map(str,l))
I know an easier way to do the exact same thing would be to use:
bin(10)[2:]
(with the slice just taking off the prefix) but I wanted to try implementing the algorithm myself.
[edit] I see that append()
is more efficient than simple concatenation (from this post). What about appending at each step and then reversing the list? Or is there a similarly efficient function for adding to the beginning of the list (like insert()
)?