python - 在不使用列表、集合等的情况下在 Python 中生成唯一数字

标签 python loops numbers unique

这是一个带回家的测试题(我在 20 分钟前寄出,如果 Gruhn 教授正在无情地搜索 stackoverflow)。第一门计算机科学类(class),介绍使用 Python。使用“Python 入门第 2 版”一书。测试基本上是关于创建我们自己的模块库、读取和写入文件以及 try/except 逻辑。

第一部分要求创建彩票号码模拟器。一个生成非唯一数字,另一个生成唯一的非重复数字。我在这里看到的每个答案都使用了列表,很遗憾,这是下一章,我们被明确禁止使用它们。

我这部分的代码:

import random

def ballPickerOne():
    a = random.randint(1, 59)
    b = random.randint(1, 59)
    c = random.randint(1, 59)
    d = random.randint(1, 59)
    e = random.randint(1, 59)
    f = random.randint(1, 35)

    showNumbers(a,b,c,d,e,f)


def ballPickerTwo():
   a = random.randrange(1,59,2)
   b = random.randrange(1,59,3)
   c = random.randrange(1,59,5)
   d = random.randrange(1,59,7)
   e = random.randrange(1,59,11)
   f = random.randint(1,35)

   showNumbers(a,b,c,d,e,f)


def showNumbers(a,b,c,d,e,f):

   print("Your Numbers ...")
   print()
   print("Ball 1: ", a)
   print("Ball 2: ", b)
   print("Ball 3: ", c)
   print("Ball 4: ", d)
   print("Ball 5: ", e)
   print("Red Ball: ", f)
   print()
   print("Good Luck")

我们需要使用 showNumbers 函数来显示结果,并以由此产生的格式显示。 ballPickerTwo 是“唯一”的,我在尝试唯一性失败时使用素数间隔。我试过使用循环,但无法弄清楚如何显示使用 showNumbers 生成的数字。

最佳答案

这是一种非常乏味的方法,但它不使用列表。它将选择随机且唯一的值。

def ballPickerTwo():

    a = random.randint(1, 59)

    b = a        
    while b == a:
        b = random.randint(1, 59)

    c = b
    while c == b or c == a:
        c = random.randint(1, 59)

    d = c
    while d == c or d == b or d == a:
        d = random.randint(1, 59)

    ...

关于python - 在不使用列表、集合等的情况下在 Python 中生成唯一数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13523283/

相关文章:

python - 如果执行因 RTSP 摄像头问题而停止,如何终止 cv2.VideoCapture(rtsp_url) 调用?

python - 我有一个问题 Django , authViews.LoginView.as_view(template_new ="")

C 编程,如何在日期结构数组中找到最旧的日期?

c# - 如何在没有 Zeros 的情况下将 Oracle 数值获取到 .NET?

c - 三角数

python - 使用 Python 覆盖 XLSX 文件中的现有单元格

Python Turtle Trouble - 循环结束太早

Perl:如何跳出嵌套循环?

python - 比较两个列表,然后说出列表中某个项目匹配的次数

python - 使用 python 修复列缩进