gpt4 book ai didi

python - 产生重复数字的宾果卡

转载 作者:行者123 更新时间:2023-12-04 02:36:20 24 4
gpt4 key购买 nike

我创建了一个简单的宾果卡生成器,它生成 nn+15 之间的 4 个数字。但是,我注意到数字有时会生成两次,尽管我写了一个 if 语句,该语句应该找到重复项并重新运行该单元格的随机生成。我的代码如下:

import random

ballCount = 75 # Max value of cell
gridWidth = 4
gridHeight = 5
numPerCard = 20 # Numbers generated per card
minimum = 1
maximum = 15


def generate_number(stored, small_num, big_num):
random.seed(a=None, version=2)
random_number = str(random.randint(small_num, big_num))
if "| "+random_number+" |" in stored:
generate_number(stored, small_num, big_num)
return random_number


for row in range(gridHeight):
string = ""
for Number in range(gridWidth):
number = generate_number(string, minimum, maximum)
string += " | " + number
string += " |"
print(string)
maximum += 15
minimum += 15

这里是一个带有重复项的输出示例(23 出现了 2 次):

 | 2 | 5 | 9 | 12 |
| 25 | 23 | 19 | 23 |
| 37 | 42 | 30 | 37 |
| 60 | 49 | 50 | 55 |
| 73 | 71 | 69 | 67 |

最佳答案

    if "| "+random_number+" |" in stored:
generate_number(stored, small_num, big_num)
return random_number

如果您已经有了该号码,则再次调用 generate_number,但您仍会返回原始号码(重复号码)。

您可能对 random.sample 感兴趣,将其作为在一定范围内随机选择唯一数字的替代方法。例如:

>>> [random.sample(range(n, n+15), 4) for n in range(15, 75, 15)]
[[20, 26, 15, 23], [37, 44, 32, 40], [48, 45, 47, 50], [63, 62, 68, 71]]

或者,使用 pretty-print :

>>> for row in [random.sample(range(n, n+15), 4) for n in range(15, 75, 15)]:
... print(f"| {' | '.join(map(str, row))} |")
...
| 17 | 15 | 27 | 22 |
| 34 | 33 | 42 | 36 |
| 54 | 51 | 55 | 48 |
| 68 | 73 | 61 | 72 |

关于python - 产生重复数字的宾果卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61688203/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com