mirror of https://github.com/python/cpython.git
SF bug #753602: random.sample not properly documented
The docs were fine but the "int=int" in the function call was both ugly and confusing. Moved it inside the body of the function definition.
This commit is contained in:
parent
43e559a155
commit
fdbe5223b7
|
@ -207,7 +207,7 @@ def shuffle(self, x, random=None, int=int):
|
||||||
j = int(random() * (i+1))
|
j = int(random() * (i+1))
|
||||||
x[i], x[j] = x[j], x[i]
|
x[i], x[j] = x[j], x[i]
|
||||||
|
|
||||||
def sample(self, population, k, int=int):
|
def sample(self, population, k):
|
||||||
"""Chooses k unique random elements from a population sequence.
|
"""Chooses k unique random elements from a population sequence.
|
||||||
|
|
||||||
Returns a new list containing elements from the population while
|
Returns a new list containing elements from the population while
|
||||||
|
@ -240,19 +240,20 @@ def sample(self, population, k, int=int):
|
||||||
if not 0 <= k <= n:
|
if not 0 <= k <= n:
|
||||||
raise ValueError, "sample larger than population"
|
raise ValueError, "sample larger than population"
|
||||||
random = self.random
|
random = self.random
|
||||||
|
_int = int
|
||||||
result = [None] * k
|
result = [None] * k
|
||||||
if n < 6 * k: # if n len list takes less space than a k len dict
|
if n < 6 * k: # if n len list takes less space than a k len dict
|
||||||
pool = list(population)
|
pool = list(population)
|
||||||
for i in xrange(k): # invariant: non-selected at [0,n-i)
|
for i in xrange(k): # invariant: non-selected at [0,n-i)
|
||||||
j = int(random() * (n-i))
|
j = _int(random() * (n-i))
|
||||||
result[i] = pool[j]
|
result[i] = pool[j]
|
||||||
pool[j] = pool[n-i-1] # move non-selected item into vacancy
|
pool[j] = pool[n-i-1] # move non-selected item into vacancy
|
||||||
else:
|
else:
|
||||||
selected = {}
|
selected = {}
|
||||||
for i in xrange(k):
|
for i in xrange(k):
|
||||||
j = int(random() * n)
|
j = _int(random() * n)
|
||||||
while j in selected:
|
while j in selected:
|
||||||
j = int(random() * n)
|
j = _int(random() * n)
|
||||||
result[i] = selected[j] = population[j]
|
result[i] = selected[j] = population[j]
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue