简单抽奖:生成1到49之间的新六个唯一随机数

时间:2018-03-19 05:23:49

标签: python random integer

  • 如果有五个“短号”或者所有六个都是“短号”(短号是1 <=数字<25)
  • 如果有五个“大数字”或全部六个是“大数字”(大数字定义为25 <=数字<= 49)
  • 如果六个数字中至少有五个是
  • 如果六个数字中至少有五个是奇数
  • 如果至少有三个数字是连续的数字(例如,[13,14,15,28,35,49] - >抽取新的六个。或者另一个例子是例如,[5,6,7,8, 21,38] - &gt;绘制新的六个数字)

我开始在列表中编写前两个编程:

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()))

然而,这不起作用。为什么?我该如何解决?

3 个答案:

答案 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()))