-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerators_example.py
More file actions
69 lines (49 loc) · 1.2 KB
/
generators_example.py
File metadata and controls
69 lines (49 loc) · 1.2 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
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun May 20 10:53:29 2018
@author: Ankit
Example to demonstarte the use of generators in python
debugging this example will explain how generators work
and the significance of yield keyword.
"""
def gen123():
yield 1
yield 2
yield 3
return
g=gen123()
print g.next()
print g.next()
print g.next()
print "*"*10
def run_take(count,iterable):
counter=0
for item in iterable:
if counter==count:
return
counter+=1
yield item
def run_take_distinct(iterable):
seen = set()
for item in iterable:
if item in seen:
continue
yield item
seen.add(item)
def run_pipeline(count,iterable):
for item in run_take(4,run_take_distinct(iterable)):
print item
def main():
items = [1,2,3,4,5]
for item in run_take(4,items):
print(item)
print "*"*10
items =[1,2,2,3,4,4,4,4,5,6,6,6,6,7,7,7,7,7]
for item in run_take_distinct(items):
print(item)
print "*"*10
run_pipeline(4,items)
if __name__=="__main__":
main()
# next call to new_g.next() will throw a StopIteration exception