Skip to content

Instantly share code, notes, and snippets.

@r3
Created May 3, 2012 22:52
Show Gist options
  • Save r3/2590147 to your computer and use it in GitHub Desktop.
Save r3/2590147 to your computer and use it in GitHub Desktop.
Project Euler #1 (prior to refactor)
# The name doesn't well reflect what the function does (as Ilya pointed
# out), but after the refactor, this will be fixed
def find_multiples(factors, end=1000, func=sum):
"""Creates a list of multiples less than a given end
value (1000 by default) from the given factors and
applies a function to them (sum by default).
"""
result = set()
# This is the block that may generate an error, so we
# wrap it in a 'try' context. So long as no errors
# occur, it will execute and skip the 'except' block
try:
for factor in factors:
multiples = [x for x in range(factor, end, factor)]
result.update(set(multiples))
return func(result)
# Here, we catch the error that will occur when we try to iterate
# over a non-iterable (like an integer) in the for-loop.
# We do nothing with the error (and implicitly return None)
# If errors other than 'TypeError' occurs, it will not be caught
# and will cause the program to break
except TypeError as e:
pass
if __name__ == '__main__':
# A few simple test cases. Certainly not extensive, but enough
# to ensure that this example code is valid.
assert find_multiples([3, 5]) == 233168
assert find_multiples([1], 10) == 45
assert find_multiples([2, 3], func=lambda *x: 0) == 0
assert find_multiples(23) == None
print(find_multiples([3, 5]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment