Knuth's algorithm S: Difference between revisions

Content added Content deleted
(added C)
Line 329: Line 329:


=={{header|Python}}==
=={{header|Python}}==
{{works with|Python|3.x}}
<lang python>from random import randrange
<lang python>from random import randrange


Line 405: Line 406:
elif randrange(i) < n:
elif randrange(i) < n:
# Keep item
# Keep item
del sample[randrange(n)]
sample[randrange(n)] = item
sample.append(item)
return sample</lang>
return sample</lang>
The above can be instantiated as follows after which <code>s_of_n</code> can be called in the same way as it is in the first example where it is a function instead of an instance.
The above can be instantiated as follows after which <code>s_of_n</code> can be called in the same way as it is in the first example where it is a function instead of an instance.