Random Choice在Python中不在列表范围内?

时间:2014-12-24 00:47:02

标签: python list python-2.7 random

我正在尝试创建一个程序来猜测您输入的数字。我试图让计算机尽可能少地猜测数字,所以我做的就是二元搜索。当我运行代码并且它到达total = total[the_low_one:computer2_guess]时,我不断使索引超出范围。我很困惑为什么它超出了范围。我应该在每次达到新的低点时向the_low_one添加或减去一个,以使其保持在范围内吗?因为我迷路了,我将不胜感激。提前谢谢! 代码:

def second_computer():
    global computer2_score
    computer2_score=0
    computer2_guess= -1
    the_low_one=1
    the_high_one=1000000
    total= range(1,1000000)
    while computer2_guess != pick_number:
        computer2_guess=random.choice(total)
        if computer2_guess>pick_number:
            total=total[the_low_one:computer2_guess]
            the_high_one=computer2_guess-1
        else:
            total=total[computer2_guess:the_high_one]
            the_low_one=computer2_guess+1
        computer2_score+=1

1 个答案:

答案 0 :(得分:1)

total缩小时,列表中的数值不再与其索引对齐。你可以通过

使它工作

total=total[total.index(the_low_one):total.index(the_high_one)]

更简单的方法是完全取消total并设置 computer2_guess=random.randint(the_low_one,the_high_one)