简体   繁体   English

随机的数字列表并添加它们

[英]Random list of numbers and add them

I am trying to create a program that asks user for a number and then generates a list of random numbers entered by the user and then uses a function to add these numbers together and return it back to the main function. 我正在尝试创建一个程序,要求用户输入一个数字,然后生成用户输入的随机数列表,然后使用函数将这些数字加在一起并将其返回到主函数。 I am so lost can someone please help me? 我很迷茫可以有人请帮帮我吗?

import random

def main():
    rand = int(input('How many random intergers? (Max 20)'))
    if rand <= 20:
        for x in range(rand):
            print (random.randint(1,9), end=' ')
        total = randnums(x)
        print('Integers total is ', total)
    else:
        print('Bad inpit. Maximum input is 20.')

Trying to get this sample output 试图获得此示例输出

How many random integers (max 20)? 有多少随机整数(最多20个)? 12 12

5 9 7 7 9 8 8 2 5 5 8 7 5 9 7 7 9 8 8 2 5 5 8 7

Integers total is 80 整数总数为80

import random
def f():
  n= input("give n : ")
  return sum([random.randint(0,10) for i in range(n)])

this will return the sum of 10 random number between 0 and 10 这将返回0到10之间的10个随机数之和

You have at least to store your random outputs and only then you can add them... 您至少要存储随机输出,然后才能添加它们......

EG 例如

total = 0
for x in range(rand):
  rnum = random.randint(1,9)
  print (rnum, end=' ')
  total = total + rnum
print('Total: %s' %total)

Import random 随机导入

print (sum ([random.random () for x in range (1,input ("choose a list size"))])) print(sum([random.random()for x in range(1,input(“select a list size”)))))

To sample i integers without replacement from a pool of integers from 1 to n , and then sum them: 从1到n的整数池中对i个整数进行采样而不进行替换,然后将它们相加:

$ n=12345
$ i=100
$ seq ${n} | shuf -n ${i} | awk '{s+=$0}END{print s}'

To sample with replacement and sum: 要用替换和总和进行抽样:

$ seq ${n} | shuf -r -n ${i} | awk '{s+=$0}END{print s}'

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

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