Forgot password
 Register account
View 168|Reply 0

[组合] 1到$n^2$分成$n\times n$个,每组和相等,分法有几种

[Copy link]

3156

Threads

7932

Posts

45

Reputation

Show all posts

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

Quick Reply

Advanced Mode
B Color Image Link Quote Code Smilies
You have to log in before you can reply Login | Register account

$\LaTeX$ formula tutorial

Mobile version

2025-6-8 12:02 GMT+8

Powered by Discuz!

Processed in 0.014952 second(s), 21 queries

× Quick Reply To Top Edit