我在尝试编写一个函数组合时遇到了很大的困难,该函数组合以两个自然数 k 和 n 作为输入,并返回大小为 k 且总和为 n 的所有元组的集合。我关心的是找到同一组数字的不同排列。
我从 python 中找到了这个文档,可以在不使用 itertools 的情况下进行计算。
我的问题允许使用这些库
import sys
import numpy as np
import scipy as sp
from scipy.special import *
def compositions(iterable, r):
# combinations('ABCD', 2) --> AB AC AD BC BD CD
# combinations(range(4), 3) --> 012 013 023 123
pool = tuple(iterable)
n = len(pool)
if r > n:
return
indices = range(r)
yield tuple(pool[i] for i in indices)
while True:
for i in reversed(range(r)):
if indices[i] != i …Run Code Online (Sandbox Code Playgroud)