0

Looking for a way to write the dictionary constant.

For example,

EXAMPLE = {0~10: 'low', 11-20: 'medium', 21:30: 'high}

is there a way to code 0~10 where I can do EXAMPLE[5] and it will output 'low'?

  • In `O(1)` or is `O(N)` ok, too? – user2390182 Jan 15 '18 at 03:27
  • I do not understand your question. – user9217105 Jan 15 '18 at 03:28
  • @cᴏʟᴅsᴘᴇᴇᴅ, are you saying I have to write it like EXAMPLE = {0:'low', 1:'low'... etc} ? – user9217105 Jan 15 '18 at 03:29
  • That, or use some external library which gives you that functionality. – cs95 Jan 15 '18 at 03:31
  • @cᴏʟᴅsᴘᴇᴇᴅ This will only work for integers, though – user2390182 Jan 15 '18 at 03:31
  • Why not just use if statements? if n <= 10: print('low') elif n <= 20: print('medium') elif n <= 30: print('high') else: pass # handle it however you want – Niema Moshiri Jan 15 '18 at 03:33
  • @cᴏʟᴅsᴘᴇᴇᴅ None of the answers there actually address the generic issue of getting `O(N)` range lookup. The one "library" does iterate the underlying dict :) – user2390182 Jan 15 '18 at 03:34
  • @schwobaseggl Yep, I don't think there's a way around the O(N) without replicating data. – cs95 Jan 15 '18 at 03:35
  • @cᴏʟᴅsᴘᴇᴇᴅ yes there is. – wim Jan 15 '18 at 03:36
  • @wim If there is (well, there probably is), I'd love to see an answer on one of the marked dupes! – cs95 Jan 15 '18 at 03:38
  • @cᴏʟᴅsᴘᴇᴇᴅ Of the top of my head I think I could cook up a tree based `O(logN)` approach... – user2390182 Jan 15 '18 at 03:41
  • @schwobaseggl Like https://stackoverflow.com/a/34718595/4909087? – cs95 Jan 15 '18 at 03:42
  • more like https://stackoverflow.com/questions/6852283/key-lookup-from-a-data-structure-based-on-range – wim Jan 15 '18 at 03:42
  • @wim Hmm.. Do you know of any`O(1)` algorithm for arbitrary ranges when the ranges aren't as regular that there is a simple function (like floor) that can calculate the range from the value. – user2390182 Jan 15 '18 at 03:45
  • Nope, I only know O(log n). I'm not saying O(1) doesn't exist, just that I don't know how to do it.. – wim Jan 15 '18 at 03:47
  • You can have some clever hash function to do so. For example, in this one, you can have `vals=['low','medium','high']`, and for some arbitrary number `n`, you can do `vals[n%10]`. You can likely do something similar for whatever case you're thinking of as long as you're guaranteed a continuous mapping from inputs to outputs – Niema Moshiri Jan 15 '18 at 03:51
  • @wim That's how I should start wording my sentences from now on. Thanks for the link. – cs95 Jan 15 '18 at 04:12

0 Answers0