0

Why is my code giving an error??

Write a function that reverses the bits in an integer. For example, the number 417 is 110100001 in binary. Reversing the binary is 100001011 which is 267. You can assume that the number is not negative. Here Is my code and it gives me an error...Please explain why! def reverse_bits(n): b = bin(n) rem = b.replace('0b', '') integer = int(rem[::-1]) lst = list(str(integer)) x = len(lst) for i in range(lst[x]): return lst[i+1] * 2**x-1

22nd Jun 2021, 9:19 PM
Ailana
Ailana - avatar
4 ответов
+ 2
At line ,"for i in range(lst[x]) :" x holds the length of lst and u are then using that as an index for lst which obviously will give an indexError since the maximum index in lst will be len(lst)-1.
22nd Jun 2021, 9:35 PM
Abhay
Abhay - avatar
+ 1
You don't need to convert the binary string into list. Once you have stripped off the binary sign '0b', you just need to reverse the string, then pass it on to int() function, providing the second argument which represents the base of the first argument (binary string) def reverse_bits( n : int ): try: return int( bin( int( n ) ) [ 2 : ][ : : -1 ], 2 ) except( ValueError, TypeError ): return 0 print( reverse_bits( 417 ) )
23rd Jun 2021, 2:09 AM
Ipang
0
Then what should i put as the index in the for loop?
22nd Jun 2021, 9:37 PM
Ailana
Ailana - avatar
0
You should simply have x instead of lst[x]. Even after doing so you will get few more errors , so i rewrote the code . def reverse_bits(n): b = bin(n) rem = b.replace('0b', '') lst=[int(i) for i in rem] x = len(lst) return sum(lst[i] * 2**i for i in range(x-1,-1,-1))
22nd Jun 2021, 10:05 PM
Abhay
Abhay - avatar