Consider a list of integers, ranging from 0 to 50. I would like to generate and print all possible permutations of this list that sum to a given number. An example is shown below:
If the sum is 41:
One output is [4,5,7,9,16]
...
Consider a list of integers, ranging from 0 to 50. I would like to generate and print all possible permutations of this list that sum to a given number. An example is shown below:
If the sum is 41:
One output is [4,5,7,9,16]
...
The following code repeatedly generates random sequences of numbers and adds them to a tell until the list has the desired mean. In the example below, the code will output a list of six numbers, ranging from 9 to 17, with an average of 14.5. These can obviously be changed as desired.
```python
def stats():
x =[0,0,0,0,0,0]
while mean(x) != 14.5:
x =[0,0,0,0,0,0]
for i in range(6):
a = random.randint(9,17)
x[i] = a
return x
```
The mean
function very simply accepts the list and returns the mean as desired. You will need to change the divisor (6 in the example below) for different lengths of lists.
```python
def mean(x):
y = sum(x)/6
return y
```
At the start of the code, you need to import the random library to allow the code to work properly. The one caveat of this code, is that it only generates one permutation at a time. However a for
loop can be used to generate more:
stats()
>>> [11, 12, 16, 17, 16, 15]
You could write a recursive generator to efficiently produce only the combinations of positive integers that sum up to the target number:
def sumSets(numbers,target):
if not target : yield []
if not numbers or target <= 0: return
yield from sumSets(numbers[1:],target)
yield from (numbers[:1]+ss for ss in sumSets(numbers[1:],target-numbers[0]))
nums = list(range(1,50,3))
for ss in sumSets(nums,41): print(ss)
[19, 22]
[16, 25]
[13, 28]
[10, 31]
[7, 34]
[4, 37]
[1, 40]
[1, 4, 7, 13, 16]
[1, 4, 7, 10, 19]
Note that, if you're looking for all combinations of numbers from 1 to 50 that sum up to 41, you're going to get a lot of them:
nums = list(range(1,51))
print(sum(1 for _ in sumSets(nums,41))) # 1260
import itertools
def find_permutations_with_sum(nums, target_sum):
# Generate all permutations of the input list
all_permutations = list(itertools.permutations(nums))
# Filter permutations that sum to the target_sum
valid_permutations = []
for perm in all_permutations:
if sum(perm) == target_sum:
valid_permutations.append(perm)
return valid_permutations
# Example usage
nums_range = range(0, 51) # List of integers from 0 to 50
target = 10 # The desired sum
valid_permutations = find_permutations_with_sum(nums_range, target)
# Print the valid permutations
for perm in valid_permutations:
print(perm)