练习 9.14:彩票 创建⼀个列表或元素,其中包含 10 个数和 5 个字
⺟。从这个列表或元组中随机选择 4 个数或字⺟,并打印⼀条消息,
指出只要彩票上是这 4 个数或字⺟,就中⼤奖了。
练习 9.15:彩票分析 可以使⽤⼀个循环来理解中前述彩票⼤奖有多
难。为此,创建⼀个名为 my_ticket 的列表或元组,再编写⼀个循
环,不断地随机选择数或字⺟,直到中⼤奖为⽌。请打印⼀条消息,
报告执⾏多少次循环才中了⼤奖
from random import choicedef get_winning_ticket(possibilities):"""Return a winning ticket from a set of possibilities."""winning_ticket = []while len(winning_ticket) < 4:item = choice(possibilities)if item not in winning_ticket:winning_ticket.append(item)return winning_ticketdef check_ticket(player_ticket,winning_ticket):"""Check all elements in the played ticket. If any are not in the winning ticket, return False."""for item in player_ticket:if item not in winning_ticket:return Falsereturn Truedef make_random_ticket(possibilities):"""Make a random ticket from a set of possibilities"""ticket=[]while len(ticket)<4:item=choice(possibilities)if item not in ticket:ticket.append(item) return ticketpossibilities = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "a", "b", "c", "d", "e"]
winning_ticket=get_winning_ticket(possibilities)plays=0
won=False
times=1_000_000while not won:new_ticket=make_random_ticket(possibilities)won=check_ticket(new_ticket,winning_ticket)plays+=1if plays>=times:break
if won:print("We have a winning ticket!")print(f"Your ticket: {new_ticket}")print(f"Winning ticket: {winning_ticket}")print(f"It only took {plays} tries to win!")
else:print(f"Tried {plays} times, without pulling a winner. :(")print(f"Your ticket: {new_ticket}")print(f"Winning ticket: {winning_ticket}")