Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting permutations in Python, itertools

I want to get all the 3 letter permutations possible from every letter in the alphabet using itertools. This comes back blank:

import itertools 

def permutations(ABCDEFGHIJKLMNOPQRSTUVWXYZ, r=3):
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    for indices in product(range(n), repeat=r):
        if len(set(indices)) == r:
            yield tuple(pool[i] for i in indices)

What am I doing wrong?

like image 394
Damien Avatar asked Dec 01 '25 05:12

Damien


1 Answers

You are a bit mixed up, that is just code explaining what permutations does. itertools is actually written in C code, the python equivalent is just given to show how it works.

>>> from itertools import permutations
>>> from string import ascii_uppercase
>>> for x in permutations(ascii_uppercase, r=3):
        print x


('A', 'B', 'C')    
('A', 'B', 'D')
('A', 'B', 'E')    
('A', 'B', 'F')
.....

That should work fine

like image 120
jamylak Avatar answered Dec 02 '25 19:12

jamylak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!