0
votes
from bisect import bisect

grades = "FEDCBA"
breakpoints = [30, 44, 66, 75, 85]  

def grade(total):
    return grades[bisect(breakpoints, total)]

print(grade(66))
print(list(map(grade, [33, 99, 77, 44, 12, 88])))

'''
C
['E', 'A', 'B', 'D', 'F', 'A']

[Program finished]'''

Not my program. Imported from enki. Bisect module provides support for maintaining a list in sorted order without having to sort the list after each insertion. So, when we call grade(66). It passes 66 to the grade function which returns C, How? The second print statement is even more confusing. It is mapping function grade with a List. If I try to print, print (grades[bisect(breakpoints, grades)]), I get Err,

TypeError: '<' not supported between instances of 'str' and 'int'

2

2 Answers

0
votes

Your code produced the correct results for the data you fed it!

The breakpoint list [30, 44, 66, 75, 85] bisects the letter string "FEDCBA" as follows:

If         grade < 30 then F 
If   30 <= grade < 44 then E  
If   44 <= grade < 66 then D
If   66 <= grade < 75 then C 
If   75 <= grade < 85 then B
If   85 <= grade      then A

Therefore print(grade(66)) correctly resulted in an output of C.

Similarly, your print(list(map(grade, [33, 99, 77, 44, 12, 88]))) correctly resulted in an output of ['E', 'A', 'B', 'D', 'F', 'A'].

Now regarding your getting TypeError because of print (grades[bisect(breakpoints, grades)]), it just looks like you meant to do grades[bisect(breakpoints, total)] instead. Notice total instead of grades as the second argument to bisect().

Here's another version of the working code which puts all the variables at the top so you can change them easier for testing:

data_list = [33, 99, 77, 44, 12, 88]
grade_string = 'FEDCBA'
breakpoint_list = [30, 44, 66, 75, 85]
def grade(total, breakpoints=breakpoint_list, grades=grade_string):
    i = bisect(breakpoints, total)
    return grades[i]

print([grade(total) for total in data_list])

The output is:

['E', 'A', 'B', 'D', 'F', 'A']
0
votes
from bisect import bisect

grades = "FEDCBA"
breakpoints = [95, 44, 66, 75, 85]  


def grade(total):
    i = bisect(breakpoints, total)
    return grades[i]

print("Original Data:", [grade(total) for total in breakpoints ])
print("Data within print statement:",list(map(grade, [33, 99, 77, 44, 12, 88])))

Thanks Scott, Original Data: ['A', 'D', 'C', 'B', 'A'] Data within print statement: ['F', 'A', 'B', 'D', 'F', 'A'] I was able to produce the output I wanted for learning purpose