可以使用一个循环来理解中前述彩票大奖有多难。为此,创建一个名为my_ticket的列表
或元组,再编写一个循环,不断地随机选择数或字母,直到中大奖为止。请打印一条消息,报
告执行多少次循环才中了大奖。
from random import choice
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'a', 'b', 'c', 'd']
lucky_lottery = []
my_ticket = []
for i in range(4):
value = choice(list1)
lucky_lottery.append(value)
print(f'幸运彩票号是:{lucky_lottery}')
n = 1
while True:
for s in range(4):
my_ticket.append(choice(list1))
if my_ticket == lucky_lottery:
print('恭喜你中奖了,中奖号是:{}'.format(lucky_lottery))
print('执行了{}次才中了大奖'.format(n))
break
else:
n += 1
my_ticket.clear()
continue
输出:
幸运彩票号是:[10, 3, 'b', 'c']
恭喜你中奖了,中奖号是:[10, 3, 'b', 'c']
执行了30100次才中了大奖
或者:
from random import choice
def get_lucky_lottery(list1):
# 先 生成中奖号码
lucky_lottery = []
for i in range(4):
values = choice(list1)
lucky_lottery.append(values) # 允许有重复数值
return lucky_lottery
def check_values(value, lucky_lottery):
# 检查是否每个数值都在中奖号码中
for element in value:
if element not in lucky_lottery:
return False
return True
def make_random_values(list1):
# 随机生成彩票
lucky_value = []
for i in range(4):
values = choice(list1)
lucky_value.append(values)
return lucky_value
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'a', 'b', 'c', 'd']
lucky_value = get_lucky_lottery(list1)
times = 0
won = False
max_tries = 1000000 # 设置允许最多运行几次
while not won:
new_ticket = make_random_values(list1)
won = check_values(new_ticket, lucky_value)
times += 1
if times >= max_tries:
break
if won:
print(f'生成了一个幸运票,你的幸运票是{new_ticket},幸运号是{lucky_value},这运行了{times}次')
else:
print(f'试了{times}次还是没有产生幸运号。你的号码是{new_ticket},彩票号是{lucky_value}')
输出:
生成了一个幸运票,你的幸运票是['d', 8, 'a', 'd'],幸运号是['a', 'b', 8, 'd'],这运行了109次