猜数字者:请复习一下,让它更像Python

2024-05-19 02:25:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习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)

Tags: numberinputyourrawlenifisvar
3条回答

通常我会尝试帮助您编写代码,但您已经使它变得非常复杂,我认为您可以更容易地查看一些代码。在

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之前,我可能会让它更简单。。。这个算法比必要的复杂得多。当两个整数足够时,不需要使用列表。在

def guesser(low = 0, up = 100):
    print("Choose a number between %d and %d" % (low, up-1))
    while low < up - 1:
        mid = (low+up)//2
        yn = raw_input("Is Your Number Smaller Than %s? (y/n): " % mid)
        if yn not in ['y', 'n']: continue
        low, up =  (low, mid) if yn == 'y' else (mid, up)
    print "Your Number is:", low


guesser()

更多的python使用bisect模块,当然还有class模块:)

import bisect    
hival= 50

class Guesser(list):
    def __getitem__(self, idx):
        return 0 if raw_input("Is your number bigger than %s? (y/n)"%idx)=='y' else hival

g=Guesser()
print "Think of a number between 0 and %s"%hival
print "Your number is: %s"%bisect.bisect(g,0,hi=hival)

下面是python库中bisect.bisect的定义。如您所见,大多数算法都是在这里为您实现的

^{pr2}$

相关问题 更多 >

    热门问题