File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python
2+
3+ """
4+ script to determine what programming languages students came to this
5+ class with
6+
7+ This version updated to use collections.Counter, to count and maintain
8+ a set at the same time.
9+
10+ """
11+
12+ import collections # lots of neat stuff in there
13+
14+ file_path = '../../Examples/Session01/students.txt'
15+
16+ # use a counter to ensure unique values and keep track of count
17+ all_langs = collections .Counter ()
18+
19+ f = open (file_path ) # default read text mode
20+
21+ f .readline () # read and toss the header
22+
23+ for line in f :
24+ langs = line .split (':' )[1 ]
25+ langs = langs .split (',' )
26+ for lang in langs :
27+ lang = lang .strip ().lower ()
28+ if lang : # don't want empty strings
29+ all_langs [lang ] += 1
30+ for lang , count in all_langs .items ():
31+ print "%10s: %i students" % (lang , count )
Original file line number Diff line number Diff line change @@ -4,19 +4,11 @@ Future Sessions:
44
55Sorting!
66
7+ add pathlib examples
78
89For Session 6:
910
10- if something is None, True, False
11- (rich comparisons)
11+ Counter() demo -- in the get languages example.
1212
13- reminder about opening file in binary mode.
14-
15- show defaultdict -- Carolyn
16-
17- you don't actually need to use the result of a list comp:
18-
19- for i, st in zip( divisors, sets):
20- [ st.add(j) for j in range(21) if not j%i ]
2113
2214lambda and sorting...
You can’t perform that action at this time.
0 commit comments