我开始在列表中编写前两个编程:
import random
def lottery_six():
setOfSix = set()
while len(setOfSix) < 6:
setOfSix.add(random.randint(1,49))
lottery = list(setOfSix)
return lottery
def generateLottery(lottery):
abc = set()
while (all(i >= 25 for i in lottery) == True) or (all(i < 25 for i in lottery) == True) or \
(sum(i >= 25 for i in lottery) >= 5) or (sum(i < 25 for i in lottery) >= 5):
abc = lottery_six()
return abc
print(generateLottery(lottery_six()))
然而,这不起作用。为什么?我该如何解决?
答案 0 :(得分:1)
import random
def lottery_six():
setOfSix = set()
while len(setOfSix) < 6:
setOfSix.add(random.randint(1,49))
lottery = list(setOfSix)
return lottery
def generateLottery(lottery):
abc = set(lottery) #Modified this Line
while (all(i >= 25 for i in lottery) == True) or (all(i < 25 for i in lottery) == True) or (sum(i >= 25 for i in lottery) >= 5) or (sum(i < 25 for i in lottery) >= 5):
abc = lottery_six()
return abc
print(generateLottery(lottery_six()))
答案 1 :(得分:1)
考虑到这一点,我们将重复此代码,直到找到一组合适的值。首先,我们将采用范围[1,49],我们将随机排序并获取前6个值。然后我们检查范围是否满足前两个要求中的任何一个。如果确实如此,我们就会打破循环并保留这个值列表。
while True:
x = (np.random.permutation(49)+1)[0:6]
if len([i for i in x if 1<=i<25]) > 4: break
if len([i for i in x if 25<=i<=49]) > 4: break
print(x)
您的整个代码可以写成
while True:
x = (np.random.permutation(49)+1)[0:6]
# Check for short
if len([i for i in x if 1<=i<25]) > 4: break
# Check for large
if len([i for i in x if 25<=i<=49]) > 4: break
# Check for even
if len([i for i in x if i%2 == 0]) > 5: break
# Check for odd
if len([i for i in x if (i+1)%2 == 0]) > 5: break
# Check for successive
if len([i for ix, i in enumerate(x[0:-2])
if (x[ix+1] - i == 1 and x[ix+2] - x[ix+1] == 1)]) > 0: break
print(x)
这将找到满足您条件的列表。最后一个语句有点密集,细分它会遍历列表中的每个值,并检查您是否至少有3个连续值x[ix+1] - i == 1 and x[ix+2] - x[ix+1] == 1
。如果这是真的,我们将值添加到列表中,如果最后在这个新列表中至少有1个值,我们可以得出结论,至少有3个连续值。
答案 2 :(得分:1)
您的代码似乎没有进入循环,您可以在while循环之前生成一个集合。这些行似乎也是多余的:
(all(i >= 25 for i in lottery) == True) or (all(i < 25 for i in lottery) == True)
最终代码:
def generateLottery(lottery):
lottery = lottery_six()
while sum(i >= 25 for i in lottery) >= 5 or sum(i < 25 for i in lottery) >= 5:
lottery = lottery_six()
return lottery
print(generateLottery(lottery_six()))