|
A321230 Number of set partitions of [n^2] into n n-element subsets having the same sum.
$n=5$ Python 代码:
- from itertools import permutations
- for x in permutations(range(1, 26)):
- if all(
- sum(x) == 65 for x in zip(x[::5], x[1::5], x[2::5], x[3::5], x[4::5])
- ):
- print(x)
Copy the Code 改进后的代码:
- from itertools import combinations
- def find_partitions(total_sum, num_subsets, subset_size):
- # base case: only one subset remaining, generate it from the remaining numbers
- if num_subsets == 1:
- if total_sum == sum(range(26)):
- yield [range(1, 26)]
- return
- # generate the first subset and recursively search for the remaining ones
- for subset in combinations(range(1, 26), subset_size):
- if sum(subset) == total_sum:
- remaining = set(range(1, 26)) - set(subset)
- for partition in find_partitions(total_sum, num_subsets-1, subset_size):
- partition.append(subset)
- yield partition
- # find all partitions with 5 subsets of size 5 and sum 65
- for partition in find_partitions(65, 5, 5):
- print(partition)
Copy the Code |
|