-
Notifications
You must be signed in to change notification settings - Fork 34
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
40 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
""" | ||
Imagine you wanted to rimplement "head" and "grep" in python. Here's a first cut: | ||
""" | ||
|
||
def head(max_lines, filenames): | ||
for fn in filenames: | ||
with open(fn) as f: | ||
for ix, line in f: | ||
if ix >= max_lines: | ||
return | ||
print(line, end='') | ||
|
||
|
||
def grep(needle, filenames): | ||
for fn in filenames: | ||
with open(fn) as f: | ||
for line in f: | ||
if needle in line: | ||
print(line, end='') | ||
|
||
""" | ||
There's a lot of duplicated code there! Now we could build a helper function like this: | ||
""" | ||
|
||
def getlines(filenames): | ||
for fn in filenames: | ||
with open(fn) as f: | ||
return f.readlines() | ||
|
||
""" | ||
but then head would be inefficient, because getlines always reads every single line in the file. | ||
Find out how to use a generator to make a version of getlines that is "lazy" | ||
More info here: http://anandology.com/python-practice-book/iterators.html | ||
""" | ||
|