def dec2binr(n):
if n == 1:
return '1'
else: return (str(n%2)+dec2binr(n//2))[::-1]
Without the [::-1] it returns the reversed correct binary number. The [::-1] does not work in this case – for n=40 Ii get:
011000
when i would expect
101000
Without [::-1] I get
000101
Which is reversed, but correct.
Why does this happen and how can I fix it?
You need to reverse how you append the strings.
The issue is,
n%2will read the least significant bit, but you were appending it to the left of the string, which is the most significant place.