I have the following piece of code where I take in an integer n from stdin, convert it to binary, reverse the binary string, then convert back to integer and output it.
import sys
def reversebinary():
n = str(raw_input())
bin_n = bin(n)[2:]
revbin = "".join(list(reversed(bin_n)))
return int(str(revbin),2)
reversebinary()
However, I'm getting this error:
Traceback (most recent call last):
File "reversebinary.py", line 18, in <module>
reversebinary()
File "reversebinary.py", line 14, in reversebinary
bin_n = bin(n)[2:]
TypeError: 'str' object cannot be interpreted as an index
I'm unsure what the problem is.
You want to convert the input to an integer not a string - it's already a string. So this line:
should be something like this:
You are passing a string to the
bin()
function:Give it a integer instead:
by turning the
raw_input()
result toint()
:Tip: you can easily reverse a string by giving it a negative slice stride:
so you can simplify your function to:
or even:
It is raw input, i.e. a string but you need an int:
bin
takes integer as parameter and you are putting string there, you must convert to integer: