Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Random fact: Abraham Lincoln was the first president to ever be photographed at his inauguration. solution in Clear category for Compare Functions by siebenschlaefer
def checkio(f, g):
"""Return a combination of primary/backup functions 'f'/'g'."""
def h(*args, **kwargs):
return status_for_results(f, g, *args, **kwargs)
return h
def status_for_results(f, g, *args, **kwargs):
"""Return the result of primary/backup functions 'f'/'g'."""
f_result = result_or_none(f, *args, **kwargs)
g_result = result_or_none(g, *args, **kwargs)
if f_result is None and g_result is None:
result = (None, "both_error")
elif g_result is None:
result = (f_result, "g_error")
elif f_result is None:
result = (g_result, "f_error")
elif f_result == g_result:
result = (f_result, "same")
else:
result = (f_result, "different")
return result
def result_or_none(func, *args, **kwargs):
"""Return 'func(*args, **kwargs)' or None if an execption occured."""
try:
return func(*args, **kwargs)
except:
return None
def test_checkio():
# (x+y)(x-y)/(x-y)
assert checkio(lambda x,y:x+y,
lambda x,y:(x**2-y**2)/(x-y))\
(1,3)==(4,'same'), "Function: x+y, first"
assert checkio(lambda x,y:x+y,
lambda x,y:(x**2-y**2)/(x-y))\
(1,2)==(3,'same'), "Function: x+y, second"
assert checkio(lambda x,y:x+y,
lambda x,y:(x**2-y**2)/(x-y))\
(1,1.01)==(2.01,'different'), "x+y, third"
assert checkio(lambda x,y:x+y,
lambda x,y:(x**2-y**2)/(x-y))\
(1,1)==(2,'g_error'), "x+y, fourth"
# Remove odds from list
f = lambda nums:[x for x in nums if ~x%2]
def g(nums):
for i in range(len(nums)):
if nums[i]%2==1:
nums.pop(i)
return nums
assert checkio(f,g)([2,4,6,8]) == ([2,4,6,8],'same'), "evens, first"
assert checkio(f,g)([2,3,4,6,8]) == ([2,4,6,8],'g_error'), "evens, second"
# Fizz Buzz
assert checkio(lambda n:("Fizz "*(1-n%3) + "Buzz "*(1-n%5))[:-1] or str(n),
lambda n:('Fizz'*(n%3==0) + ' ' + 'Buzz'*(n%5==0)).strip())\
(6)==('Fizz','same'), "fizz buzz, first"
assert checkio(lambda n:("Fizz "*(1-n%3) + "Buzz "*(1-n%5))[:-1] or str(n),
lambda n:('Fizz'*(n%3==0) + ' ' + 'Buzz'*(n%5==0)).strip())\
(30)==('Fizz Buzz','same'), "fizz buzz, second"
assert checkio(lambda n:("Fizz "*(1-n%3) + "Buzz "*(1-n%5))[:-1] or str(n),
lambda n:('Fizz'*(n%3==0) + ' ' + 'Buzz'*(n%5==0)).strip())\
(7)==('7','different'), "fizz buzz, third"
if __name__ == '__main__':
test_checkio()
April 1, 2016
Comments: