自定义排列 Python



给定此字典

dictt={2:'abc',3:'def',4:'gfi',5:'jkl',6:'mno',7:'pqrs',8:'tuv',9:'wxyz'}

我需要做一个自定义排列。

输入中的数字将告诉您输出将有多长。

输入还将指向正在排列的字母。

例如。"34"将使程序返回第一个序列的第一个字母,并将第二个序列的所有3个字母逐个相加。A+D=AD A+E=AE A+D=AF然后它将取第一个序列的第二个字母并将第二个序列的所有 3 个字母相加b+d=bd b+e=be b+f=bf然后是第三个字母C+D=CD C+E=CE C+F=CF因此,当您输入 34 时,它将返回 ad ae af bd 为 bf cd ce cf如果输入是 3 个数字。然后输出将是 3 对。如果输入是一个数字。然后输出将只是列出的相应序列。 ex: "2" would return a b c

def permuteString(numString):
    array=[]
    original={2:'abc',3:'def',4:'gfi',5:'jkl',6:'mno',7:'pqrs',8:'tuv',9:'wxyz'}
    for a,b in original.iteritems():
        print a,b
        for c in b:
            print c
    return array
stuff=permuteString("234")

到目前为止,我所做的只是把字典拿出

写成生成器类:

import itertools
class PhoneWords(object):
    letters = {
        2: 'abc',
        3: 'def',
        4: 'ghi',
        5: 'jkl',
        6: 'mno',
        7: 'pqrs',
        8: 'tuv',
        9: 'wxyz'
    }
    def __init__(self, num_string):
        self.num = [int(i) for i in num_string]                 # => [3, 4]
        self.chars = [PhoneWords.letters[i] for i in self.num]  # -> ['def', 'ghi']
    def __iter__(self):
        return (''.join(letters) for letters in itertools.product(*self.chars))

和使用中:

for word in PhoneWords("34"):
    print word

返回

dg
dh
di
eg
eh
ei
fg
fh
fi

我认为这是你想要的:

>>>from itertools import product
>>>def permuteString(numString):
>>>    original = {2:'abc',3:'def',4:'gfi',5:'jkl',6:'mno',7:'pqrs',8:'tuv',9:'wxyz'}
>>>    #extract the wanted string, for example input numString='23', the pools is ['abc', 'def']
>>>    pools = [original[int(n)] for n in numString]                                                 
>>>    return (''.join(x) for x in product(*pools)) #return a generator   

并以这种方式使用

>>>for x in permuteString('23'):
>>>    print x
ad
ae
af
bd
be
bf
cd
ce
cf

细节:

乘积:输入迭代对象的笛卡尔积

生成器:用于创建迭代器的简单而强大的工具

join:is 可以加入列表,例如:

x = ['a', 'b', 'c', 'd']
print ''.join(x)

这将输出:

'abcd'

最新更新