How Do You Use the Bisect Module in Python?

Problem scenario
You want to use bisect in Python. How do you do this?

Solution

# This program was adapted from code found 
# https://docs.python.org/3/library/bisect.html

import bisect
def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
     i = bisect.bisect(breakpoints, score)
     return grades[i]

x = [grade(score) for score in [71, 88, 94]]
print(x)
import bisect
def whether(temperature, breakpoints=[38, 70, 80, 100], descriptors=["cold", "cool", "warm", "hot", "very hot"]):
     i = bisect.bisect(breakpoints, temperature)
     return descriptors[i]

#descriptions = [whether(temperature) for temperature in [71, 88, 94]]
descriptions = [whether(temperature) for temperature in [11, 68, 104]]

Leave a comment

Your email address will not be published. Required fields are marked *