添加随机选择的数字

时间:2017-08-30 14:01:21

标签: python random sum

以下代码为我提供了数字列表中的随机选择。

import random
print ('Your five random numbers are')
for i in range(1):
print (random.sample([10,12,14,15,17,24,27,30,32,35,38,39,42,45,46,47],5))

输出结果为:

Your five random numbers are
[39, 10, 15, 38, 24]

在上面的输出中,它们总计为126.如何让python计算这个总和?

1 个答案:

答案 0 :(得分:1)

那样的东西?

import random

numbers = random.sample([10,12,14,15,17,24,27,30,32,35,38,39,42,45,46,47],5)

print("Your five random numbers are {}".format(numbers))

total = 0
for i, n in enumerate(numbers):
    total += n

print("The sum is {}".format(total))

示例运行的输出是:

Your five random numbers are [32, 24, 45, 38, 15]
The sum is 154

或直接使用sum函数:

import random

numbers = random.sample([10,12,14,15,17,24,27,30,32,35,38,39,42,45,46,47],5)

print("Your five random numbers are {}".format(numbers))

total = sum(numbers)
print("The sum is {}".format(total))

加成

OP还要求循环此过程并仅保留在范围(123,143)中具有总和的集合,而不添加任何其他约束。我将循环找到N个集合:

import random
# List of number
pool = [10,12,14,15,17,24,27,30,32,35,38,39,42,45,46,47]
# This will contain the selcted list
picked = []
# This will contain the selcted list sums
picked_totals = []
# Number of selected list of random numbers
N = 10

while len(picked) <= N:
    numbers = random.sample(pool, 5)
    total = sum(numbers)
    if total > 123 and total < 143:
        picked.append(numbers)
        picked_totals.append(total)

print("Result")
for i, e in enumerate(picked):
    print("{} :: {} (sum {})".format(i, e, picked_totals[i]))