2011-07-19 17 views
6

私は、Pythonで文字列のすべての大文字小文字の問題を生成するプログラムを作成しようとしています。たとえば、 'abcedfghij'を指定すると、プログラムを生成する必要があります。 Abcdefghij ABcdef .. 。 。 aBcdef .. 。 ABCDEFGHIJすべての可能な文字列の組み合わせ

など。私はそれをすばやく見つける方法を見つけようとしていますが、どこから始めるべきかわかりません。

+1

なぜ下降音がここにあるのですか?明確な質問でも、明確な理由ではないにせよ、より多くの些細な質問が尋ねられ、棄却されないのですか? – agf

答えて

7
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'] 
+0

ありがとうございます。それは完璧に働いています。私はこのようにすることは決して考えなかったでしょう。私は再帰的な方法を試みていたが、それは時間がかかりすぎていた。 – peacey

+4

あなたはこれをもっと短くすることもできます: 'return( '' .join(t)for product(* zip(s.lower()、s.upper()))'。 –

0
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 
10

ダンのソリューションに似ていますが、はるかに簡単:

>>> 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']