通过调用random模块、定义函数、使用循环来简单模拟彩票大奖有多难中奖!这里我根据是否需要考虑号码顺序分成了两种情况。在不超过规定的最大抽奖次数的情况下,打印出循环了多少次才中奖或者一直没有中奖。
大致分为4个步骤:
1.定义中奖号码(假设是4位数)
2.定义彩票号码
3.识别是否中奖
4.导入数据,进行判断并输出结果(可以设置最大抽奖次数)
考虑号码顺序
#考虑号码顺序from random import randintdef win(possibilities):"""定义中奖号码"""winning_ticket = []while len(winning_ticket) < 4:one = choice(possibilities)if one not in winning_ticket:winning_ticket.append(one)return winning_ticketdef choose(possibilities):"""定义彩票号码"""choose_ticket = []while len(choose_ticket) < 4:one = choice(possibilities)if one not in choose_ticket:choose_ticket.append(one)return choose_ticketdef identify(winning_ticket, choose_ticket, order = False):"""识别彩票是否中奖,order参数默认不考虑号码顺序"""if order == False: for i in choose_ticket:if i not in winning_ticket:return Falsereturn Trueelif order == True:if choose_ticket == winning_ticket:won = Trueelse:won = Falsereturn wonpossibilities = [1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f']
winning_ticket = win(possibilities)max_times = 10_000
flag = True
times = 0while flag:times += 1choose_ticket = choose(possibilities)won = identify(winning_ticket, choose_ticket, order = True)if times > max_times:print('很遗憾,你的次数已用完了仍然没有中奖!')breakelse:if won:print(f'恭喜你中奖了!中奖号码为{winning_ticket},你的号码为{choose_ticket},你一共抽了{times}次!')flag = False
输出结果:
恭喜你中奖了!中奖号码为[2, ‘a’, 6, ‘e’],你的号码为[2, ‘a’, 6, ‘e’],你一共抽了8645次!
不考虑号码顺序
#不考虑号码顺序from random import randintdef win(possibilities):"""定义中奖号码"""winning_ticket = []while len(winning_ticket) < 4:one = choice(possibilities)if one not in winning_ticket:winning_ticket.append(one)return winning_ticketdef choose(possibilities):"""定义彩票号码"""choose_ticket = []while len(choose_ticket) < 4:one = choice(possibilities)if one not in choose_ticket:choose_ticket.append(one)return choose_ticketdef identify(winning_ticket, choose_ticket, order = False):"""识别彩票是否中奖,order参数默认不考虑号码顺序"""if order == False: for i in choose_ticket:if i not in winning_ticket:return Falsereturn Trueelif order == True:if choose_ticket == winning_ticket:won = Trueelse:won = Falsereturn wonpossibilities = [1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f']
winning_ticket = win(possibilities)max_times = 10_000
flag = True
times = 0while flag:times += 1choose_ticket = choose(possibilities)won = identify(winning_ticket, choose_ticket, order = False)if times > max_times:print('很遗憾,你的次数已用完了仍然没有中奖!')breakelse:if won:print(f'恭喜你中奖了!中奖号码为{winning_ticket},你的号码为{choose_ticket},你一共抽了{times}次!')flag = False
输出结果:
恭喜你中奖了!中奖号码为[7, 1, ‘d’, 3],你的号码为[‘d’, 3, 7, 1],你一共抽了1054次!