Created
October 18, 2015 15:57
-
-
Save cmattoon/abeed5fb8367b0b869cf to your computer and use it in GitHub Desktop.
Function Overloading - Alternative
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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