Skip to content

Commit 38a32f2

Browse files
Added the practice code files
1 parent 37ed7e0 commit 38a32f2

1 file changed

Lines changed: 81 additions & 0 deletions

File tree

practice.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# # Yield from
2+
# def yieldOnly():
3+
# yield "Sreekanth"
4+
# yield "Sourav"
5+
# yield "Satyamani"
6+
7+
# def yieldFrom():
8+
# for i in [1]:
9+
# yield from yieldOnly()
10+
11+
# test = yieldFrom()
12+
# for i in test:
13+
# print(i)
14+
15+
# # lazy evaluation
16+
# def fibonacci():
17+
# a, b = 0, 1
18+
# while True:
19+
# yield a
20+
# a, b = b , a + b
21+
22+
# fibonacci_Seq = (n for i, n in enumerate(fibonacci()) if i < 10)
23+
24+
# for n in fibonacci_Seq:
25+
# print(n)
26+
27+
# # reading files using generators
28+
# def pdf_reader(file_name):
29+
# for row in open (file_name, "r"):
30+
# yield row
31+
32+
# pdf_gen = pdf_reader("testfile.txt")
33+
# row_count = 0
34+
35+
# for row in pdf_gen:
36+
# row_count += 1
37+
38+
# print(f"Row count is {row_count}")
39+
# pdf_gen = (row for row in open("testfile.txt"))
40+
41+
# generator_methods
42+
def isEven(n):
43+
if n % 2 == 0:
44+
return True
45+
else:
46+
return False
47+
48+
def get_Even():
49+
value = 0
50+
while True:
51+
if isEven(value):
52+
i = yield value
53+
if i is not None:
54+
value = i
55+
value += 1
56+
57+
even_gen = get_Even()
58+
print(next(even_gen))
59+
print(even_gen.send(1))
60+
# it allows you to .send() a value back to the generator.
61+
print(next(even_gen))
62+
63+
for x in even_gen:
64+
if x < 10:
65+
even_gen.throw(ValueError, "I, THINK IT WAS ENOUGH!")
66+
# .throw() allows you to throw exceptions with the generator.
67+
print(x)
68+
69+
for x in even_gen:
70+
if x > 10:
71+
even_gen.close() .close()
72+
# .close() allows you to stop a generator. This can be especially handy when controlling an infinite sequence generator.
73+
print(x)
74+
75+
# generator with context manager
76+
def read_lines(filename):
77+
with open(filename) as f:
78+
for line in f:
79+
yield line.strip()
80+
for line in read_lines("testfile.txt"):
81+
print(line)

0 commit comments

Comments
 (0)