Skip to content

Instantly share code, notes, and snippets.

@cmattoon
Created October 18, 2015 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmattoon/abeed5fb8367b0b869cf to your computer and use it in GitHub Desktop.
Save cmattoon/abeed5fb8367b0b869cf to your computer and use it in GitHub Desktop.
Function Overloading - Alternative
#!/usr/bin/env python
from string import ascii_lowercase
def sum_list(values, ignore_invalid=True):
"""Returns the sum of a list of values.
String representations of integers ('0'-'9') are added at their
integer value, but letters have a value between 1-26.
(a=1, b=2, c=3, ...)
"""
total = 0
for value in values:
try:
# Try casting it to an int.
total += int(value)
except ValueError as e:
""" ValueError: invalid literal for int() with base 10: 'A' """
try:
assert len(value) is 1
total += (ascii_lowercase.index(value.lower()) + 1)
except (AssertionError, ValueError):
""" ValueError: substring not found """
if ignore_invalid is True:
continue
raise ValueError("Invalid value '%s'" % (str(value)))
return total
_tests_ = [
([], 0),
([1,2,3], 6),
(['A','B','C'], 6),
(['1','2','3'], 6),
(['a','b','c'], 6),
(['a','!', ' '], 1),
(['d', 'e', 3, 10, 'asdf'], 22),
(['d', 'e', 3, 10, 'abc'], 22), # ascii_lowercase.index('abc')
]
if __name__ == '__main__':
for test, expected in _tests_:
msg = "\033[92m PASS \033[0m"
answer = sum_list(test)
if answer != expected:
msg = "\033[91m FAIL \033[0m"
msg += "+%d\n" % (expected)
msg += "-%s\n" % (str(answer))
print msg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment