forked from kgisl/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.py
76 lines (60 loc) · 1.56 KB
/
solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/usr/bin/env python
import sys
def factorial(n):
"""
Naively calculates n!
"""
f = 1
while n > 0:
f *= n
n -= 1
return f
def count(values):
"""
Returns a dict of counts for each value in the iterable.
"""
counts = dict()
for v in values:
if v not in counts:
counts[v] = 0
counts[v] += 1
return counts
def rank(word, i, chars):
"""
Finds the rank of word[i:] amongs permutations of characters in words[i:].
:type word: str
:type i: int
:type chars: Dict[chr, int] The count of each character in word[i:]
"""
n = len(word)
assert i >= 0
assert i < n
if i == n - 1:
return 0
# The first character of the word[i:].
c = word[i]
# The number of characters less than word[i] in word[i:]. Helps count the
# number of words starting with a character less than word[i].
lt = 0
for j in range(i, n):
k = word[j]
if k < c:
lt += 1
# Count the number of words starting with a character less than word[i].
r = lt * factorial(n - i - 1)
# Remove identical permutations from duplicate characters.
for k in chars:
r /= factorial(chars[k])
# Recurse for word[i + 1:].
chars[c] -= 1
r = int(r) + rank(word, i + 1, chars)
chars[c] += 1
return r
def main():
T = int(sys.stdin.readline())
for _ in range(0, T):
word = sys.stdin.readline().strip()
chars = count(word)
print(rank(word, 0, chars) + 1)
if __name__ == '__main__':
main()