如何打印所有长度为n的序列,其中包含列表中的字母(可以重复(使用递归。例如:
seq = ['a', 'b']
n = 2
输出:
aa,ab,ba,bb
我一直在查找,只能找到递归程序,它们给出的所有序列都没有重复。此外,我找不到任何关于给定列表的解决方案(其中大多数是给定字符串(
其中一个问题是,当函数包含长度n时,我不知道如何递归地处理它。
您可以在n
上重新使用子序列的长度。如果是n == 0
,则只有一个子序列——空子序列。否则,取列表中的所有元素对和长度为n-1的子序列,得到长度为n
的所有子序列。
def subseqs(lst, n):
if n <= 0:
return [[]]
else:
return [[x] + xs for x in lst for xs in subseqs(lst, n - 1)]
解决此问题的方法之一是使用itertools.product
import itertools
seq = ['a', 'b']
n = 2
for a, b in itertools.product(seq,repeat = n): print (f"{a}{b}") #loop through all the products and print them
#result -->
# aa
# ab
# ba
# bb
我希望这能有所帮助:(
我将使用itertools
import itertools
seq = ['a', 'b']
n = 2
print([i+j for i,j in itertools.product(seq,repeat=n)])
这是产品的任务;(
BTW:如果你不想模块看看源代码:
def product(*args, repeat=1):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = [tuple(pool) for pool in args] * repeat
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
源代码位于:https://docs.python.org/3/library/itertools.html#itertools.product
学习并对其进行逆向工程以满足您的需求;(。例如,如果您不希望它返回元组。
这里是另一种只使用递归的方法。findSeqRecPerChar
查找列表中特定字符的所有可能组合,findSeqRec
查找每个字符的所有潜在组合:
seq = ['a', 'b']
n = 2
def findSeqRecPerChar(seq,n,elem,index):
if index == n:
return []
else:
return [elem+seq[index]] + findSeqRecPerChar(seq,n,elem,index+1)
def findSeqRec(seq,n,index,l):
if index == n-1:
return l + []
else:
l.extend(findSeqRecPerChar(seq,n,seq[index-1],0))
return findSeqRec(seq,n,index+1,l)
result = findSeqRec(seq,n,-1,[])
print(result)
输出:
['aa', 'ab', 'ba', 'bb']