1+ '''
2+ Created on Oct 17, 2014
3+
4+ @author: db345c
5+ '''
6+
7+ import string
8+
9+ def kata14 (filename , start ):
10+ """ Set up variables, split lines in the groups of three, populate
11+ dictionary, and call function to print kata14 """
12+ # create dictionary
13+ words = {}
14+ # open file
15+ f = open (filename , "r" )
16+ count = 0
17+ for line in f :
18+ # Split the line into separate tokens
19+ lst = line .split ()
20+
21+ # discard all the lines containing less than three words
22+ if len (lst ) > 2 :
23+
24+ # Remove punctuation with string.punctuation (import string)
25+ for j , k in enumerate (lst ):
26+ lst [j ] = k .strip (string .punctuation )
27+
28+ # split the line in the groups of three words
29+ lst_length = len (lst )
30+ for idx , i in enumerate (lst ):
31+ # assure the last element of the list is reached, if so, break
32+ if idx == lst_length - 2 :
33+ break
34+ else :
35+ # got the three strings to use and add those to the dictionary
36+ l = [ (lst [idx ] + " " + lst [idx + 1 ]).strip (), lst [idx + 2 ].strip ()]
37+ buildDictionary (l , words )
38+ count += 1
39+ # close file
40+ f .close ()
41+
42+ # print kata14
43+ printKata14 (words , start )
44+
45+ def buildDictionary (l , words ):
46+ """ Populate the dictionary """
47+ if l [0 ] in words :
48+ words [l [0 ]].append (l [1 ])
49+ else :
50+ words [l [0 ]] = [l [1 ]]
51+ return words
52+
53+ def printKata14 (word , start ):
54+ """ Recursively print Kata14 """
55+ if start in word :
56+ if len (word [start ]) > 0 :
57+ temp = word [start ].pop ()
58+ print start , temp ,
59+ printKata14 (word , str (start .split ()[1 ]) + " " + temp )
60+ else :
61+ return
62+
63+ if __name__ == "__main__" :
64+ """ Execute Kata14 algorythm """
65+ kata14 ("sherlock.txt" , "little use" )
0 commit comments