8

我有以下代码,我从标准输入中获取整数 n,将其转换为二进制,反转二进制字符串,然后转换回整数并输出。

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()

但是,我收到此错误:

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

我不确定问题是什么。

4

4 回答 4

9

您正在将字符串传递给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)
于 2013-05-31T23:30:41.757 回答
4

您想将输入转换为整数而不是字符串 - 它已经是字符串。所以这一行:

n = str(raw_input())

应该是这样的:

n = int(raw_input())
于 2013-05-31T23:30:42.317 回答
1

它是原始输入,即一个字符串,但您需要一个 int:

bin_n = bin(int(n))
于 2013-05-31T23:32:04.527 回答
0

bin将整数作为参数并且您将字符串放在那里,您必须转换为整数:

import sys

def reversebinary():
  n = int(raw_input())
  bin_n = bin(n)[2:]
  revbin = "".join(list(reversed(bin_n)))
  return int(str(revbin),2)

reversebinary()
于 2013-05-31T23:35:47.533 回答