所以我试图模拟NBA的彩票,当我创建一个团队并尝试在for循环中为每个团队分配它的组合时,我在这一行中得到一个超出界限的pop索引:
combos.append(self.combinations.pop(randint(0,len(self.combinations))))
但是,如果我只是为其组合分配一个团队项目,则不会发生错误。当我尝试迭代地分配它的组合时会发生错误。
from Team import *
from LotteryMachine import *
"""Main class"""
lotteryMachine = LotteryMachine()
"""Initialize Teams"""
teams = [Team('Lakers', '81-0',1),Team('Wizards', '81-0',2)]
for team in teams:
team.combinations=
lotteryMachine.assignCombinations(team.numCombinations)
团队课程:
class Team():
combination_dict={1:250, 2:199, 3:156, 4:119, 5:88, 6:63, 7:43, 8:28, 9:17, 10:11, 11:8, 12:7, 13: 6, 14:5}
def __init__(self, name, record, standing):
self.name=name
self.record = record
self.standing = standing
self.numCombinations= Team.combination_dict[self.standing]
def __str__(self):
return self.name
彩票机类:
from random import *
class LotteryMachine():
def __init__(self):
self.combinations = list(self.createCombinations([x for x in range(1,15)],4))
self.deleteRandom()
self.copyCombinations = self.combinations
def combination(self,n,k):
return int(self.factorial(n)/(self.factorial(k)*self.factorial(n-k)))
def factorial(self,n):
assert n>=0
if n==0 or n==1:
return 1
return n*self.factorial(n-1)
def createCombinations(self,elements,length):
for i in range(len(elements)):
if length==1:
yield [elements[i],]
else:
for next in self.createCombinations(elements[i+1:len(elements)],length-1):
yield [elements[i],]+next
def deleteRandom(self):
self.combinations.pop(randint(0,len(self.combinations)))
def assignCombinations(self,length):
combos=[]
for x in range(length):
combos.append(self.combinations.pop(randint(0,len(self.combinations))))
return combos
#error occurs in above line
def drawCombinations(self):
combos=[]
for x in range(3):
combos.append(self.copyCombinations.pop(randint(0, len(self.copyCombinations))))
return combos
def __str__(self):
return "NBA Lottery Machine"
答案 0 :(得分:0)
randint
函数返回一个范围最大为的随机整数,包括上限。如果您希望它在列表中生成随机索引,您可能需要randrange
来代替,它从半开区间(包括下限,但不包括上限)中选择。