You can do it, but you should know that this is a complex problem to solve it in optimal time.
I can only give you a random solution, which may take a lot of time in some cases, because it is, you know, random:
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))
Here is a demonstration; the same parameters may have a different durations in each invocation of the function
>>> 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]
If it fails, you can try again with a higher number of iterations, but it does not always solve the issue:
>>> 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