我想生成10个整数,加起来是40,在2-6的范围内。
例如:
2 + 6 + 2 + 5 + 6 + 2 + 2 + 6 + 3 + 6 = 40
10个在2到6之间的随机数,加起来是40。
发布于 2022-09-09 11:28:54
我的想法是在2,6的范围内生成数字,直到列表的长度是10,然后开始检查和,如果它不是40,那么删除列表的第一个元素并生成一个新的数字。唯一的问题是,您可能需要检查是否有可能将这些数字与目标数字相加,例如,如果是奇数,但所有生成的数字都是偶数,它就永远无法到达目标数。
import random
low,high = 2,6
count = 10
target = 40
k = []
r = range(low,high+1)
tries = 0
while True:
k.append(random.choice(r))
if len(k) == count:
if sum(k) == target:
break
k = k[1:]
tries += 1
print(k)
print(len(k))
print(sum(k))
print(tries)发布于 2022-09-09 11:28:43
在搜索空间相对较小的情况下,您可以使用itertools.combinations_with_replacement()生成在2到6之间的所有可能的10个数字序列,除了之和为40的序列--然后根据请求随机挑选和洗牌一个:
from itertools import combinations_with_replacement as combine
from random import choice, shuffle
sequences = [list(combo) for combo in combine(range(2, 6+1), 10) if sum(combo) == 40]
def get_random_sequence_of_sum_40():
seq = choice(sequences)
shuffle(seq)
return seq
# ... later when you need random sequences of sum=40
for i in range(10):
rand_sequence = get_random_sequence_of_sum_40()
print(f"The sum of {rand_sequence} is {sum(rand_sequence)}")样本输出:
The sum of [6, 3, 4, 4, 3, 3, 4, 6, 5, 2] is 40
The sum of [3, 3, 5, 3, 5, 5, 3, 3, 5, 5] is 40
The sum of [3, 3, 6, 3, 4, 6, 3, 4, 4, 4] is 40
The sum of [6, 6, 5, 3, 4, 3, 3, 2, 4, 4] is 40
The sum of [5, 2, 2, 4, 4, 4, 5, 4, 4, 6] is 40
The sum of [4, 4, 4, 3, 4, 4, 3, 6, 4, 4] is 40
The sum of [4, 4, 5, 4, 2, 4, 4, 5, 5, 3] is 40
The sum of [4, 2, 6, 2, 5, 6, 2, 5, 4, 4] is 40
The sum of [3, 6, 3, 4, 3, 3, 4, 4, 6, 4] is 40
The sum of [2, 2, 6, 2, 3, 5, 6, 4, 4, 6] is 40发布于 2022-09-09 11:26:39
如果我明白你的问题正确的话,就应该这样做:
import random as rd
run = True
while run:
list = []
for i in range(10):
ran_num = rd.randint(2, 6)
list.append(ran_num)
if sum(list) >= 40 and len(list) == 10:
print(list)
run = False 这将打印出10个数字的列表,这些数字加起来会达到40个或更多。
https://stackoverflow.com/questions/73661082
复制相似问题