没有循环或迭代工具的递归排列



在整个网站上搜索解决方案,但找不到任何内容
需要一些帮助来计算算法,获得所有带有重复的排列
我不允许使用循环或任何其他帮助程序库。

def func(num):
# The solution 

num表示每个节点长度的数目

例如,如果num=1,则解决方案为['a', 'b', 'c']
,或者如果num=2,则为['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc'],等等

谢谢

您可以使用递归生成器函数:

vals = ['a', 'b', 'c']
def combos(d, n, c = ''):
if len(c) == n:
yield c
else:
def _range(x=0):
if x < len(d):
yield from combos(d, n, c=c+d[x])
yield from _range(x+1)
yield from _range()
print([*combos(vals, 2)])

输出:

['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']

我们可以编写接受任何可迭代tcombinations来计算任何整数大小的固定长度组合n-

def combinations(t, n):
if n <= 0:
yield ()
elif not t:
return
else:
for x in combinations(t, n - 1):
yield (t[0], *x)
yield from combinations(t[1:], n)

任何可迭代项都可以用作输入。在这种情况下,组合将"abc"视为等效于["a", "b", "c"]-

for x in combinations("abc", 2):
print(x)
('a', 'a')
('a', 'b')
('a', 'c')
('b', 'b')
('b', 'c')
('c', 'c')

适用于n-的所有正整数值

for x in combinations("abc", 1):
print(x)
('a',)
('b',)
('c',)

n = 0n < 0-时产生空输出

for x in combinations("abc", 0):
print(x)
()

使用元组作为累加器,combinations不仅限于基于字符串的组合。如果需要的话,调用者可以很容易地加入元组来创建两个字符串-

for x in combinations("abc", 2):
print("".join(x))
aa
ab
ac
bb
bc
cc
函数func(n(和func1(list1,list2(将生成排列。函数func1将对相乘n次。当n=1时,(a,b,c(。然后当n=2时,(a,b,c(x(a,b,c(。当n=3时,(a,b,c(^3。
input = ['a','b','c']
input2 = input
output = [ ]
def func(t):
global input
global input2
global output
if t==1:
print(input)    
if t>1:
func1(0,0)
input=output 
output=[]
func(t-1)
def func1(x,y):
global input
global input2
global output
if y<len(input):
output.append(input2[x]+input[y])
func1(x,y+1)    
if y+1>len(input) and x+1<len(input2):
func1(x+1,0)    
return input[x]
func(2)

当func(2(:时显示输出

['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']

最新更新