【问题标题】:Combination of all possible cases of a string字符串所有可能情况的组合
【发布时间】:2011-07-19 12:29:21
【问题描述】:

我正在尝试创建一个程序来在 python 中生成字符串的所有可能的大写情况。例如,给定“abcedfghij”,我想要一个程序生成: Abcdefghij ABc定义.. . . aBcdef.. . ABCDEFGHIJ

等等。我试图找到一种快速的方法来做到这一点,但我不知道从哪里开始。

【问题讨论】:

  • 不知道为什么会在这里投反对票?明确的问题,即使没有明确的理由,也会提出更多琐碎的问题并且没有被否决?

标签: python string permutation


【解决方案1】:

类似于 Dan 的解决方案,但更简单:

>>> import itertools
>>> def cc(s):
...     return (''.join(t) for t in itertools.product(*zip(s.lower(), s.upper())))
...
>>> print list(cc('dan'))
['dan', 'daN', 'dAn', 'dAN', 'Dan', 'DaN', 'DAn', 'DAN']

【讨论】:

    【解决方案2】:
    from itertools import product, izip
    def Cc(s):
        s = s.lower()
        for p in product(*[(0,1)]*len(s)):
          yield ''.join( c.upper() if t else c for t,c in izip(p,s))
    
    print list(Cc("Dan"))
    

    打印:

    ['dan', 'daN', 'dAn', 'dAN', 'Dan', 'DaN', 'DAn', 'DAN']
    

    【讨论】:

    • 谢谢。这是完美的工作。我从来没有想过这样做。我正在尝试一种递归方法,但耗时太长。
    • 您可以更短地执行此操作:return (''.join(t) for t in product(*zip(s.lower(), s.upper()))).
    【解决方案3】:
    import itertools
    
    def comb_gen(iterable):
        #Generate all combinations of items in iterable
        for r in range(len(iterable)+1):
            for i in itertools.combinations(iterable, r):
                yield i 
    
    
    def upper_by_index(s, indexes):
         #return a string which characters specified in indexes is uppered
         return "".join(
                    i.upper() if index in indexes else i 
                    for index, i in enumerate(s)
                    )
    
    my_string = "abcd"
    
    for i in comb_gen(range(len(my_string))):
        print(upper_by_index(my_string, i))
    

    输出:

    abcd Abcd aBcd abCd abcD ABcd AbCd AbcD aBCd aBcD abCD ABCd ABcD AbCD aBCD ABCD
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-11
      • 2015-05-06
      • 1970-01-01
      • 2018-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多