File tree Expand file tree Collapse file tree 4 files changed +115
-0
lines changed
Expand file tree Collapse file tree 4 files changed +115
-0
lines changed Original file line number Diff line number Diff line change 1+ import sys
2+
3+ read = lambda : sys .stdin .readline ().rstrip ()
4+
5+
6+ class Problem :
7+ def __init__ (self ):
8+ self .n = int (read ())
9+ self .words = [read () for _ in range (self .n )]
10+
11+ def solve (self ) -> None :
12+ total , trie = 0 , self .make_trie ()
13+ for word in self .words :
14+ total += self .count_keystrokes (word , trie )
15+
16+ print (f"{ total / self .n :.2f} " )
17+
18+ def make_trie (self ) -> dict :
19+ trie = {}
20+
21+ for word in self .words :
22+ node = trie
23+ for char in word :
24+ node = node .setdefault (char , {})
25+
26+ node ["*" ] = True
27+
28+ return trie
29+
30+ def count_keystrokes (self , word : str , trie : dict ) -> int :
31+ strokes , node = 1 , trie [word [0 ]]
32+
33+ for char in word [1 :]:
34+ if len (node ) > 1 or "*" in node :
35+ strokes += 1
36+
37+ node = node [char ]
38+
39+ return strokes
40+
41+
42+ if __name__ == "__main__" :
43+ while True :
44+ try :
45+ Problem ().solve ()
46+ except (EOFError , ValueError ):
47+ break
Original file line number Diff line number Diff line change 1+ [
2+ {
3+ "input" : [
4+ " 4" ,
5+ " hello" ,
6+ " hell" ,
7+ " heaven" ,
8+ " goodbye" ,
9+ " 3" ,
10+ " hi" ,
11+ " he" ,
12+ " h" ,
13+ " 7" ,
14+ " structure" ,
15+ " structures" ,
16+ " ride" ,
17+ " riders" ,
18+ " stress" ,
19+ " solstice" ,
20+ " ridiculous"
21+ ],
22+ "expected" : [
23+ " 2.00" ,
24+ " 1.67" ,
25+ " 2.71"
26+ ]
27+ }
28+ ]
Original file line number Diff line number Diff line change 1+ import json
2+ import os .path
3+ import unittest
4+ from io import StringIO
5+ from unittest .mock import patch
6+
7+ from parameterized import parameterized
8+
9+ from main import Problem
10+
11+
12+ def load_sample (filename : str ):
13+ path = os .path .join (os .path .dirname (os .path .abspath (__file__ )), filename )
14+
15+ with open (path , "r" ) as file :
16+ return [(case ["input" ], case ["expected" ]) for case in json .load (file )]
17+
18+
19+ class TestCase (unittest .TestCase ):
20+ @parameterized .expand (load_sample ("sample.json" ))
21+ def test_case (self , case : str , expected : list [str ]):
22+ # When
23+ with (
24+ patch ("sys.stdin.readline" , side_effect = case ),
25+ patch ("sys.stdout" , new_callable = StringIO ) as output ,
26+ ):
27+ while True :
28+ try :
29+ Problem ().solve ()
30+ except StopIteration :
31+ break
32+
33+ result = output .getvalue ().rstrip ()
34+
35+ # Then
36+ self .assertEqual ("\n " .join (expected ), result )
37+
38+
39+ if __name__ == "__main__" :
40+ unittest .main ()
You can’t perform that action at this time.
0 commit comments