您正在将字符串传递给bin()函数:
>>> bin('10')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an index
给它一个整数来代替:
>>> bin(10)
'0b1010'
通过将raw_input()结果转换为int():
n = int(raw_input())
提示:您可以通过给负片跨度轻松地反转字符串:
>>> 'forward'[::-1]
'drawrof'
因此您可以将功能简化为:
def reversebinary():
n = int(raw_input())
bin_n = bin(n)[2:]
revbin = bin_n[::-1]
return int(revbin, 2)
甚至:
def reversebinary():
n = int(raw_input())
return int(bin(n)[:1:-1], 2)
相关分类