练习9.5 彩票分析

练习 9.14:彩票 创建⼀个列表或元素,其中包含 10 个数和 5 个字
⺟。从这个列表或元组中随机选择 4 个数或字⺟,并打印⼀条消息,
指出只要彩票上是这 4 个数或字⺟,就中⼤奖了。
练习 9.15:彩票分析 可以使⽤⼀个循环来理解中前述彩票⼤奖有多
难。为此,创建⼀个名为 my_ticket 的列表或元组,再编写⼀个循
环,不断地随机选择数或字⺟,直到中⼤奖为⽌。请打印⼀条消息,
报告执⾏多少次循环才中了⼤奖

from random import choice

def 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_ticket

def 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 False
    return True

def 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 ticket

possibilities = [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_000

while not won:
    new_ticket=make_random_ticket(possibilities)
    won=check_ticket(new_ticket,winning_ticket)
    plays+=1
    if 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}")

在这里插入图片描述

上一篇:Perl 语言开发(十五):调试和测试


下一篇:IT运维也有自己的节日 724向日葵IT运维节,三大版本如何选?