我想我的问题不在于方法,而在于切片列表(例如列表 [2:5])。当代码实际运行时,它并没有在正确的位置切割列表。该程序试图猜测用户给它的数字。它是使用随机模块执行此操作的,我知道这可能不是最好的方法,但我正在试验。
编码:
import random
number = input('Pick a number from 1-100 for the computer to guess, \nand find out how many tries it takes the computer: ')
print number
possibilities = range(101)
del possibilities[0]
tries = 1
guess = random.choice(possibilities)
print "\n", guess
while guess != number:
if guess > number:
possibilities = possibilities[:(guess-1)]
else:
possibilities = possibilities[(guess-1):]
print possibilities
guess = random.choice(possibilities)
print guess
tries += 1
错误示例:
程序的输出,来自上面的打印语句。我还想提一下,它并不总是出现故障,大约 50-60% 的时间可以正常工作。此外,不仅仅是我输入的数字,例如,45 可能工作正常,或者可能会像下面那样失败,这似乎是一个非常随机的事件。
初始输入 45:
45
30 [30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79、80、81、82、83、84、85、86、87、88、89、90、91、92、93、94、95、96、97、98、99、100]
88 初始错误(程序应该在 88 之后切断列表) [30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97、98、99、100]
54 [30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82] 40 致命错误(它切断了列表,删除了它正在“寻找”的数字)[69,70,71,72,73,74,75,76,77,78, 79, 80, 81, 82] 72 [69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82]
初始输入 6:
6
48
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47]
9
[1, 2, 3, 4, 5, 6, 7, 8]
5 **Initial Error** (the program should have eliminated 5 from the list below this line)
[5, 6, 7, 8]
5 **Fatal Error** (the program deleted the rest of the list)
[]
Traceback (most recent call last):
File "C:\Users\Joseph\Documents\Programming fun\computer guessing a number game.py", line 32, in <module>
guess = random.choice(possibilities)
File "C:\Python27\lib\random.py", line 274, in choice
return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty
IndexError: list index out of range
我想知道 Python 为什么要这样做,以及它是否可以避免。我不认为我的代码有问题,在我看来,Python 只是没有按应有的方式工作,但我对编程非常陌生,所以我不确定我是否遗漏了什么。
感谢您提供的任何帮助。