0

所以我最近做了这段代码,它应该能猜出你脑子里想的数字。

from random import shuffle

def guess(start,limit):
    nl = []
    for i in range(start,limit+1):
        nl.append(i)
    shuffle(nl)
    return nl[0]

def logic(start,limit):
    p = False
    while p == False:
        j = guess(start,limit)
        print 'Is your number %i?' % (j)
        a = raw_input('Too High (h) or Too Low (l) or True (t)?\n')
        if a.lower() == 'h':
            limit = j - 1
        elif a.lower() == 'l':
            start = j + 1
        elif a.lower() == 't':
            p = True
    return 'You\'re number was %i' % (j)

并且由于某种原因,即使在开始guess() 要求nl [0],有时当start 是54 并且limit 是56 时,Python 给了我这个错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 13, in logic
  File "<stdin>", line 8, in guess
IndexError: list index out of range

为什么会发生这种情况,我该如何阻止它发生?

4

2 回答 2

3

你的清单是空的;limit如果低于:它将为空start

>>> from random import shuffle
>>> guess(1, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in guess
IndexError: list index out of range
>>> guess(1, 1)
1

因为 then 生成range()的结果是一个空列表:

>>> range(1, 1)
[]

您需要在循环中对此进行测试;如果玩家撒谎并说猜测太高,而它确实正确或太低,那么你最终limit可能会低于start

请注意,random.shuffle()您可以只使用random.choice()从序列中选择一个值,而不是:

import random

def guess(start,limit):
    return random.choice(range(start, limit + 1))

但如果它是一个范围内的值只需使用random.randint()

def guess(start,limit):
    return random.randint(start, limit)

好消息是randint()在可供选择的可能值中包含最终值,因此您不必limit + 1在此处使用。

logic()稍微简化您的功能,guess()完全消除,并添加对startand的测试limit

import random

def logic(start, limit):
    while True:
        guess = random.randint(start, limit)
        print 'Is your number %i?' % guess
        answer = raw_input('Too high (h), too low (l) or true (t)?\n')
        if answer.lower() == 'h':
            limit = guess - 1
            if limit < start:
                print "I give up, I've run out of options"
                return
        elif answer.lower() == 'l':
            start = guess + 1
            if start > limit:
                print "I give up, I've run out of options"
                return
        elif answer.lower() == 't':
            return 'Your number was %i' % guess
于 2013-10-25T17:55:52.060 回答
0

如果您的 nl ​​数组为空,则不会得到 nl[0] 。

于 2013-10-25T17:55:09.170 回答