Skip to content

Commit

Permalink
add a new challenge, generators
Browse files Browse the repository at this point in the history
  • Loading branch information
hjwp committed May 28, 2016
1 parent d282a63 commit 6ccdb53
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
4 changes: 3 additions & 1 deletion challenges/Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ features of Python, and help you to write more "Pythonic" code...

[decorators](decorators.py) - decorators, a pretty way of transforming functions using other functions. functional programming! functions.

[context managers](context_managers.py) - aka the "with" statement. What's it for, and how does it help to make your code look nicer?
[context managers](context_managers.py) - aka the `with` statement. What's it for, and how does it help to make your code look nicer?

[generators](generators.py) - more efficient iterators with python and the `yield` statement.

[The Game of Life](life.md) - a programming classic. Try it out using OO and functional paradigms in Python.

Expand Down
37 changes: 37 additions & 0 deletions challenges/generators.py
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
"""

0 comments on commit 6ccdb53

Please sign in to comment.