Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep ranges with python?

I should keep ranges (with different intervals) and according values like below:

  • 0..5000: 1234
  • 5001..10000: 1231
  • 10001..20000: 3242
  • ...
  • 50001..100000: 3543
  • 100001..200000: 2303
  • ...

How should I store it? As dict like {'0': 1234, '5001': 1231, '10001': 3242, ...}?

Once stored, I will need to search for according value, but it should look for a range - for ex., 6000 should return 1231. If I store it as dict, how should I perform the search?

Upd. There are no gaps in the intervals and number of ranges is quite small (~50).

like image 388
LA_ Avatar asked Dec 26 '22 04:12

LA_


1 Answers

I would recomend you store it as a list of dictionaries because:

Explicit is better than implicit.

>>> rang = [{'start': 0, 'end': 5000, 'id': 1234}, {'start': 5000, 'end': 10000, 'id': 1231}, {'start': 10001, 'end': 20000, 'id': 342}]
>>> num = 10
>>> for r in rang:
...   if r['start'] < num < r['end']:
...     print r['id']
... 
1234
>>> num = 10500
>>> for r in rang:
...   if r['start'] < num < r['end']:
...     print r['id']
... 
342
>>> 
like image 164
Vor Avatar answered Dec 31 '22 12:12

Vor