当前位置:   article > 正文

Python从入门到实践第九章习题9-15_python编程从入门到实践9-15

python编程从入门到实践9-15

9-15彩票分析是python第二版新加的题目,对于小白来说极为不友好。找了半天也没有找到这道题的答案,记录一下这次完成的答案。

from random import choice
def get_winning_ticket(possibilities):
    """摇出中奖组合。"""
    winning_ticket = []
    # 中奖组合中不能包含重复的数字或字母,因此使用了 while 循环。
    while len(winning_ticket) < 4:
        pulled_item = choice(possibilities)
 # 仅当摇出的数字或字母不在组合中时,才将其添加到组合中。
        if pulled_item not in winning_ticket:
            pulled_item = choice(possibilities)
            # 仅当摇出的数字或字母不在组合中时,才将其添加到组合中。
        if pulled_item not in winning_ticket:
            winning_ticket.append(pulled_item)
    return winning_ticket
def check_ticket(played_ticket, winning_ticket):
 # 检查彩票的每个数字或字母,只要有一个不在中奖组合中,就返回 False。
    for element in played_ticket:
        if element not in winning_ticket:
            return False
    # 如果代码执行到这里,就说明中奖了!
    return True
def make_random_ticket(possibilities):
    """随机地生成彩票。"""
    ticket = []
    # 彩票不能包含重复的数字或字母,因此使用了 while 循环。
    while len(ticket) < 4:
        pulled_item = choice(possibilities)

 # 仅当随机生成的数字或字母不在彩票中时,才将其添加到彩票中。
        if pulled_item not in ticket:
            ticket.append(pulled_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
# 为避免程序执行时间太长,设置最多随机生成多少张彩票。
max_tries = 1_000_000
while not won:
    new_ticket = make_random_ticket(possibilities)
    won = check_ticket(new_ticket, winning_ticket)
    plays += 1
    if plays >= max_tries:
        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}")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
'
运行
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/992880
推荐阅读
相关标签
  

闽ICP备14008679号