Вы находитесь на странице: 1из 11

=================Python Interview Questions=================================

Recursion: == Define a base case and continue reducing the problem until the base case is reached.

1.Divide a problem into subproblem. (Subproblems must be same as that of original)

2.Solve those sub problems.

3.Combine the results to solve the original.

Eg:

array = [1,7,8,5,4]

def length_of_list(array):

if array==[]:=====================> base case

return 0

return 1+length_of_list(array[1:])

a=length_of_list(array)

print(a)

o/p: 5

Errors:

RecursionError: maximum recursion depth exceeded ====> base condition never met

To understand recursion, understand STACK.

Stack is a data structure that holds sequence of data and lets you interact with topmost data item
only.==FILO

Python's list follows FILO

Eg-2: Python remembers the last function call and acts accordingly i.e order of execution is - recent
fn call -----> first fn call.

def a():

print("start of a")
b()

print("end of a")

def b():

print("start of b")

c()

print("end of b")

def c():

print("start of c")

print("end of c")

a()

O/P:

start of a

start of b

start of c

end of c

end of b

end of a

Extra Credit; https://pymotw.com/3/inspect https://pymotw.com/3/traceback


Frame objects (frame object is a function call) are stored in Stack, o/p is popped out each time
(2*1.3*2… 5*24) (In this case 5 being the last element in Stack)

Fn calls pushes frame objects to stack and return pops it

Video Reference: https://youtu.be/AfBqVVKg4GE

When to use recursion?

Problem that has tree like structure.

When the problem requires backtracing.

Limitation:

Python has limitation of 1000 function calls , eg: factorial(1001), where our script involves more than
1000 fn calls.= gives recursion error.

To overcome this follow:

Tail call optimization/Elimination:  optimizing the recursive function call (which is actually the tail
of recursive function).

Without TCO:

The first function is not tail recursive because when the recursive call is made, the
function needs to keep track of the multiplication it needs to do with the result after the
call returns.

With TCO: Cpython doesn’t implement TCO


TCO = Overcome Stackoverflow error.

Memoization: reduces To remember the function return values so that the next time if the fn takes
same parameter, it eliminates the need for recalculating

O(1)  simple checks and variable assignments.

O(n)->simple for loops.

O(log n)-> eg: binary search

O(n2)->Nested for loops.

O(n log n), O(2^n),O(n!)

OOPS:
Linear data structure:

Stack: Use stack when you want quick access to the most recent item and keep the items in order.

Queue: FIFO, Process items in order which they were added.


Non linear DS: BST,Graphs

Sorting:

Insertion
Merge

Quick == Low memory usage.

Вам также может понравиться