forked from cirosantilli/python-cheat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiterator.py
More file actions
executable file
·187 lines (133 loc) · 3.72 KB
/
iterator.py
File metadata and controls
executable file
·187 lines (133 loc) · 3.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#!/usr/bin/env python
"""
## Iterator
## yield
"""
"""
Iterators are more memory efficent for iterations than lists
since there is no need to store the entire sequence!
However, if you must calculate each new item, so more time expensive if
you are going to use it more than once
It is a classic space/time tradeoff.
"""
if '## create':
# An iterator is just a function with a `yield` method:
def mycount():
i = 0
while True:
yield i
i = i + 1
c = mycount()
assert next(c) == 0
assert next(c) == 1
assert next(c) == 2
# Raise exception when over:
def myxrange(n):
i = 0
while True:
yield i
i = i+1
if i > n:
raise StopIteration
x = myxrange(2)
assert next(x) == 0
assert next(x) == 1
assert next(x) == 2
try:
next(x)
except StopIteration:
pass
else:
assert False
if '## generator expressions':
# Shorthand way to create iterators
it = (i for i in xrange(10))
for i in it:
print i
# Parenthesis can be ommited for single argument func call:
def mysum(vals):
total = 0
for val in vals:
total += val
return total
assert mysum(i for i in [0, 2, 5]) == 7
if '## iter':
# Converts various types to iterators,
# in particular generator expressions.
iter('abc')
iter([1, 2, 3])
if '## next':
# Will not work with `xrange`!
# http://late.am/post/2012/06/18/what-the-heck-is-an-xrange
#next(xrange(1))
i = iter(xrange(2))
assert next(i) == 0
assert i.next() == 1
try:
next(i)
except StopIteration:
pass
else:
assert False
# Use default value if over:
it = iter(xrange(1))
assert next(it) == 0
assert next(it, 3) == 3
assert next(it, 3) == 3
# There is no has_next method.
# The only way is to catch the `StopIteration` exception:
# <http://stackoverflow.com/questions/1966591/hasnext-in-python-iterators>
if '## iterators can\'t be rewinded':
# Either store a list on memory or recalculate.
# Recalculate:
it = iter('asdf')
for i in it:
print 'first'
print i
it = iter('asdf')
for i in it:
print 'second'
print i
# Store on memory:
it = list(iter('asdf'))
for i in it:
print 'first'
print i
for i in it:
print 'second'
print i
if 'Built-in iterator functions':
if '## enumerate':
assert list(enumerate(['a', 'c', 'b']) ) == [(0, 'a'), (1, 'c'), (2, 'b'), ]
if '## reduce':
"""
- take two leftmost, apply func
- replace the two leftmost by the result
- loop
On the example below:
- 2*3 - 1 = 5
- 2*5 - 3 = 8
"""
assert reduce(lambda x, y: 2*x - y, [3, 1, 2]) == 8
if '## itertools':
import itertools
"""
Hardcore iterator patterns.
http://docs.python.org/2/library/itertools.html#recipes
Most important ones:
- imap: map for iterators
- izip: count to infinity
- count: count to infinity
"""
# Cartesian product:
for i, j in itertools.product(xrange(3), xrange(3)):
print i, j
# Join two iterators:
assert [i for i in itertools.chain(xrange(2), xrange(2))] == [0, 1, 0, 1]
if '## Applications':
if 'Merge two lists of same length odd / even elements':
# http://stackoverflow.com/questions/18041840/python-merge-two-lists-even-odd-elements
# Same length:
x = [0, 1]
y = [2, 3]
assert [ x for t in zip(x,y) for x in t ] == [0, 2, 1, 3]