《Python编程从⼊门到实践第⼆版》第九章练习9-15分析
dw网站模板下载aspect名词答案
到图书提供的标准答案了,分享给⼤家
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:
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 = 0python数据分析基础教程答案
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}")
我做的那个中奖顺序必须⼀样才能中奖,这个只要4个相同,不需要顺序⼀样,运⾏结果如下:
动漫网页制作源代码We have a winning ticket!
Your ticket: [2, 1, 'e', 'a']
Winning ticket: ['a', 1, 'e', 2]
It only took 2082 tries to win!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论