[英]Random number generator comparing a list
Hi I am trying to compare a list of picked numbers to a list of randomly generated numbers.嗨,我正在尝试将选择的数字列表与随机生成的数字列表进行比较。 I want to know how many times it took to get the same numbers in the same sequence picked.
我想知道以相同的顺序选择相同的数字需要多少次。 I am using the choice() function which i have imported.
我正在使用我导入的choice() function。 Please see my code below.
请在下面查看我的代码。 I seem to continue to get an infinite loop and never generate the same list as "my ticket"
我似乎继续陷入无限循环,并且永远不会生成与“我的票”相同的列表
My code below我的代码如下
from random import choice
my_ticket = (9, 'z', 4, 0)
lottery_numbs = ['a', 'z', 'i', 't', 'u', 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
winning_numbers = []
picked_sequences = []
increment = 0
while True:
for pick in range(4):
pick = choice(lottery_numbs)
winning_numbers.append(pick)
if winning_numbers in picked_sequences:
continue
else:
picked_sequences.append(winning_numbers)
if my_ticket in picked_sequences:
print(increment)
break
else:
winning_numbers = []
print(increment)
increment += 1
print(winning_numbers)
print(my_ticket)
print(f"It took {increment} picks to pick my lottery numbers")
Think about the types of data that you're generating.考虑一下您正在生成的数据类型。 What is
choice(lottery_numbs)
returning?什么是
choice(lottery_numbs)
返回? What does winning_numbers
contain? winning_numbers
包含什么? What are you comparing it against?你拿什么来比较? If you have similar digits in different containers, you're not going to get a "match" unless you explicitly handle the containers.
如果您在不同的容器中有相似的数字,除非您明确处理容器,否则您不会得到“匹配”。
The following is my take on your code.以下是我对您的代码的看法。
Firstly, I changed your my_ticket
into winning_ticket
and made it into a list.首先,我将您的
my_ticket
更改为winning_ticket
并将其放入列表中。
Then I changed your filtering of duplicate numbers inside current_ticket into a while loop, to ensure that the ticket will always contain 4 unique characters.然后我将您对 current_ticket 中重复数字的过滤更改为 while 循环,以确保票证始终包含 4 个唯一字符。
Then I converted your while true loop into a while condition on if the current ticket is the same as winning ticket.然后,我将您的 while true 循环转换为当前票是否与中奖票相同的 while 条件。
Your main issue is the my_ticket
being a tuple, the other minor issues are redundant for loop to filter duplicate, no guarantee on current ticket having 4 characters, variable namings, etc.您的主要问题是
my_ticket
是一个元组,其他小问题对于循环过滤重复项是多余的,不能保证当前票证有 4 个字符、变量命名等。
from random import choice
winning_ticket = [9, 'z', 4, 0]
lottery_numbs = ['a', 'z', 'i', 't', 'u', 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
picks = 0
current_ticket = []
while current_ticket != winning_ticket:
current_ticket = []
while len(current_ticket) < 4:
pick = choice(lottery_numbs)
if pick not in current_ticket:
current_ticket.append(pick)
picks += 1
print(f"It took {picks} picks to pick my lottery numbers")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.