1

我正在尝试递归地创建给定字符串的所有子集。给定 string = 'aab',我们为不同的字符生成所有子集。答案是:["", "b", "a", "ab", "ba", "a", "ab", "ba", "aa", "aa", "aab", "aab", "aba", "aba", "baa", "baa"]。我一直在研究几个解决方案,比如这个, 但我试图让函数接受一个变量——只接受字符串并使用它,但不知道怎么做。我也一直在研究类似问题的解决方案,但是由于它处理的是列表而不是字符串,因此我似乎在将其转换为接受和生成字符串时遇到了一些麻烦。这是我的代码,在此示例中,我无法将 str 连接到列表。因此我的问题。 我编辑了输入和输出。

def gen_all_strings(word):

    if len(word) == 0:
        return ''

    rest = gen_all_strings(word[1:])

    return  rest + [[ + word[0]] + dummy for dummy in rest]
4

3 回答 3

1
from itertools import *

def recursive_product(s,r=None,i=0):
    if r is None:
        r = []
    if i>len(s):
        return r
    for c in product(s, repeat=i):
        r.append("".join(c))
    return recursive_product(s,r,i+1)

print(recursive_product('ab'))
print(recursive_product('abc'))

输出:

['', 'a', 'b', 'aa', 'ab', 'ba', 'bb']

['', 'a', 'b', 'c', 'aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc', 'aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca', 'acb', 'acc', 'baa', 'bab', 'bac', 'bba', 'bbb', 'bbc', 'bca', 'bcb', 'bcc', 'caa', 'cab', 'cac', 'cba', 'cbb', 'cbc', 'cca', 'ccb', 'ccc']

老实说,在这种情况下感觉真的被迫使用递归,一个更简单的版本,具有相同的结果:

nonrecursive_product = lambda s: [''.join(c)for i in range(len(s)+1) for c in product(s,repeat=i)]
于 2020-06-01T12:22:07.677 回答
0

这是字符串中字符集的集。

from itertools import chain, combinations

s = set('ab') #split string into a set of characters

# combinations gives the elements of the  powerset of a given length r
# from_iterable puts all these into an 'iterable'
# which is converted here to a list

list(chain.from_iterable(combinations(s, r) for r in range(len(s)+1)))
于 2020-06-01T11:46:54.243 回答
0
import itertools as it

def all_subsets(iterable):
    s = list(iterable)
    subsets = it.chain.from_iterable(it.permutations(s,r) for r in range(len(s) + 1))
    return list(map("".join, list(subsets)))

print(all_subsets('aab'))
# ['', 'a', 'a', 'b', 'aa', 'ab', 'aa', 'ab', 'ba', 'ba', 'aab', 'aba', 'aab', 'aba', 'baa', 'baa']

print(all_subsets('abc'))
# ['', 'a', 'b', 'c', 'ab', 'ac', 'ba', 'bc', 'ca', 'cb', 'abc', 'acb', 'bac', 'bca', 'cab', 'cba']
于 2020-06-06T05:57:42.697 回答