Skip to content

Commit 9bca5ef

Browse files
committed
Updated generator notes
1 parent a6207f0 commit 9bca5ef

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

18. Generators.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import time
2+
import random
3+
print("Generators are used to return a sequence of values as output. It uses 'yield' keyword for it. It does not store the values in their memory, so memory issues can be avoided. It cang erneate one valeu at a time. So,whehever u need to have a sequence of values, and need only one at a time, use generators. Advantages of generators:\n 1. Better Performance.\n2. Better memory utilisation.\n3. When compared with normal iterators, generators are easy to use.\n4. Generators are best suitable for web scraping,wherever large amt of data is involved.")
4+
5+
6+
def generator():
7+
yield '1st month groceries buy at Jan'
8+
yield '2nd month groceries buy at Feb'
9+
yield '3rd month groceries buy at Mar'
10+
11+
12+
g = generator()
13+
print("The type of g is: ",type(g))
14+
print(next(g))
15+
print(next(g))
16+
print(next(g))
17+
try:
18+
print(next(g))
19+
except Exception as e:
20+
print("The error is",e,"There is no further elemetns to yield.SO,it throws error.")
21+
try:
22+
MAX_SIZE = 10**(10000)
23+
if MAX_SIZE > 10**5:
24+
raise MemoryError("Attempting to allocate too much memory!")
25+
li = [x**x for x in range(MAX_SIZE)]
26+
print(li)
27+
28+
29+
except Exception as e:
30+
print("It leads to memoery error, instead if we have used generator, we would'nt have faced this issue,as it wont store the value")
31+
def generate_values(n):
32+
i = 0
33+
while i<=n:
34+
yield i*i
35+
i+=1
36+
37+
MAX_SIZE = 10**(1000000)
38+
for i in generate_values(MAX_SIZE):
39+
if i>10000:
40+
print("If i didnt break,it will execute forever. Our generator cacluated teh values on the fly,without storing all of them. So,always use generators instead of [i for i in range(10**100000)]")
41+
break
42+
print(i)
43+
44+
45+
print("We can also use generators, like tuple comprehension format, here we need not give yield keyword expleicitely. It takes care of it internally.")
46+
generator = (x**x for x in range(1000000000000))
47+
count = 0
48+
limit = 100
49+
50+
51+
while(count<limit):
52+
print(next(generator))
53+
count+=1
54+
55+
56+
print("Countdown eg.,: Here, in the below e.g., as value calls countdown(5),it doesnt perfrom the complete execution, instead it returns the countdown generator object, and that generator object is used in the for loop for iteration.")
57+
def countdown(start):
58+
while start >= 0:
59+
yield start
60+
start -= 1
61+
62+
value = countdown(5)
63+
print("Type of value is, ",value)
64+
for number in value:
65+
print("Countdown: ",number)
66+
67+
68+

0 commit comments

Comments
 (0)