-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbigger_is_greater.py
More file actions
executable file
·66 lines (53 loc) · 1.63 KB
/
bigger_is_greater.py
File metadata and controls
executable file
·66 lines (53 loc) · 1.63 KB
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
#!/usr/bin/env python3
import os
import sys
from pathlib import Path
from typing import IO
def switchAbove(word: list[int]) -> bool:
for i in range(len(word) - 2, -1, -1):
for j in range(len(word) - 1, i, -1):
if word[i] < word[j]:
w = word[i]
word[i] = word[j]
word[j] = w
return True
return False
def switchBelow(word: list[int], best: list[int]) -> list[int]:
previous_equal = True
for i in range(len(word) - 1):
if previous_equal and word[i] == best[i]:
continue
previous_equal = False
for j in range(i + 1, len(word)):
if best[j] < best[i]:
candidate = best.copy()
candidate[i] = candidate[j]
candidate[j] = best[i]
if word < candidate < best:
best = candidate
return best
def biggerIsGreater(word: str) -> str:
reference = [ord(c) for c in word]
best = reference.copy()
if not switchAbove(best):
return "no answer"
while True:
candidate = switchBelow(reference, best)
if best != candidate:
best = candidate
else:
break
return "".join(chr(i) for i in best)
def main(fptr: IO) -> None:
T = int(input().strip())
for _ in range(T):
w = input()
result = biggerIsGreater(w)
fptr.write(result + "\n")
if __name__ == "__main__":
if path := os.getenv("OUTPUT_PATH"):
with Path(path).open("wt", encoding="utf-8") as fptr:
main(fptr)
fptr.close()
else:
main(sys.stdout)