Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The accepted solution (as well as my first attempt) failed due to the ambiguity inherent in the specs: <code>'.'</code> may be "just a separator" <strong>or</strong> a part of the actual key string. Consider, for example, that <code>key</code> may be <code>'a.b.c.d.e.f'</code> and the actual key to use at the current level is <code>'a.b.c.d'</code> with <code>'e.f'</code> left over for the next-most-indented level. Also, the spec is ambiguous in another sense: if more than one dot-joined prefix of <code>'key'</code> is present, which one to use?</p> <p>Assume the intention is to try <em>every</em> such feasible prefix: this would possibly produce multiple solutions but we can arbitrarily return the first solution found in this case.</p> <pre><code>def getitem(key, context): stk = [(key.split('.'), context)] while stk: kl, ctx = stk.pop() if not kl: return ctx if kl[0].isdigit(): ik = int(kl[0]) try: stk.append((kl[1:], ctx[ik])) except LookupError: pass for i in range(1, len(kl) + 1): k = '.'.join(kl[:i]) if k in ctx: stk.append((kl[i:], ctx[k])) raise KeyError(key) </code></pre> <p>I was originally trying to avoid <em>all</em> <code>try/except</code>s (as well as recursion and introspection via <code>hasattr</code>, <code>isinstance</code>, etc), but one snuck back in: it's hard to check if an integer is an acceptable index/key into what might be either a dict or a list, without either some introspection to distinguish the cases, <em>or</em> (and it looks simpler here) a <code>try/except</code>, so I went fir te latter, simplicity being always near the top of my concerns. Anyway...</p> <p>I believe variants on this approach (where all the "possible continuation-context pairs" that might still be feasible at any point are kept around) are the only working way to deal with the ambiguities I've explained above (of course, one might choose to collect <em>all</em> possible solutions, arbitrarily pick one of them according to whatever heuristic criterion is desire, or maybe raise if the ambiguity is biting so there are multiple solutions, etc, etc, but these are minor variants of this general idea).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload