我只需要使用一些预定义的数字来生成随机填充的固定大小的整数列表。另外,此新列表中的数字总和必须等于给定的数字。
例如:随机重复这3个数字-2
,2
,3
,以创建一个大小为20
的新列表,并且列表项的总和必须为{ {1}}。在此示例中,60
,size = 20
和sum = 60
是输入。
我可以在python中这样做吗?
答案 0 :(得分:1)
import numpy as np
def sum_to_x(n, x):
values = [0.0, x] + list(np.random.uniform(high=x, size=n - 1))
values.sort()
return [values[i + 1] - values[i] for i in range(n)]
d = sum_to_x(20, 60)
print(d)
print(sum(d))
输出:
[1.1666321716192374, 3.7356682360404636, 0.10213495009527396, 15.944355221343475, 4.823749563474106, 2.771274835477797, 1.1543877569990038, 6.6231006904687675, 1.0517272997350275, 6.954578248764335, 0.9446793094979142, 2.079080332702951, 1.1813248101489293, 3.3584697034830597, 0.8048689399051554, 1.3952223726127002, 4.797652596772288, 0.30201710006423355, 0.5143495684426824, 0.29472629235259973]
60.0
用于整数值:
import random as r
def random_sum_to(n, num_terms=None):
num_terms = (num_terms or r.randint(2, n)) - 1
a = r.sample(range(1, n), num_terms) + [0, n]
list.sort(a)
return [a[i + 1] - a[i] for i in range(len(a) - 1)]
print(random_sum_to(60, 20))
输出:
[3, 3, 4, 1, 2, 5, 4, 1, 4, 2, 1, 2, 1, 2, 1, 3, 6, 1, 12, 2]
60
答案 1 :(得分:1)
您可以做到,但是您应该知道这是在最佳时间内解决它的复杂问题。
我只能给您一个随机的解决方案,在某些情况下,这可能会花费很多时间,因为它是随机的:
import random
def create_list(possible_values, size, sum_of_values, max_iterations=10**5):
for i in range(max_iterations):
values = [
random.choice(possible_values)
for _ in range(size)]
if sum(values) == sum_of_values:
# only exit once it reaches the goal
print('solution found after {:,d} iterations'.format(i))
return values
raise ValueError(
'no solution found after {:,d} iterations'.format(max_iterations))
这是示威活动;每次调用函数时,相同的参数可能具有不同的持续时间
>>> create_list([-1, 0, 1, 2, 3], 20, 30)
solution found after 38 iterations
[1, 2, 1, 1, 1, 3, 2, 2, 3, 2, 3, 2, 1, 1, -1, 0, 0, 2, 2, 2]
>>> create_list([-1, 0, 1, 2, 3], 20, 30)
solution found after 31 iterations
[2, 2, 3, 0, 3, 1, 1, 1, 3, 3, 1, 1, 0, 2, 1, -1, 3, 3, 0, 1]
>>> create_list([-1, 0, 1, 2, 3], 20, 30)
solution found after 93 iterations
[2, -1, 2, 1, 3, 2, -1, 0, 2, -1, 3, 3, 2, 2, 3, 1, 1, 0, 3, 3]
>>> create_list([-1, 0, 1, 2], 20, 30)
solution found after 50,456 iterations
[1, 2, 2, 2, 2, 2, 2, 2, -1, 2, 1, 0, 2, 2, 2, 2, 2, 0, 2, 1]
如果失败,您可以使用更多的迭代次数再试一次,但这并不总是可以解决问题:
>>> create_list([-1, 0, 1], 20, 30)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/ralf/PycharmProjects/django_test_02/run_pw.py", line 20, in create_list
'no solution found after {:,d} iterations'.format(max_iterations))
ValueError: no solution found after 100,000 iterations
>>> create_list([-1, 0, 1], 20, 30, 10**6)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/ralf/PycharmProjects/django_test_02/run_pw.py", line 20, in create_list
'no solution found after {:,d} iterations'.format(max_iterations))
ValueError: no solution found after 1,000,000 iterations