bisect

时间:2021-12-27 22:17:52
# 二分查找算法
import bisect farm = sorted(['haystack', 'needle', 'cow', 'pig'])
# ['cow', 'haystack', 'needle', 'pig'] #在保证列表有序的情况下给出要插入的新元素的索引位置
#bisect.bisect
#bisect.bisect_left
#bisect.bisect_right
#已经存在的值插入
bisect.bisect(farm, 'needle') #
bisect.bisect_left(farm, 'needle') #
bisect.bisect_right(farm, 'needle') #
bisect.bisect(farm, 'chicken') # #bisect.insort
#bisect.insort_left
#bisect.insort_right
bisect.insort(farm, 'eggs')
# ['cow', 'eggs', 'haystack', 'needle', 'pig']
import bisect

def grade(score, breakpoints = [60, 70, 80, 90], grades = 'FDCBA'):
i = bisect.bisect(breakpoints, score)
return grades[i] grade(66) #D
grade(99) #A