调用随机整数时为什么会出现值错误?

时间:2019-06-29 20:58:19

标签: python

我正在编写一个程序,您在其中输入“听我说”这样的短语,并输出一个字谜短语。例如:“下摆耳朵”。我写的一个函数t = RandomWordofLength遇到了问题。致电randint时,我不断收到值错误。我通过创建一个名为test_random_word的脚本来隔离问题。谁能解释这个错误的根源?

import random

def CreateDictionary(text):
    """
    :param text: A txt file of English words, one word per line.
    :return: Dictionary with keys: "2", "3", "4", ..."12" denoting the length of the words, and values are lists of
    words with the appropriate length.
    """
    dict = {"2": [], "3": [], "4": [], "5": [], "6": [], "7": [], "8": [], "9": [], "10": [], "11": [], "12": []}
    with open(text, "r") as fileObject:
        for line in fileObject:
            if 1 < len(line.strip()) < 12:
                dict[str(len(line.strip()))].append(line.strip())

    return dict


def FindRandonmWordofLength(dict, length):
    """
    :param dict: a dictionary constructed from the CreateDictionary function.
    :param length: an integer value between 3 and 12, including endpoints.
    :return: a random word from the dictionary of the requested length.
    """
    length_of_list = len(dict[str(length)])
    random_num = random.randint(1, length_of_list - 1)
    return dict[str(length)][random_num]

dict = CreateDictionary("20k.txt")

for i in range(1000000):
    random_length = random.randint(3, 12)
    word = FindRandonmWordofLength(dict, random_length)

    print("The random word is: " + word)

我经常看到此错误。

  

返回self.randrange(a,b + 1)文件   “ C:\ Users \ kevoh \ AppData \ Local \ Programs \ Python \ Python37-32 \ lib \ random.py”,   兰德兰奇第200行       引发ValueError(“ randrange()的空范围(%d,%d,%d)”%(istart,istop,width))ValueError:randrange()的空范围(1,0,   -1)

1 个答案:

答案 0 :(得分:1)

使用random.randint(a, b)时,必须确保a <= b,否则将导致错误empty range for randrange()。我的最佳猜测是,您没有仔细检查是否在向random.randint()的调用中传递了有效参数。例如,如果是length_of_list == 1,那么您刚刚调用了random.randint(1, 0),它将准确给出您得到的错误消息。也许您可以尝试random_num = random.randint(0, length_of_list - 1),因为python列表索引从0开始,避免了这个问题。

如果您的预期行为是从1开始的间隔中获取随机整数(此处似乎不是这种情况),请相应地调整第二个参数。