所以我的目标是让程序运行,以便继续绘制票据,直到找到与Winning Ticket匹配的票证。如果没有重复的门票,这将更好地工作,但我不知道如何实现它。
from __future__ import print_function
from datetime import date, datetime, timedelta
from random import randint
count = 0
class Ticket:
#Powerball Lottery Ticket Class'
def __init__(Ticket, ball1, ball2, ball3, ball4, ball5, pb):
Ticket.ball1 = ball1
Ticket.ball2 = ball2
Ticket.ball3 = ball3
Ticket.ball4 = ball4
Ticket.ball5 = ball5
Ticket.pb = pb
def displayTicket(Ticket):
print ("Ticket: ", Ticket.ball1, Ticket.ball2, Ticket.ball3,
Ticket.ball4, Ticket.ball5, Ticket.pb)
WinningTicket = Ticket(randint(0, 69), randint(0, 69), randint(0, 69),
randint(0, 69), randint(0, 69), randint(0, 26))
DrawnTicket = Ticket(randint(0, 60), randint(0, 60), randint(0, 60),
randint(0, 60), randint(0, 60), randint(0, 26))
#Winning Ticket
print("Powerball Ticket")
WinningTicket.displayTicket()
print("----------------")
#Draws a random ticket
def randomTicket():
DrawnTicket = Ticket(randint(0, 69), randint(0, 69), randint(0, 69),
randint(0, 69), randint(0, 69), randint(0, 27))
DrawnTicket.displayTicket()
return Ticket
#Draw Random Ticket Until DrawnTicket is = RandomTicket
while WinningTicket != DrawnTicket:
randomTicket()
count += 1
if WinningTicket == DrawnTicket:
break
#Number of DrawnTickets
print("Number of Drawn Ticket: ", count)
答案 0 :(得分:1)
根据PowerBall的规则,你必须从1-69的数字中抽取5个随机数,包括没有替换的数字,你必须从1-26中包含的数字中抽取一个数字。要赢得累积奖金,您必须匹配红色强力球号码,并按任意顺序匹配前5个号码,这意味着您正在寻找那里的组合,而不是排列。
由此,我对您的代码进行了调整,以便查看数字组合,并定义了__eq__()
魔术方法,以便比较运算符可以按预期工作。为了检查重复的数字,我基本上有一个存储数字列表的列表,每当我们生成一个新的数字列表时,我们只需检查它是否在返回之前不在列表中,否则我们将其清除并再试一次。
以下是反映这些调整的代码:
from __future__ import print_function
from datetime import date, datetime, timedelta
from random import randint
count = 0
class Ticket:
# Powerball Lottery Ticket Class'
def __init__(self, numbers):
self.wb = numbers[:5]
self.pb = numbers[5]
def displayTicket(self):
print("Ticket: ", self.wb[0], self.wb[1], self.wb[2], self.wb[3], self.wb[4], self.pb)
def __eq__(self, other):
if isinstance(other, Ticket):
return set(self.wb) == set(other.wb) and self.pb == other.pb
else:
return False
checkedNumbers = []
# Draws a random ticket
def randomTicket():
numbers = []
while True:
if len(numbers) < 5:
numbers.append(randint(0,69))
else:
numbers.append(randint(0, 26))
if numbers in checkedNumbers:
numbers = []
elif len(numbers) == 6:
break
DrawnTicket = Ticket(numbers)
DrawnTicket.displayTicket()
checkedNumbers.append(numbers)
return DrawnTicket
WinningTicket = randomTicket()
checkedNumbers.remove([number for number in WinningTicket.wb] + [WinningTicket.pb])
# Winning Ticket
print("Powerball Ticket")
WinningTicket.displayTicket()
print("----------------")
# Draw Random Ticket Until DrawnTicket is = RandomTicket
while True:
DrawnTicket = randomTicket()
count += 1
if WinningTicket == DrawnTicket:
break
# Number of DrawnTickets
print("Number of Drawn Ticket: ", count)
该计划将按预期运作。但是,就像TigerhawkT3试图暗示的那样,这个程序将花费很长时间非常。你试图通过292,201,338组合数字来蛮力,通过随机生成数字,这将产生大量的重复,而不是你通过每一个组合增加你的方式。即使这样,它仍然需要很长时间。