【问题标题】:Given a set of letters, how to create all possible combinations of a word with these letters, duplicated with a specified number?给定一组字母,如何用这些字母创建单词的所有可能组合,并以指定的数字重复?
【发布时间】:2019-04-11 23:52:21
【问题描述】:

假设我有单词“apple”,一组字母 ['a', 'l', 'e'] 和重复次数 3。 从这里我想创建以下集合: ['aaapple', 'aaappllle', 'aaappllleee', 'appllle', 'appllleee', 'appleee'].

这是我已经尝试过的:

l = ['a', 'l', 'e']
word = "apple"

for i in range(0, len(l)):
    print wordWithDuplicatedLetters = "".join(3*c if c == l[i] else c for c in word)

但这并不匹配所有的组合,而且 itertools 似乎没有提供我正在寻找的可能性。

【问题讨论】:

  • 为什么不组合:aaappleee
  • 另外,如果您是 python 新手。请使用python 3,不要使用python 2。

标签: python string list


【解决方案1】:

我不认为您的示例输出具有所有可能的组合,我认为下面的输出具有所有可能的组合。这里的诀窍是通过下面的函数all_combinations 所做的任何大小的所有组合。

import itertools

repeat = ['a', 'l', 'e']
word = 'apple'

def all_combinations(itr):
    lst = list(itr)
    for r in range(1, len(lst) + 1):  # set start to 0 if want to include []
        for perm in itertools.combinations(lst, r=r):
            yield perm   # or use yield from in py3

def all_repeats():
    for rep in all_combinations(repeat):
        yield ''.join(char * 3 if char in rep else char for char in word)

print(list(all_repeats()))

输出

['aaapple',
 'appllle',
 'appleee',
 'aaappllle',
 'aaappleee',
 'appllleee',
 'aaappllleee']

【讨论】:

  • 看起来你那里有一些重复。
  • @quamrana 是的,应该使用组合,而不是排列——很好发现
  • @FHTMitchell 我在回答中这样做了
  • @FHTMitchell 前几天刚开始使用Python,对yield这个关键字还不是很熟悉;无论如何,感谢您提交详细的答案! :)
  • @ooj-001 很公平——坚持你所知道的。我认为这将是最快的解决方案,因为使用了yield
【解决方案2】:

尝试使用这个循环:

s = ''
for i in word:
    if i in l:
        s += (3 * i)
    else:
        s += i

可以是列表推导:

s = ''.join([3 * i if i in l else i for i in word])

现在在这两种情况下:

print(s)

是:

aaappllleee

全面回答您的问题

你必须使用:

import itertools

l = ['a', 'l', 'e']
word = 'apple'
l2 = []
for i in range(len(l)):
   for x in itertools.combinations(l, r=i+1):
       l2.append(x)
l3 = []
for lst in l2:
    l3.append(''.join(char * 3 if char in lst else char for char in word))

print(l3)

输出:

['aaapple', 'appllle', 'appleee', 'aaappllle', 'aaappleee', 'appllleee', 'aaappllleee']

【讨论】:

  • @FHTMitchell 我编辑了我的,但这是 OP 想要的输出......你投反对票了吗?
  • @U9-Forward 最后的编辑回答了我的问题,非常感谢您花时间查看我的问题!
【解决方案3】:

您可以将此问题分为两个步骤。首先,找出应该重复的所有可能的位置子集。这本质上是一个 powerset taken from here,去掉了空壳。从索引构建它可以使解决方案对包含重复字母的单词具有鲁棒性。

其次,对于 powerset 中的每个案例,构建一个有效的字符串并显示它。

from itertools import chain, combinations

def powerset_non_empty(iterable):
    """
    powerset with empty set skipped
    powerset([1,2,3]) -->  (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)
    """
    xs = list(iterable)
    # note we return a list, but could choose to return an iterator too
    return list(chain.from_iterable(combinations(xs,n) for n in range(1, len(xs)+1)))



l = ['a', 'l', 'e']
word = "apple"

indices = [i for i,c in enumerate(word) if c in l]
number_of_repetition = 3
powerset = powerset_non_empty(indices)

result = []
for index_tuple in powerset:
    s = ''
    for i, c in enumerate(word):
        if i in index_tuple:
            s += (number_of_repetition * c)
        else:
            s += c
    print(s)
    result.append(s)
#Output:
['aaapple',
 'appllle',
 'appleee',
 'aaappllle',
 'aaappleee',
 'appllleee',
 'aaappllleee']

【讨论】:

    【解决方案4】:

    你可以使用一个简单的递归生成器函数:

    l = ['a', 'l', 'e']
    word = "apple"
    def combo(d, r, c):
      for i in l:
        if any(j[0] == i and len(j) < r for j in c):
          w = [j if j[0] != i or len(j) == r else j+([i]*(r-1)) for j in c]
          yield ''.join(map(''.join, w))
          if any(j[0] in l and len(j) < r for j in w):
            yield from combo(d, r, w)
    
    
    print(list(combo(l, 3, [[i] for i in word])))
    

    输出:

    ['aaapple', 'aaappllle', 'aaappllleee', 'aaappleee', 'aaappllleee', 'appllle', 'aaappllle', 'aaappllleee', 'appllleee', 'aaappllleee', 'appleee', 'aaappleee', 'aaappllleee', 'appllleee', 'aaappllleee']
    

    【讨论】:

      猜你喜欢
      • 2017-02-17
      • 1970-01-01
      • 1970-01-01
      • 2022-11-29
      • 2022-12-06
      • 2014-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多