【问题标题】:how to generate combinations with no repetitions of characters in python? [duplicate]如何在python中生成不重复字符的组合? [复制]
【发布时间】:2017-12-14 09:44:51
【问题描述】:

我有以下字符集:

qwertyiopnmjk013

我想生成所有可能的 6 个字符的字符串以及所有 7 个字符的字符串,注意每个字母在同一个生成的字符串中只出现一次。

在 python 中最好的形式是什么?有什么例子吗?

现在我正在将字符集复制到另一个变量,然后我开始生成挑选字母并将它们从字符集中删除,然后继续前进,但我认为这不是最好的方法..

【问题讨论】:

  • 这不是重复的。由于他要求“所有可能的字符串”,因此他指的是排列,而不是标题所暗示的组合。

标签: python math combinations


【解决方案1】:

使用迭代工具:

    import itertools
    myStr = "qwertyiopnmjk013"
    chars = list(myStr)
    for comb in itertools.combinations(chars, 6):
        print comb

【讨论】:

  • 这个“注意每个字母在同一个生成的字符串中只出现一次”怎么样?
  • 这是“组合”的标准数学定义的一部分。
  • @LeeDanielCrocker 这不是问题的一部分。据说“出现一次”
  • 您可以在调用 combination() 之前检查字符列表的唯一性,并进行任何适当的更改,例如删除重复项。
  • 是的,我的意思是他提出问题的方式与“组合”的标准定义兼容,因此combinations()函数完全符合他的要求。
【解决方案2】:

这个问题有点模棱两可,但这里是所有部分。 首先,只是为了获得组合:

import itertools
source = "qwertyiopnmjk013"
map(''.join, itertools.combinations(source, 6))

现在,如果您不希望出现重复的字母,即使您的源字符串 包含重复项,然后先修复您的源字符串:

source = ''.join(set("qwertyiopnmjk013"))

如果您还希望按每个顺序重新排列每个组合, 那么你处理的是排列,而不是组合。要将两者都列入一个不错的列表:

reduce(lambda x, y: x + y, map(lambda x: map(''.join, itertools.permutations(x)), itertools.combinations(source, 6)))

您应该注意,此时您正在处理数以千万计的字符串;希望你有一台快速的机器。

【讨论】:

  • import itertools print(map("".join, itertools.combinations("aaaaaaa", 6))) => ['aaaaaa', 'aaaaaa', 'aaaaaa', 'aaaaaa', 'aaaaaa', 'aaaaaa', 'aaaaaa'] 任务:注意每个字母在同一个生成的字符串中只出现一次。我认为问题在于将原始字符串中的相同字母视为“不同”。我承认这个问题可以有不同的解读,而且有些雄心勃勃。
【解决方案3】:

你可以使用itertools.combinations:

import itertools
s = "qwertyiopnmjk013"
final_letters = [''.join(b) for b in [i for i in itertools.combinations(s, 6)]+[i for i in itertools.combinations(s, 7)] if len(set(b)) == len(b)]

【讨论】:

    【解决方案4】:

    既然你说:

    我想生成所有可能的 6 个字符的字符串以及所有 7 个字符的字符串,注意每个字母在同一个生成的字符串中只出现一次。

    我假设您的意思是排列,而不是组合。

    在您的示例中,您没有重复的字符,但如果有,您可以先将字符串转换为集合。

    from itertools import permutations
    
    def permute_string(s, n):
        return map(lambda x: ''.join(x), permutations(set(s)))
    
    my_string = 'qwertyiopnmjk013'
    six_chars = list(permute_string(my_string, 6))
    seven_chars = list(permute_string(my_string, 7))
    

    【讨论】:

      猜你喜欢
      • 2019-04-19
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2010-12-15
      • 1970-01-01
      • 2019-08-11
      • 2015-07-25
      • 1970-01-01
      相关资源
      最近更新 更多