如何确保这些号码一旦使用后不再打印?

时间:2016-03-11 13:02:11

标签: python

此代码必须能够识别已使用的数字,因此不会再次打印。

def Bingo():                    
    import random
    import time

    while True:
        try:

            command = input("Do you want to generate a number Y/N: ")
        except:
            print("You colossal spanner")

        if command.lower() == "y":

            text_file = open("Cache.txt", "a")

            text_file.write("Numbers Used \n")

            print("Welcome to the Bingo number generator")

            UserNumber = str((random.randint(1,90)))

            print(UserNumber)

            text_file.write (UserNumber)

            text_file.close()

        elif command.lower == "N":
            print("Try generating another one: ")

Bingo()

text_file.close()

3 个答案:

答案 0 :(得分:3)

您可以列出所有可用号码,并从中删除已生成的号码。您可以在这些数字的列表中生成索引,而不是生成数字。这将使这一代确定性:

numbers = list(range(1, 90))

def Bingo():
    import random
    import time

    while True:
        try:
            command = input("Do you want to generate a number Y/N: ")
        except:
            print("You colossal spanner")
        if command.lower() == "y":
            text_file = open("Cache.txt", "a")
            text_file.write("Numbers Used \n")
            print("Welcome to the Bingo number generator")

            remaining_numbers = len(numbers)
            if remaining_numbers == 0:
                print('No more numbers')
                exit(-1)
            index = random.randrange(remaining_numbers)
            user_number = numbers.pop(index)
            print(user_number)
            text_file.write (str(user_number))
            text_file.close()

        elif command.lower == "N":
            print("Try generating another one: ")

Bingo()

text_file.close()

答案 1 :(得分:1)

我建议您生成这样的数字:

numbers = range(1,90)

然后在宾果游戏做这样的事情来得到下一个数字:

number = random.randrange(len(numbers))
v = numbers.pop(number)
print v

您可以检查是否可以提取其他数字来检查数字的长度,如下所示:

len(numbers) > 0

生成函数内的数字,这样每次调用Bingo()时,都会有一个新的数字列表在游戏中使用。

答案 2 :(得分:0)

您需要列出已使用的数字,当您说UserNumber = str((random.randint(1,90)))时,请将其放在while循环中,然后将其添加到数字列表中:

def Bingo():                    
    import random
    import time

    used = []
    while True:
        try:
            command = input("Do you want to generate a number Y/N: ")
        except:
            print("You colossal spanner")

        if command.lower() == "y":
            text_file = open("Cache.txt", "a")
            text_file.write("Numbers Used \n")

            print("Welcome to the Bingo number generator")

            UserNumber = None
            while UserNumber is None or UserNumber in used:
                UserNumber = str((random.randint(1,90)))

            used.append(UserNumber)
            print(UserNumber)
            text_file.write (UserNumber)
            text_file.close()

        elif command.lower == "N":
            print("Try generating another one: ")

Bingo()

text_file.close()