Python Forum

Full Version: compacting multiple ranges
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i have two or more int, float, Decimal, string, or bytes (anything simple and sortable) non-overlapping ranges, like maybe:
1...1000, 2000...4000, 9000....
or maybe:
'alice'...'carol', 'wanda'...'zelda'

i want to apply a value test across the ranges so that a return value associated with each range is return (or yielded)
so in the above examples i might have:
1...1000:1, 2000...4000:2, 9000....:3 default:0
'alice'...'carol':400, 'wanda'...'zelda':800 default:600

i'm curious what tools are commonly used or what coding style/pattern is used when trying to map a value that could be in one of the ranges to a value (maybe the same type or maybe different) associated with the range it is in.

for functions doing this perhaps a way to represent these ranges with a mapped value could have integrated values like:
[(1,1,1000),(2,2000,4000)(3,9000),0]
[(400,'alice',carol'),(800,'wanda','zelda'),600]

or separated values like:
[(1,1000),(2000,4000)(9000,)] and [1,2,3,0]
[('alice',carol'),('wanda','zelda')] and [400,800,600]

or the default value could be given as a separate argument.

any suggestions or ideas?  i'm sure a need for this have come up many times, already.
With such a small set of output values, the easiest approach is if-then-else statements:
Pseudocode:

if <s in range_1>:
return 1
elif <s in range_2>:
return 2
...

<s in range_1> could be implemented as one of these:

s in ('Alice',...,'Carol') # tuple
s in ['Alice',...,'Carol'] #list

If you had a much larger set of output values, it would be best to use a dict:
range_1 = {'Alice': 1,...,'Carol:1}

If you have both a reasonably large set of input and output values, you can just use a dict:
range = {'Alice':1,...,'Wanda':93}
i am looking for a function that can do a variable number of ranges and can work with any type that can compare with another of the same type that can be compared with < and/or > (including immutable sequences).