Skip to content

Commit 813be0b

Browse files
authored
Create generator.md
1 parent 44203c2 commit 813be0b

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

generator.md

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# In-Build Generators:
2+
A generator is a function that generates output whenever you call it and remembers the current state untill the next call is made
3+
4+
A simple example of a generator is ```range()``` function in python
5+
6+
```python
7+
# this code will freeze you pc if it generates the entire list
8+
# and saves it to memory
9+
#but it doesn't
10+
range(90000000000000000000000000)
11+
```
12+
The reason is this creates a generator which calculates next element every time you call it
13+
14+
## Use of in-build generators
15+
To create a generator we have to write our expression inside parenthesis '()'.
16+
```python
17+
n = 10
18+
# this creates a generator that gives even i upto n
19+
gen = (i for i in range(n) if i%2 == 0)
20+
for i in gen:
21+
print(i)
22+
23+
# this creates a list that contains even i upto n
24+
# as this creates the entire list at once it's not a generators
25+
# you can call it one line for-loops
26+
# also known as list comprehensions
27+
l = [i for i in range(n) if i%2 == 0]
28+
```
29+
30+
## Custom Generators.
31+
32+
To create more powerfull generators you can use this technique
33+
34+
__Program to calculate fibonacci__
35+
```python
36+
# normal method
37+
def fibo(n):
38+
f0 = 0
39+
print(0)
40+
f1 = 1
41+
print(1)
42+
for i in range(n-2):
43+
temp = f1
44+
f1 = f1+f0
45+
f0 = temp
46+
print(f1)
47+
48+
# generator method
49+
def fibo(n):
50+
f0 = 0
51+
yield f0
52+
f1 = 1
53+
yield f1
54+
for i in range(n-2):
55+
temp = f1
56+
f1 = f1+f0
57+
f0 = temp
58+
yield f1
59+
60+
```
61+
## Important points
62+
1. Generators consume more time but are memory efficient and do not blow up your ram by calculating everything before hand.
63+
2. Normal method is faster but comsumes more ram memory.

0 commit comments

Comments
 (0)