如何在python中获取字母的所有排列以及字符串的大小写?

时间:2014-05-20 02:43:50

标签: python case permutation letters

如何在python中获取所有可能的案例组合以及字符串的字母?

示例

输入:'ab'输出:aB','Ba','BA','Ab','AB','bA'

输入:'dan'输出:aND','ANd','Dna','naD','DaN','aDn','Adn' ,'dnA','NdA','anD','DnA','NAD','nAD','Dan','NDA','nAd','AdN','DAn','AnD',' '','DNA','daN','adN','nDa','dAN','dNa','aDN','ADN','dNA','Nda','AND','DNa' ,'NaD','NAD','aNd','nDA','dAn','NAd','ndA','NDa','ADn','DAN'

3 个答案:

答案 0 :(得分:1)

这可以使用itertools

完成
from itertools import permutations
def perm(word):
    perms = [''.join(p) for p in permutations(word)]
    print(perms)
    return perms

def capPer(arrPerm):
    result=[]
    for val in arrPerm:
        wordList=list(val)

        for i,letter in enumerate(wordList):
            wordList[i]=letter.upper()
            result.extend(perm(''.join(wordList)))
    return set(result)

def combi(wrd):
    print(capPer(perm(wrd)))


combi('ab')
combi('dan')

**output:**
set(['aB', 'Ba', 'BA', 'Ab', 'AB', 'bA'])
set(['aND', 'ANd', 'Dna', 'naD', 'DaN', 'aDn', 'Adn', 'dnA', 'NdA', 'anD', 'DnA', 'NAD', 'nAD', 'Dan', 'NDA', 'nAd', 'AdN', 'DAn', 'AnD', 'And', 'DNA', 'daN', 'adN', 'nDa', 'dAN', 'dNa', 'aDN', 'ADN', 'dNA', 'Nda', 'AND', 'DNa', 'NaD', 'Nad', 'aNd', 'nDA', 'dAn', 'NAd', 'ndA', 'NDa', 'ADn', 'DAN'])

答案 1 :(得分:1)

您可以使用itertools.product函数执行此操作。在https://docs.python.org/2/library/itertools.html

了解相关信息

这是一个例子:

def combos(s):
    combolist = []
    for i in range(len(s)):
        combolist.append([])
    for i in range(len(s)):
        combolist[i].append(s[i].lower())
        combolist[i].append(s[i].upper())
    return list(itertools.product(*combolist))

输出:

combos('ab')
>>> [('a', 'b'), ('a', 'B'), ('A', 'b'), ('A', 'B')]
combos('dan')
>>> [('d', 'a', 'n'), ('d', 'a', 'N'), ('d', 'A', 'n'), ('d', 'A', 'N'), ('D', 'a', 'n'), ('D', 'a', 'N'), ('D', 'A', 'n'), ('D', 'A', 'N')]

可以从那里轻松格式化。

答案 2 :(得分:1)

合并itertools.permutationsitertools.product

from itertools import permutations, product

def perm_with_case(word):
    cased = product(*zip(word.lower(), word.upper()))
    next(cased) # throw away the all-lowercase result
    return (''.join(p) for w in cased for p in permutations(w))

给出

>>> list(perm_with_case("ab"))
['aB', 'Ba', 'Ab', 'bA', 'AB', 'BA']
>>> list(perm_with_case("dan"))
['daN', 'dNa', 'adN', 'aNd', 'Nda', 'Nad', 'dAn', 'dnA', 'Adn', 'And', 'ndA', 'nAd', 'dAN', 'dNA', 'AdN', 'ANd', 'NdA', 'NAd', 'Dan', 'Dna', 'aDn', 'anD', 'nDa', 'naD', 'DaN', 'DNa', 'aDN', 'aND', 'NDa', 'NaD', 'DAn', 'DnA', 'ADn', 'AnD', 'nDA', 'nAD', 'DAN', 'DNA', 'ADN', 'AND', 'NDA', 'NAD']

似乎与所需的输出相匹配,但我承认我不明白为什么我们要抛出全小写的值。