File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
Exams/final_exam_2024/task1 Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ from collections import defaultdict
2
+
3
+ def solve (word ):
4
+ chars = defaultdict (int ) # letter -> count in string
5
+ for ch in word :
6
+ chars [ch ] += 1
7
+
8
+ if len (chars ) == 1 : # aaaaa
9
+ return True
10
+
11
+ frequencies = defaultdict (int ) # counts of letters -> frequency of the count
12
+ for count in chars .values ():
13
+ frequencies [count ] += 1
14
+
15
+ if len (frequencies ) != 2 : # abbccc/ abcd
16
+ return False
17
+
18
+ by_frequency = list (sorted (frequencies .items (), key = lambda x : (x [1 ], - x [0 ]))) # sort by smallest frequency
19
+ count_key_removable , frequency_removable = by_frequency [0 ]
20
+ count_key_unchanged , frequency_unchanged = by_frequency [1 ]
21
+
22
+ if frequency_removable != 1 : # aaabbbccdd
23
+ return False
24
+
25
+ if count_key_removable == 1 : # xaabbcc
26
+ return True
27
+
28
+ if count_key_unchanged == 1 and frequency_unchanged == 1 : # aaaax
29
+ return True
30
+
31
+ if count_key_removable - 1 == count_key_unchanged : # xxxxaaabbbccc
32
+ return True
33
+
34
+ return False # xxxxxaaabbbccc
35
+
36
+ N = int (input ())
37
+ words = [input () for _ in range (N )]
38
+
39
+ for word in words :
40
+ output = 1 if solve (word ) else 0
41
+ print (output )
You can’t perform that action at this time.
0 commit comments