Week # 9 Lecture # 17 & 18 Python Programming Iteration: Learning Objectives

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

Week # 9 Lecture # 17 & 18

PYTHON PROGRAMMING ITERATION

RELATED VIDEOS ON YOUTUBE

Sr. Channel Video Name URL

1 Dr Umair Abdullah Assignment 5 solution https://youtu.be/MBecHBhkU8o

Recursive Functions for Flat Lists https://youtu.be/zhWgWD28_Ew


2 Dr Umair Abdullah
(Second Method: Anser variable) https://youtu.be/gWs8ooNSLYY

https://youtu.be/fibHOcU-Tcw
https://youtu.be/uAVgwPQCRZw
3 Dr Umair Abdullah Recursive Functions for Nested Lists https://youtu.be/Y7tKlcfUE00
https://youtu.be/dNc-fleLgac

Learning Objectives
1. Solution of assignment # 5
2. Recursive functions using second method
a. Count , sum, member, delete, reverse, factorial, Fibonacci
3. Recursive functions for nested lists

PRE-REQUISITS

1. PyCharm is installed
2. You have learned basics of Python programming
3. You have executed iterative and recursive examples of last week lectures
SOLUTION (Assignment # 5)

QUESTION: Define two functions (one iterative and other recursive) in Python named
sub-it and sub-rec. Each of the functions will take three arguments; old-value, new-
value, and a list. They should replace old-value with the new-value from the given list.
Sample call;

>>> sub_it (10, 5, [10, 8, 10, 12])


[ 5 , 8 , 5 , 12]
>>> sub_rec (10, 5, [10, 8, 10, 12])
[ 5 , 8 , 5 , 12]

SOLUTION:

A) ITERATIVE FUNCTION

def sub_it (o,n,x):


ans = []
for e in x:
if e == o:
ans.append(n)
else:
ans.append(e)
return ans

print(sub_it(10, 5, [10, 8, 10, 12]))


[5, 8, 5, 12]

B) RECURSIVE FUNCTION

def sub_rec (o,n,x):


if x == []:
return []
else:
ans = sub_rec(o,n, x[1:])
if x[0] != o:
ans.insert(0, x[0])
else:
ans.insert(0, n)
return ans

print(sub_rec(10, 5, [10, 8, 10, 12]))


[5, 8, 5, 12]
RECURSIVE FUNCTIONS IN PYTHON

Method of Additional Variables

Fibonacci Series example in last lecture already uses this method i.e. passing data to
recursvie calls with the help of additional variables. Now we shall use this method for
accumulating the result in the additional answer variable. We shall be redoing all the
example of last lecture using this new method.

1. count(x) : counts the number of elements present in a list


2. sum(x) : returns sum of all the numbers present in the list x
3. member(e,x) : returns True if e is present in list x otherwise returns False
4. delete (e, x): removes all the occurrences of e from list x
5. Reverse (x): returns the reverse of given list x
6. Factorial (n): calculates and returns the factorial of given number n

RECURSIVE FUNCTIONS
with additonal ans variables

1. count recursive

def cr2(a, ans = 0):


if a == []:
return ans
else:
return cr2(a[1:], ans+1)

print(cr2([10,20,30,40]))
# [10, 20, 30, 40] 0
# [20, 30, 40] 1
# [30, 40] 2
# [40] 3
# [] 4
4

2. Sum recursive

def sr2(a,ans = 0):


if a == []:
return ans
else:
return sr2(a[1:],a[0] + ans)
print(sr2([10,20,30,40]))
# [10, 20, 30, 40] 0
# [20, 30, 40] 10
# [30, 40] 30
# [40] 60
# [] 100
100

3. Member-recursive
def memr(a, x):
if x == []:
return False
elif a == x[0]:
return True
else:
return memr(a, x[1:])

print(memr(60, [10, 20, 70, 60, 40] ))


# True
print(memr(50, [10, 20, 70, 60, 40]))
# False

Note that for the member function we don’t need to use the second method as we are not maintaing
any answer in this fuction. True is returned immediately when the element is found in the list (no
need to store it)

4. Delete-recursive
def dr2(a, x, ans=[]):
if x == []:
return ans
elif a == x[0]:
return dr2(a, x[1:], ans)
elif type(x[0]) is list:
ans1 = dr2(a, x[0], [])
ans.append(ans1)
return dr2(a, x[1:], ans)
else:
ans.append(x[0])
return dr2(a, x[1:], ans)

print(dr2(10, [10, 20, 10, 30, 10, 40]))


# dr2( 10 , [10, 20, 10, 30, 10, 40] , [] )
# dr2( 10 , [20, 10, 30, 10, 40] , [] )
# dr2( 10 , [10, 30, 10, 40] , [20] )
# dr2( 10 , [30, 10, 40] , [20] )
# dr2( 10 , [10, 40] , [20, 30] )
# dr2( 10 , [40] , [20, 30] )
# dr2( 10 , [] , [20, 30, 40] )
[20, 30, 40]

5. Reverse Recursive

def rev2(x, ans=[]):


print('rev2(', x, ', ', ans, ')')
if x == []:
return ans
else:
ans.insert(0,x[0])
return rev2(x[1:],ans)

print(rev2([10,20,30, 40,50]))
# rev2( [10, 20, 30, 40, 50] , [] )
# rev2( [20, 30, 40, 50] , [10] )
# rev2( [30, 40, 50] , [20, 10] )
# rev2( [40, 50] , [30, 20, 10] )
# rev2( [50] , [40, 30, 20, 10] )
# rev2( [] , [50, 40, 30, 20, 10] )
[50, 40, 30, 20, 10]

6. Factorial Recursive

def factr2(n, ans=1):


print(n,' ', ans)
if n < 1:
return ans
else:
return factr2(n - 1, ans * n)

print(factr2(5))
# 5 1
# 4 5
# 3 20
# 2 60
# 1 120
# 0 120
120
Processing Nested/Embedded Lists
Flat list can be used for Linear Data Structures
[10, 20, 70, 80, 30, 50, 60, 40]

Nested lists can be user for Multi-Dimensional Data Structures like tables
[[10, 20], [70, 80], [30, 50], [60, 40]]

Or for Complex data structures like trees and graphs


[10, 20, [[70, 80], 30, [50, 60]], 40]

1. count recursive for nested lists

def cr2e(a,c=0):
print(a, '\t', c)
if a == []:
return c
elif type(a[0]) is list:
c1 = cr2e(a[0])
return cr2e(a[1:],c+c1)
else:
return cr2e(a[1:],c+1)

print(cr2e([10,[20,30],40]))
# [10, [20, 30], 40] 0
# [[20, 30], 40] 1
# [20, 30] 0
# [30] 1
# [] 2
# [40] 3
# [] 4
4

2. sum recursive for nested lists

def sr2e(a,ans = 0):


print(a, '\t', ans)
if a == []:
return ans
elif type(a[0]) is list:
s1 = sr2e(a[0])
return sr2e(a[1:],ans+s1)
else:
return sr2e(a[1:],a[0] + ans)

print(sr2e([10,[20,30],40]))
# [10, [20, 30], 40] 0
# [[20, 30], 40] 10
# [20, 30] 0
# [30] 20
# [] 50
# [40] 60
# [] 100
100

3. member recursive for nested lists

def mre(a,x):
print(a, ' ',x)
if x == []:
return False
elif a == x[0]:
return True
elif type(x[0]) is list:
return mre(a,x[0]) or mre(a,x[1:])
else:
return mre(a,x[1:])

print(mre(60, [10, [20, 70, 60], 40]))


# 60 [10, [20, 70, 60], 40]
# 60 [[20, 70, 60], 40]
# 60 [20, 70, 60]
# 60 [70, 60]
# 60 [60]
True
print(mre(50, [10, [20, 70, 60], 40]))
# 50 [10, [20, 70, 60], 40]
# 50 [[20, 70, 60], 40]
# 50 [20, 70, 60]
# 50 [70, 60]
# 50 [60]
# 50 []
# 50 [40]
# 50 []
False

4. delete recursive for nested/embedded lists

def dr2e(a, x, ans=[]):


print('dr2e(',a,', ',x,', ',ans,')')
if x == []:
return ans
elif a == x[0]:
return dr2e(a, x[1:], ans)
elif type(x[0]) is list:
ans1 = dr2e(a, x[0], [])
ans.append(ans1)
return dr2e(a, x[1:], ans)
else:
ans.append(x[0])
return dr2e(a, x[1:], ans)

print(dr2e(10, [10, 20, [10, 30], 10, 40]))


# dr2e( 10 , [10, 20, [10, 30], 10, 40] , [] )
# dr2e( 10 , [20, [10, 30], 10, 40] , [] )
# dr2e( 10 , [[10, 30], 10, 40] , [20] )
# dr2e( 10 , [10, 30] , [] )
# dr2e( 10 , [30] , [] )
# dr2e( 10 , [] , [30] )
# dr2e( 10 , [10, 40] , [20, [30]] )
# dr2e( 10 , [40] , [20, [30]] )
# dr2e( 10 , [] , [20, [30], 40] )
[20, [30], 40]

5. member recursive for nested lists

def rev2e(x, ans=[]):


print('rev2e(', x, ', ', ans, ')')
if x == []:
return ans
elif type(x[0]) is list:
ans1= rev2e(x[0], [])
else:
ans1= x[0]
ans.insert(0,ans1)
return rev2e(x[1:],ans)

print(rev2e([10,20,[40,50,30],60]))
# rev2e( [10, 20, [40, 50, 30], 60] , [] )
# rev2e( [20, [40, 50, 30], 60] , [10] )
# rev2e( [[40, 50, 30], 60] , [20, 10] )
# rev2e( [40, 50, 30] , [] )
# rev2e( [50, 30] , [40] )
# rev2e( [30] , [50, 40] )
# rev2e( [] , [30, 50, 40] )
# rev2e( [60] , [[30, 50, 40], 20, 10] )
# rev2e( [] , [60, [30, 50, 40], 20, 10] )
[60, [30, 50, 40], 20, 10]

---------------------------END -------------------

You might also like