简体   繁体   English

检查排列python上排列出现的行号

[英]Checking line number of permutation occurrence on permutations python

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.它适用于较小的值,但在这种情况下,它需要通过 26 ^ 12 行来检查正确的排列。 Any help?有什么帮助吗?

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

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.也用'KUBET'尝试过,结果是4922080 ,与您的代码相同。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM