Checking line number of permutation occurrence on permutations python

Viewed 70

I need a more optimal way of searching for line count for permutations with repeating. It works fine with smaller values, but in this case, it needs to go through 26 ^ 12 lines to check correct permutation. Any help?

from itertools import product
count = 0 
for i in product(list('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), repeat=12):
    count += 1
    if ''.join(i) == "INTELLIGENCE":
        print(count)
1 Answers

Some simple math:

>>> sum(26**i * (ord(c) - ord('A')) for i, c in enumerate('INTELLIGENCE'[::-1])) + 1
31302015863412429

Tried it with 'KUBET' as well, result was 4922080, same as with your code.

Alternatively:

count = 0
for c in 'KUBET':
    count = 26 * count + ord(c) - ord('A')
count += 1

Another:

>>> table = str.maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZ', '0123456789ABCDEFGHIJKLMNOP')
>>> int('INTELLIGENCE'.translate(table), 26) + 1
31302015863412429

Slight variation:

>>> int(''.join(chr(ord(c) - (10, 17)[c < 'J']) for c in 'INTELLIGENCE'), 26) + 1
31302015863412429

Yet another:

>>> from functools import reduce
>>> reduce(lambda count, c: 26 * count + ord(c) - ord('A'), 'INTELLIGENCE', 0) + 1
31302015863412429
Related