|
| 1 | +""" Selecting values from an iterable using multiple conditions """ |
| 2 | + |
| 3 | +import itertools |
| 4 | +import collections |
| 5 | + |
| 6 | +cutoffs = {'maths': 40, 'elec': 35, |
| 7 | + 'lab' : 45, 'cs': 30, |
| 8 | + 'phy' : 25, 'chem': 35} |
| 9 | + |
| 10 | +marks_dict = { 'Karan': {'maths': 39, 'elec': 78, 'cs': 83, |
| 11 | + 'lab': 32, 'phy': 60, 'chem': 91}, |
| 12 | + 'Arjun': {'maths': 49, 'elec': 45, 'lab': 53, |
| 13 | + 'cs': 43, 'phy': 86, 'chem': 54}, |
| 14 | + 'Rancho': {'maths': 86, 'elec': 85, 'cs': 95, |
| 15 | + 'lab': 83, 'phy': 91, 'chem': 75}, |
| 16 | + 'Raju': {'maths': 32, 'elec': 36, 'lab': 50, |
| 17 | + 'cs': 26, 'phy': 35, 'chem': 41}, |
| 18 | + 'Farhan': {'maths': 30, 'elec': 56, 'cs': 21, |
| 19 | + 'lab': 33, 'phy': 27, 'chem': 56}} |
| 20 | + |
| 21 | +def find_passed(marks_dict,cutoffs): |
| 22 | + |
| 23 | + # Initialize dictionary |
| 24 | + pass_dict = {subject:[] for subject in cutoffs} |
| 25 | + |
| 26 | + for subject, cutoff in cutoffs.iteritems(): |
| 27 | + for student, student_marks in marks_dict.iteritems(): |
| 28 | + if student_marks[subject] >= cutoff: |
| 29 | + pass_dict[subject].append(student) |
| 30 | + |
| 31 | + return pass_dict |
| 32 | + |
| 33 | +def find_passedi(marks_dict, cutoffs): |
| 34 | + |
| 35 | + # defaultdict |
| 36 | + pass_dict = collections.defaultdict(list) |
| 37 | + |
| 38 | + # Dict comprehensions |
| 39 | + selectors = {(subject, student) :cutoffs[subject]<=val[subject] for subject in cutoffs for student,val in marks_dict.items()} |
| 40 | + # itertools compress |
| 41 | + passd = list(itertools.compress(selectors.keys(), selectors.values())) |
| 42 | + |
| 43 | + for subject,student in passd: |
| 44 | + pass_dict[subject].append(student) |
| 45 | + |
| 46 | + return pass_dict |
| 47 | + |
| 48 | +if __name__ == "__main__": |
| 49 | + passd = find_passed(marks_dict, cutoffs) |
| 50 | + print 'Passed =>',passd |
| 51 | + |
| 52 | + passd = find_passedi(marks_dict, cutoffs) |
| 53 | + print 'Passed =>',passd |
0 commit comments