Skip to content

Instantly share code, notes, and snippets.

@tdhopper
Created April 25, 2013 17:34
Show Gist options
  • Select an option

  • Save tdhopper/5461553 to your computer and use it in GitHub Desktop.

Select an option

Save tdhopper/5461553 to your computer and use it in GitHub Desktop.
Smallest Missing Number in a Python Iterable
def smallest_missing_number(stream, min_val, max_val, bin_exp):
###
# Returns the smallest counting number _not_ contained in a bounded
# sequence of counting numbers.
#
# Inputs:
# stream: iterator of integer values
# min_val: lower bound on values in stream
# max_val: upper bound on values in stream
# bin_exp: size of bin given as exponent of 2 (bin_size = 2^bin_exp)
# Output:
# The smallest counting number not in the stream
###
# If max = min, recusion is complete. Return value.
if max_val == min_val: return max_val
# Determine bin size.
if bin_exp > 0:
bin_size = 2 << bin_exp
else:
bin_size = 1
# Construct hashset to represent bins
bins = { i : 0 for i in xrange(0, (max_val - min_val) / bin_size + 1)}
# For each value in stream, increase the counter for its bin
for s in stream:
if s < min_val or s > max_val: continue
bin = (s - min_val) / bin_size
bins[bin] = bins[bin] + 1
# Iterate over bins. For the first bin that isn't full
# call this function where the max and min values
# are the max and mins of the bin. Also decrease the
# bin size
for i in xrange(0, (max_val - min_val) / bin_size + 1):
if bins[i] != bin_size:
return smallest_missing_number(
l,
min_val + bin_size * i,
min_val + bin_size * (i + 1) - 1,
max(bin_exp - 1, 0)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment