gpt4 book ai didi

python - 猜号机 : Please Review and Make it More Pythonic

转载 作者:太空宇宙 更新时间:2023-11-04 07:25:34 25 4
gpt4 key购买 nike

我正在学习 python,这是一个简单的程序,我写道:

def guesser(var, num1,possible):
if var == 'n':
cutoff = len(possible)/2
possible = possible[0:cutoff]
cutoff = possible[len(possible)/2]
#print possible

if (len(possible) == 1):
print "Your Number is:", possible
else:
var = raw_input("Is Your Number Bigger Than %s? (y/n): " %cutoff)
guesser(var, cutoff,possible)


elif var == 'y':
cutoff = len(possible)/2
possible = possible[cutoff:len(possible)]
cutoff = possible[len(possible)/2]
#print possible
#print cutoff

if (len(possible) == 1):
print "Your Number is:", possible
else:
var = raw_input("Is Your Number Bigger Than %s? (y/n): " %cutoff)
guesser(var, cutoff,possible)


else:
var = raw_input("Is Your Number Bigger Than 50? (y/n): ")
guesser(var, 50, possible)

possible = []
possible = range(1,101)

guesser('a', 50, possible)

最佳答案

通常我会尝试帮助您编写代码,但是您方式太复杂了,我认为您查看一些代码会更容易。

def guesser( bounds ):
a, b = bounds
mid = ( a + b ) // 2

if a == b: return a

if input( "over {0}? ".format( mid ) ) == "y":
new_bounds = ( mid, b )
else:
new_bounds = ( a, mid )

return guesser( new_bounds )

在深入研究之前,您应该从抽象的角度考虑您的算法将如何工作。

编辑:以简洁为代价简化了代码。

关于python - 猜号机 : Please Review and Make it More Pythonic,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3472124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com