简单彩票:产生新的6个唯一的随机数1到49

2024-10-03 21:35:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

然而,这并不奏效。为什么?我怎样才能修好它呢?在


Tags: orinltforreturndef数字random
3条回答
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()))

你的代码似乎没有进入循环,你可以在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()))

考虑到这一点,我们将重复这段代码,直到找到一组合适的值。首先,我们取范围[1,49],然后随机排序,取前6个值。如果满足第一个要求,则检查2。如果是这样,我们就打破循环,保留这个值列表。在

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)

整个代码可以写成

^{pr2}$

这将找到满足您条件的列表。最后一个语句有点密集,它会遍历列表中的每个值并检查是否至少有3个连续的值x[ix+1] - i == 1 and x[ix+2] - x[ix+1] == 1。如果这是真的,我们将值添加到列表中,如果在这个新列表的末尾至少有1个值,我们可以得出结论,至少有3个连续的值。在

相关问题 更多 >