考虑一个范围从 0 到 50 的整数列表。我想生成并打印该列表的所有可能排列,总和为给定数字。示例如下:
If the sum is 41:
One output is [4,5,7,9,16]
...
您可以使用
itertools中的
combinations(...)
功能
import itertools
nums = range(51)
for n in range(1, len(nums) + 1):
for p in itertools.combinations(nums, n):
if sum(p) == 41:
print(*p)
以下代码最好在子例程中使用,但它可以是独立的代码。要更改平均值,只需更改 while 循环后的数字即可。要更改数字数量,请更改列表中零的数量。随机部分也可以更改数字范围。
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
这段代码的意思是一个单独的子例程,如下所示:
def mean(x):
y = sum(x)/6
return y
在代码开始时,需要导入随机库才能让代码正常工作。唯一的是这段代码只会输出一种组合,例如:
统计() [11,12,16,17,16,15]
您可以编写一个递归生成器来有效地仅生成总和达到目标数字的正整数组合:
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]
请注意,如果您正在寻找从 1 到 50 且总和为 41 的所有数字组合,您将会得到很多这样的组合:
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)