This is part from an answer to a Stack Overflow question. The OP needed a way to perform calculations on samples from a population, but was hitting memory errors due to keeping samples in memory.
The function is based on part of random.sample, but only the code branch using a set is present.
If we can tidy and comment this well enough, it might be worth publishing as a recipe at the Python Cookbook.
import random def sampling_mean(population, k, times): # Part of this is lifted straight from random.py _int = int _random = random.random n = len(population) kf = float(k) result =  if not 0 <= k <= n: raise ValueError, "sample larger than population" for t in xrange(times): selected = set() sum_ = 0 selected_add = selected.add for i in xrange(k): j = _int(_random() * n) while j in selected: j = _int(_random() * n) selected_add(j) sum_ += population[j] # Partial result we're interested in mean = sum_/kf result.append(mean) return result sampling_mean(x, 1000000, 100)
Maybe it'd be interesting to generalize it so you can pass a function that calculates the value you're interested in from the sample?