TAGS :Viewed: 6 - Published at: a few seconds ago

[ custom permutation python? ]

Given this dictionary

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

i need to do a custom permutation.

the numbers in the input will tell you how long the output will be.

The input will also point at the letters being permutated.

for example. "34" will make the program return the first letter of the first sequence and add all 3 letters of the second sequence one by one. a+d=ad a+e=ae a+d=af then it will take the second letter of the first sequence and add all 3 letters of the second sequence b+d=bd b+e=be b+f=bf then third letter c+d=cd c+e=ce c+f=cf so when u enter 34 it will return ad ae af bd be bf cd ce cf if the input was 3 numbers. then output would be pairs of 3. if the input was one number. then the output would be just the corresponding sequence listed. 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")

so far all i did was just pull the dictionary out

Answer 1


Written as a generator class:

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))

and in use:

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

returns

dg
dh
di
eg
eh
ei
fg
fh
fi

Answer 2


I think this is you want:

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

And use by this way

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

Detail:

product :Cartesian product of input iterables

generator:a simple and powerful tool for creating iterators

join: is can join the list, for example:

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

This would output:

'abcd'