Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you change:</p> <pre><code>return lo,pi,hi,len(lo)+1 </code></pre> <p>to:</p> <pre><code>return lo,pi,hi,len(lo) </code></pre> <p>and add a closing bracket <code>)</code> so that the syntax error is corrected, like so:</p> <pre><code>lo,pi,hi,loc_pi= random_partition(seq) </code></pre> <p>It will work reliably for sequences with no repeated entries:</p> <pre><code>for i in xrange(1,8): print rselect([54,-1,1000,565,64,2,5],7,i), #Output: -1 2 5 54 64 565 [1000] </code></pre> <p>Which is the expected output. </p> <p>I guess my main advice would be to try and code following the <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">style guidlines!</a> Your code is pretty tricky to read at a glance!</p> <p>The parameter <code>length</code> is redundant, so can be removed altogether. And also sometimes the last entry would be returned as a single value list, so I've changed that (although it will know fall over if you pass it an empty list, probably not a big deal). Here is the code in slightly more readable format, with a correction to allow for repeated entries:</p> <pre><code>from random import choice, shuffle def rselect(seq, i):     lo, hi, pi, loc_pi = random_partition(seq)     if loc_pi == i or (min(lo) == max(lo) and not hi):         return pi     elif loc_pi &gt; i:         return rselect(lo, i)     elif loc_pi &lt; i:         return rselect(hi, i - loc_pi) def random_partition(seq):     pi = choice(seq)     lo = [x for x in seq if x &lt;= pi]     hi = [x for x in seq if x &gt; pi]     return lo, hi, pi, len(lo) #this is a nice way to test it: cat = range(1,21) for i in xrange(1,21):     shuffle(cat)     print rselect(cat,i), #Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 </code></pre>
    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.
 

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