【问题标题】:How to make a function with random numbers如何用随机数制作函数
【发布时间】:2020-11-16 00:05:28
【问题描述】:

您好,我正在尝试创建一个函数,该函数将选择 5 个随机数,这将等于已经给出的总数,并将 5 个数字放入列表中。当我通过函数传递一个数字时,我得到一个错误。 我似乎无法理解我做错了什么。

def num_lottery(total_num):
    the_set =[]
    n1 = random.randint(1, total_num)
    n2 = random.randint(1, total_num - n1)
    n4 = random.randint(1, total_num - (n1 + n2 + n3))
    n5 = total_num - (n1 + n2 + n3 + n4)
    the_set.append(n1, n2, n3, n4, n5)
    return the_set

当我通过 total_num = 50000 时它有效,但当 total_num = 5000 时无效。 任何帮助表示赞赏。 谢谢

【问题讨论】:

  • 好像你错过了n3初始化。
  • 添加 n3 初始化后,此代码适用于我。
  • I get an error. - 这是什么意思? but not when total_num = 5000 - 结果是什么?
  • 发布有关产生异常的代码的问题时,请始终包含完整的 Traceback - 复制并粘贴它,然后将其格式化为代码(选择它并输入 ctrl-k

标签: python function random iteration


【解决方案1】:

我现在对 python 编码一无所知,但请看一下代码中的变量 n3:

def num_lottery(total_num):
    the_set =[]
    n1 = random.randint(1, total_num)
    n2 = random.randint(1, total_num - n1)
    n4 = random.randint(1, total_num - (n1 + n2 + **n3**))
    n5 = total_num - (n1 + n2 + n3 + n4)
    the_set.append(n1, n2, n3, n4, n5)
    return the_set

它没有在任何地方定义。
我想你的意思是:

def num_lottery(total_num):
    the_set =[]
    n1 = random.randint(1, total_num)
    n2 = random.randint(1, total_num - n1)
    **n3 = random.randint(1, total_num - (n1+n2)**
    n4 = random.randint(1, total_num - (n1 + n2 + **n3**))
    n5 = total_num - (n1 + n2 + n3 + n4)
    the_set.append(n1, n2, n3, n4, n5)
    return the_set

我希望这能解决问题。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-03
  • 1970-01-01
  • 2021-09-28
  • 1970-01-01
  • 2019-03-27
相关资源
最近更新 更多