我的代码是测试我试图弄清楚为什么p & ~(p & (p - 1))不测试2的指数.无论如何,解释器in = 1因为某种原因不喜欢while循环之前.
码:
def getnumber(str):
num=0
for i in str:
zz = ord(i)-48
if zz<0 or zz>9:
num=-1
break
else:
num=(num*10)+zz
return num
def testexp2(p):
table = {1:1,2:2,4:3,8:4,16:5,32:6,64:7,128:8,256:9}
if p & ~(p & (p - 1)):
print "yes"
else:
print "no"
in = 1
while in is not -1:
in = raw_input("> ")
in = getnumber(in)
if in>-1:
testexp2(in)
else:
print "\nDone\n\n"
Run Code Online (Sandbox Code Playgroud)
几个问题:
in 是python中的保留关键字,因此您不能将其用作变量名.while inp is not -1应该是while inp != -1.(我用的是inp代替in)getnumber功能可以简化为:码:
def getnumber(strs):
num = int(strs)
return -1 if num < 0 else num
Run Code Online (Sandbox Code Playgroud)