Zip for average


 

zip(*iterables) is a very handy function when it comes to grouping together ith elements of iterables into tuples and running some operations on each of tuples.

I'll give an example of average calculation with zip. Below example is copied from hackerrank without an iota of shame 😉....

We have N students each appearing in M tests and obtaining some score in them, the ask is to calculate average score for each student.

Input format:

5 3                        # number of students, number of tests
89 90 78 93 80          #  Marks of students in test 1       
90 91 85 88 86          #  Marks of students in test 2
91 92 83 89 90.5       #  Marks of students in test 3

Desired output:

90.0 
91.0 
82.0 
90.0 
85.5

Simple implementation:

num_subj, num_stu = map(intinput().split())
mark_list = []

for _ in range(num_stu):
    mark_list.append(list(map(floatinput().split())))

zip_tuple = zip(*mark_list)
# Not mark_list, remember zip() takes iterables, not iterable

for z in zip_tuple:
    print(sum(z)/len(z))


With functools.reduce() making it look nerdy (if not reducing a few lines 😈) 

from functools import reduce
num_subj, num_stu = map(intinput().split())
mark_list = []
reduce(lambda x,y:x.append(y), (mark_list, 
                                [map(floatinput().split())
                                          for i in range(num_stu)]
                                     
                          ))
zip_tuple = zip(*mark_list[0])
for z in zip_tuple:
    print(sum(z)/len(z))


Comments

Popular Posts