简体   繁体   English

如何使用随机数制作 function

[英]How to make a function with random numbers

Hi I am trying to create a function that will select 5 random numbers which will equal a total amount already given and put the 5 numbers in a list.嗨,我正在尝试创建一个 function,它将 select 5 个随机数等于已经给出的总数,并将 5 个数字放在一个列表中。 When I pass a number through the function I get an error.当我通过 function 传递一个数字时,我收到一个错误。 I cant seem to get what Im doing wrong.我似乎无法理解我做错了什么。

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

It works when I pass through the total_num = 50000, but not when total_num = 5000. Any help is appreciated.它在我通过 total_num = 50000 时有效,但在 total_num = 5000 时无效。感谢任何帮助。 Thanks谢谢

I don't now anything about python coding, but take a look at the variable n3 in your code:我现在对 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

It isn't defined anywhere.它没有在任何地方定义。
I think you meant:我想你的意思是:

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

I hope that does the trick.我希望这能解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM