Hash a Range of Values

前端 未结 4 1137

I know that I can hash singular values as keys in a dict. For example, I can hash 5 as one of the keys in a dict.

I am current

4条回答
  •  长情又很酷
    2020-12-10 15:14

    As others have noted, the best algorithm you're going to get for this is something that's O(log N), not O(1), with something along the lines of a bisection search through a sorted list.

    The easiest way to do this in Python is with the bisect standard module, http://docs.python.org/library/bisect.html. Note, in particular, the example in section 8.5.2 there, on doing numeric table lookups -- it's exactly what you are doing:

    >>> def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
    ...     i = bisect(breakpoints, score)
    ...     return grades[i]
    ...
    >>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
    ['F', 'A', 'C', 'C', 'B', 'A', 'A']
    

    Replace the grades string with a list of functions, the breakpoints list with your list of lower thresholds, and there you go.

提交回复
热议问题