Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Mapping from intervals to values

Tags:

I'm refactoring a function that, given a series of endpoints that implicitly define intervals, checks if a number is included in the interval, and then return a corresponding (not related in any computable way). The code that is now handling the work is:

if p <= 100:     return 0 elif p > 100 and p <= 300:     return 1 elif p > 300 and p <= 500:     return 2 elif p > 500 and p <= 800:     return 3 elif p > 800 and p <= 1000:     return 4 elif p > 1000:     return 5 

Which is IMO quite horrible, and lacks in that both the intervals and the return values are hardcoded. Any use of any data structure is of course possible.

like image 900
Agos Avatar asked Jul 29 '09 09:07

Agos


People also ask

How do you map a value in Python?

You can use the Python map() function with a String. While using the map() with a String, the latter will act like an array. You can then use the map() function as an iterator to iterate through all the string characters.

What are intervals in Python?

What is interval in Python? Intervals are immutable objects that can be created by specifying their connected components: >>> k = interval([0, 1], [2, 3], [10, 15]) creates an object representing the union of the mathematical intervals [0, 1], [2, 3] and [10, 15].

How does map function work in Python?

Python's map() is a built-in function that allows you to process and transform all the items in an iterable without using an explicit for loop, a technique commonly known as mapping. map() is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable.


2 Answers

import bisect bisect.bisect_left([100,300,500,800,1000], p) 

here the docs: bisect

like image 158
Glenn Maynard Avatar answered Sep 17 '22 03:09

Glenn Maynard


You could try a take on this:

def check_mapping(p):     mapping = [(100, 0), (300, 1), (500, 2)] # Add all your values and returns here      for check, value in mapping:         if p <= check:             return value  print check_mapping(12) print check_mapping(101) print check_mapping(303) 

produces:

0 1 2 

As always in Python, there will be any better ways to do it.

like image 32
kjfletch Avatar answered Sep 17 '22 03:09

kjfletch