[Python Programming Basics to Advanced]: Lab 30: zip map filter and reduce functions

preview_player
Показать описание
This Python programming playlist is designed to take beginners with zero programming experience to an expert level. The course covers installation, basic syntax, practical scenarios, and efficient logic building. The course material includes PDF handouts, review questions, and covers a wide range of topics, from data types to advanced functions like Lambda and Recursive functions, Generators, and JSON data parsing.

In this lesson we will study about four functions; zip, map, filter and reduce.

Link of Movies Task file:

Link of Student Data Task file:

The csv file used in Student Task:

Lab Manual 30 can be downloaded from here:

Review Question: 1
1- Given at 31:02
2- Consider one actor, e.g. Al Pacino, and display his longest movie in the collection.
3- Suppose that registration fee for any course is PKR 1000 per credit hour. Use the reduce function to calculate and display the total registration fee collected from 80 students.

Practice Tasks (need not to be answered here):
1- From the student dataset, create a list of students’ registration numbers who obtained at least two A/A+ grades from sec A (if you are from sec A) / from sec B (if you are from sec B).
2- Find the registration number of the student who got highest number of A/A+ provided he/she registered in 5 courses.

#PythonProgramming #python #pythontutorial
Рекомендации по теме
Комментарии
Автор

Regarding Review Question 3, of course there can be many solution but I wanted to check how intelligently you can use reduce (and may be filter and map with that as well) to:
- Make your code less lengthy.
- Make your code better readable
- Make your code take less memory

Here is how I solved this problem:

def addRegFee(f, s):
#f is old fee sum and s is next student
c=s['Courses'].keys()
# getting all CH of the registered subjects.
m=map(lambda course:subjects.get(course), c)
return f+(sum(m))*1000

print(functools.reduce(addRegFee, data, 0))

LearningOrbis
Автор

Question No. 1:-

GPAs=list(map(calcGPA, data))
for i, j in zip(data, GPAs):
i["GPA"]=j


Question No.2 :-





print(max(filter(lambda x:"Al Pacino" in x["Actors"], myCollection), key=lambda y:y["Runtime"])["Title"])

MuhammadAhmad-dshu
Автор

question2
a=filter(lambda x:'Al Pacino' in x['Actors'], myCollection)
print(max(a, key=lambda y:y['Runtime'])['Title'])
question1
import csv
from functools import reduce
def GPA(x):
s=[sub[i]*gDict[j] for i, j in x['Courses'].items()]
return sum(s)/sum(ch)
courses=['DLD', 'CP', 'ED', 'VCA', 'EM']
ch=[3, 2, 3, 3, 2]
sub=dict(zip(courses, ch))
gLetter=['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'F']
gPoints=[4.0, 4.0, 3.7, 3.3, 3.0, 2.7, 2.3, 2.0, 1.7, 1.3, 1.0, 0]
gDict=dict(zip(gLetter, gPoints))
m=map(GPA, data)
z=zip(m, data)
for i, j in z:
j['GPA']=i
print(data)
#Q3)
def Regfee(x):
z=[sub[i] for i, j in x['Courses'].items()]
return z
m=map(Regfee, data)
print(reduce(lambda a, b:a+sum(b)*1000, m, 0))

zohaibkhalid
Автор

#REViEW question 2
f=filter(lambda a: 'Al Pacino' in a['Actors'], myCollection)
print(max(f, key=lambda f:f['Runtime'])['Title'])

talhakamboh
Автор

Question # 1:
def GPA(a):
num=0
den=0
for k, v in a['Courses'].items():
num+=subjects[k]*gDict[v]
den+=subjects[k]
return num/den


courses=['DLD', 'CP', 'ED', 'VCA', 'EM']
CH=[3, 2, 3, 3, 2]
subjects=dict(zip(courses, CH))

gLetter=['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'F']
gPoints=[4.0, 4.0, 3.7, 3.3, 3.0, 2.7, 2.3, 2.0, 1.7, 1.3, 1.0, 0]
gDict=dict(zip(gLetter, gPoints))

a=map(GPA, data)
b=zip(a, data)
for i, j in b:
j['GPA']=i
print(data)



Question # 2:
a=filter(lambda x:'Al Pacino' in x['Actors'], myCollection)
print(max(a, key=lambda y:y['Runtime'])['Title'])



Question # 3:
from functools import reduce
def RgFee(b):
a=[subjects[i] for i, j in b['Courses'].items()]
return a


m=map(RgFee, data)
print(reduce(lambda x, y:x+sum(y)*1000, m, 0))

zoniseithzoniseith
Автор

Q1:

def calcGPA(a):
n=0
d=0
for k, v in a['Courses'].items():
n+=subjects[k]*gDict[v]
d+=subjects[k]
return n/d

courses=['DLD', 'CP', 'ED', 'VCA', 'EM']
CH=[3, 2, 3, 3, 2]
subjects=dict(zip(courses, CH))
x=list(map(lambda a:calcGPA(a), data))
z=zip(x, data)
print(list(z))



Q2:

a=filter(lambda x:'Al Pacino' in x['Actors'], myCollection)
print(max(a, key=lambda y:y['Runtime'])['Title'])



Q3:

from functools import reduce
def RgFee(b):
a=[sub[i] for i, j in b['Courses'].items()]
return a

m=map(RgFee, data)
print(reduce(lambda a, b:a+sum(b)*1000, m, 0))

fourcloversan
Автор

#Review question 1
def GPA(a):
num=0
den=0
for k, v in a['Courses'].items():
num+=subjects[k]*gDict[v]
den+=subjects[k]
return num/den

#Main Program#
courses=['DLD', 'CP', 'ED', 'VCA', 'EM']
CH=[3, 2, 3, 3, 2]
subjects=dict(zip(courses, CH))

gLetter=['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'F']
gPoints=[4.0, 4.0, 3.7, 3.3, 3.0, 2.7, 2.3, 2.0, 1.7, 1.3, 1.0, 0]
gDict=dict(zip(gLetter, gPoints))

a=map(GPA, data)
b=zip(a, data)
for i, j in b:
j['GPA']=i
print(data)

#Review question 2
a=filter(lambda x:'Al Pacino' in x['Actors'], myCollection)
print(max(a, key=lambda y:y['Runtime'])['Title'])

#Review question 3
from functools import reduce
def RgFee(b):
a=[subjects[i] for i, j in b['Courses'].items()]
return a

#Main Program#
m=map(RgFee, data)
print(reduce(lambda x, y:x+sum(y)*1000, m, 0))

zainulhassan
Автор

#Review_Question_1
(only definition and main program excluding collections)
def gpa_cal(d):
    gp=sum([subjects[i]*gDict[j] for i, j in d['Courses'].items()])

    return gp/ch
  
z=zip(map(GPA, data), data)
for i, j in z:
    j['GPA']=i
print(data)



#Review_Question_2

x=filter(lambda a:'Al Pacino' in a['Actors'], myCollection)
print(max(x, key=lambda b:b['Runtime'])['Title'])



#Review_Question_3


from functools import reduce
def RgFee(x):
    a=[subjects[i] for i, j in x['Courses'].items()]
    return a

#main_program
m=map(RgFee, data)
print(reduce(lambda x, y:x+sum(y)*1000, m, 0))

abdul-hadi
Автор

#Consider one actor, e.g. Al Pacino, and display his longest movie in the collection.
f=filter(lambda m:"Al Pacino" in m["Actors"], myCollection)
o=(max(f, key=lambda m:m['Runtime']))
n=o['Title']
print(n)

hafizasadullah
Автор

Task 1)
def calcGPA(c):
x=0
y=0
for i, j in c['Courses'].items():
x+=subjects[i]*gDict[j]
y+=subjects[i]
return x/y

# Main Program #


p=list(map(lambda c:calcGPA(c), data))
q=zip(p, data)
print(list(q))

Task 2)
x=filter(lambda y:'Al Pacino' in y['Actors'], myCollection)
y=max(list(map(lambda y:((y['Runtime'])), list(x))))
print(y)

Task 3)
from functools import reduce
def function(f):
x=0
y=0
for i, j in f['Courses'].items():
y+=subjects[i]*gDict[j]
x+=subjects[i]
return x

# Main Program #

l=list(map(lambda f:function(f), data))
print((reduce(lambda x, y:(x+y), l))*1000)

hishamawan
Автор

#TASK 2#
print(max(list(map(lambda x:x['Runtime'], filter(lambda y:'Al Pacino' in

#TASK 3#
from functools import reduce
#Creating a filtered list of dictionary of registered subjects and obtained grades
s=map(list, filter(lambda r:r.values() not in gLetter, map(lambda s:s['Courses'], data)))
print(reduce(lambda x, y:x+y, map(lambda x:subjects[x]*1000, reduce(lambda x, y:x+y, s))))

amaanmajid
Автор

#Review question 1
import csv
courses=['DLD', 'CP', 'ED', 'VCA', 'EM']
def calcGPA(s):
num=0
den=0
for k, v in s['Courses'].items():
num+=subjects[k]*gDict[v]
den+=subjects[k]
return num/den
with open('studentdata.csv', 'r') as f:
r=csv.DictReader(f)
data=[]
d={}
for rec in r:
d={}
for k, v in rec.items():
if(k in ['Reg', 'Name', 'Sec']):
d[k]=v
if (k in courses and v!='NR'):
if ('Courses' not in d):
d['Courses']={k:v}
else:
d['Courses'][k]=v
data.append(d)
CH=[3, 2, 3, 3, 2]
subjects=dict(zip(courses, CH)) # Keys=CourseName value=CH
# Here is details of letter grades as Dictionary
gLetter=['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'F']
gPoints=[4.0, 4.0, 3.7, 3.3, 3.0, 2.7, 2.3, 2.0, 1.7, 1.3, 1.0, 0]
gDict=dict(zip(gLetter, gPoints))

a=(map(calcGPA, data))
z=zip(a, data)
for i, j in z:
j['GPA']=i
#print(data)
#reg=int(input('Enter Last two digit of student Reg number (XX):'))
for i in range(80):
for k, v in data[i].items():
print(f'{k}={v}')
print('-'*100)




##Review Question 3
## MAIN PROGRAM
from functools import reduce
def RegFee(x):
a=[subjects[i] for i, j in x['Courses'].items()]
return sum(a)*1000
#main_program
m=(map(RegFee, data))
print(f'Total amount collected : {reduce(lambda x, y:x+y, m)}')

huzaifasarwar
Автор

AOA sir, is it necessary to solve question no 3 with the help of user-defined function and dictionary?

hafizasadullah
Автор

##Review Question-1##
import csv
def calcGPA(s):
f=[sub[x]*gDict[y] for x, y in s['Courses'].items()]
return sum(f)/sum(CH)
courses=['DLD', 'CP', 'ED', 'VCA', 'EM']
CH=[3, 2, 3, 3, 2]
sub=dict(zip(courses, CH))
gLetter=['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'F']
gPoints=[4.0, 4.0, 3.7, 3.3, 3.0, 2.7, 2.3, 2.0, 1.7, 1.3, 1.0, 0]
gDict=dict(zip(gLetter, gPoints))
## Data list of students has been created here by opening csv file which is used in main program

##MainProgram##
m=list(map(calcGPA, data))
a=0
for i in data:
i['GPA']=m[a]
a+=1
print(data)

##Review Question-2##
f=filter(lambda m:"Al Pacino" in m["Actors"], myCollection)
m=max(f, key=lambda r: r["Runtime"])
print(f'The longest movie of Al Pacino is "{m["Title"]}"')

##Review Question-3##
from functools import reduce
import csv
def Tot_RegFee(data):
a=[sub[x] for i in data for x in i['Courses'].keys()]
return sum(a)*1000
courses=['DLD', 'CP', 'ED', 'VCA', 'EM']
CH=[3, 2, 3, 3, 2]
sub=dict(zip(courses, CH))
## Data list of students has been created here by opening csv file which is used in main program
##Main Program##
print(Tot_RegFee(data))

muhammadalihaider
Автор

Sir does using map filter and reduce vectorize our approach

muhammadshess
Автор

courses=['DLD', 'CP', 'ED', 'VCA', 'EM']
CH=[3, 2, 3, 3, 2]
subjects=dict(zip(courses, CH))
gLetter=['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'F']
gPoints=[4.0, 4.0, 3.7, 3.3, 3.0, 2.7, 2.3, 2.0, 1.7, 1.3, 1.0, 0]
gDict=dict(zip(gLetter, gPoints))

#Creating a filtered list of dictionary of registered subjects and obtained grades
s=filter(lambda r:r.values() not in gLetter, map(lambda s:s['Courses'], data))
#Creating list of GPAs
GPA_List=map(lambda for i in x)/sum(subjects[i] for i in x), s)

#Updating the data list
data=map(lambda d, y:d['GPA']=y, data, GPA_List)

""" File "d:\python\GPA.py", line 46
data=map(lambda d, y:d['GPA']=y, data, GPA_List)
^
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?"""

Command for updating data list is generating above mentioned error.

amaanmajid
Автор

question2
a=filter(lambda x:'Al Pacino' in x['Actors'], myCollection)
print(max(a, key=lambda y:y['Runtime'])['Title'])
question1
import csv
from functools import reduce
def GPA(x):
s=[sub[i]*gDict[j] for i, j in x['Courses'].items()]
return sum(s)/sum(ch)
courses=['DLD', 'CP', 'ED', 'VCA', 'EM']
ch=[3, 2, 3, 3, 2]
sub=dict(zip(courses, ch))
gLetter=['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'F']
gPoints=[4.0, 4.0, 3.7, 3.3, 3.0, 2.7, 2.3, 2.0, 1.7, 1.3, 1.0, 0]
gDict=dict(zip(gLetter, gPoints))
m=map(GPA, data)
z=zip(m, data)
for i, j in z:
j['GPA']=i
print(data)
#Q3)
def Regfee(x):
z=[sub[i] for i, j in x['Courses'].items()]
return z
m=map(Regfee, data)
print(reduce(lambda a, b:a+sum(b)*1000, m, 0))

MuhammadTalha-xmul
Автор

#REViEW question 2
f=filter(lambda a: 'Al Pacino' in a['Actors'], myCollection)
print(max(f, key=lambda f:f['Runtime'])['Title'])

huzaifasarwar
Автор

Question # 1:
def GPA(a):
num=0
den=0
for k, v in a['Courses'].items():
num+=subjects[k]*gDict[v]
den+=subjects[k]
return num/den


courses=['DLD', 'CP', 'ED', 'VCA', 'EM']
CH=[3, 2, 3, 3, 2]
subjects=dict(zip(courses, CH))

gLetter=['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'F']
gPoints=[4.0, 4.0, 3.7, 3.3, 3.0, 2.7, 2.3, 2.0, 1.7, 1.3, 1.0, 0]
gDict=dict(zip(gLetter, gPoints))

a=map(GPA, data)
b=zip(a, data)
for i, j in b:
j['GPA']=i
print(data)



Question # 2:
a=filter(lambda x:'Al Pacino' in x['Actors'], myCollection)
print(max(a, key=lambda y:y['Runtime'])['Title'])



Question # 3:
from functools import reduce
def RgFee(b):
a=[subjects[i] for i, j in b['Courses'].items()]
return a


m=map(RgFee, data)
print(reduce(lambda x, y:x+sum(y)*1000, m, 0))

haris
Автор

##Review Question-1##
import csv
def calcGPA(s):
f=[sub[x]*gDict[y] for x, y in s['Courses'].items()]
return sum(f)/sum(CH)
courses=['DLD', 'CP', 'ED', 'VCA', 'EM']
CH=[3, 2, 3, 3, 2]
sub=dict(zip(courses, CH))
gLetter=['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'F']
gPoints=[4.0, 4.0, 3.7, 3.3, 3.0, 2.7, 2.3, 2.0, 1.7, 1.3, 1.0, 0]
gDict=dict(zip(gLetter, gPoints))
## Data list of students has been created here by opening csv file which is used in main program

##MainProgram##
m=list(map(calcGPA, data))
a=0
for i in data:
i['GPA']=m[a]
a+=1
print(data)

##Review Question-2##
f=filter(lambda m:"Al Pacino" in m["Actors"], myCollection)
m=max(f, key=lambda r: r["Runtime"])
print(f'The longest movie of Al Pacino is "{m["Title"]}"')

##Review Question-3##
from functools import reduce
import csv
def Tot_RegFee(data):
a=[sub[x] for i in data for x in i['Courses'].keys()]
return sum(a)*1000
courses=['DLD', 'CP', 'ED', 'VCA', 'EM']
CH=[3, 2, 3, 3, 2]
sub=dict(zip(courses, CH))
## Data list of students has been created here by opening csv file which is used in main program
##Main Program##
print(Tot_RegFee(data))

shaheerahmadkhan