递归序列python

问题描述 投票:-1回答:4

如何打印列表中包含字母的所有长度为n的序列(可以重复自己)?使用递归。例如:

seq = ['a', 'b']
n = 2

输出:

aa,ab,ba,bb

我一直在查找,只能找到递归程序,让所有序列都没有重复。此外,我找不到任何关于给定列表的解决方案(大多数都是字符串)

其中一个问题是,我不确定如何在包含长度为n的情况下递归地处理该函数。

python list recursion sequence repetition
4个回答
3
投票

你可以在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)]

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

我希望这有帮助 :)


1
投票

我将使用itertools

import itertools

seq = ['a', 'b']
n = 2

print([i+j for i,j in itertools.product(seq,repeat=n)])

这是产品的任务;)

顺便说一句:如果您不希望模块查看源代码:

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

学习并逆向工程以满足您的需求;)。示例,如果您不希望它返回元组。


0
投票

这是另一种方法,仅使用递归。 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']
© www.soinside.com 2019 - 2024. All rights reserved.