top of page
Search
  • Writer's pictureHarshit Sharma

RECURSION, GENERATORS AND DECORATORS

Recursion:The recursion is a part of functional programming the basic purpose of recursion is self refrence functions calling themselves again and again.It is basically used in that program in which the program can be broken into sub parts or we can say sub programs.

The most used example that we use in recursion is the use of factorial calculation.These functions can be infinite just like loops.

def fact(y):

if y==1:

return 1

else:

return y*fact(y-1)

print(fact(5))

The base case of recursive function do not involve the further calls to the function.

We can use recursion indirect also.

Decorators.

Decorators is basically used to modify functions using other functions. This is used when we want to extend the functionality of functions.

def decora(func):

def wrap():

print("!!!!!!!!!!!!!!")

func()

print("!!!!!!!!!!!!!!")

return wrap

def print_text():

print("Decorators")

decorated=decora(print_text)

decorated()

OR

def decora(func):

def wrap():

print("!!!!!!!!!!!!!!")

func()

print("!!!!!!!!!!!!!!")

return wrap

def print_text():

print("Decorators")

print_text=decora(print_text)

print_text();

Generators: These are like iterable like lists or tuples. They do not allow indexing but still can be iterated with for loops. They can be created using functions and yield statement.With yield they can be infinite.

def check():

i=4

while i>0:

yield i

i-=1

for i in check():

print(i)

we have finite generators which cab be converted into lists by passing arguments to list.

def num(x):

for i in range(x):

if i%2== 0:

yield i

print (list(num(11)))

2 views0 comments

Recent Posts

See All

Comments


Post: Blog2_Post
bottom of page