Last active
December 14, 2015 00:08
-
-
Save oliland/4996396 to your computer and use it in GitHub Desktop.
Solution for "Array Addition 1" on coderbyte. We sort the list of numbers, then pop off the largest. We then walk down the reversed array subtracting until we hit 0 or until we go below 0 - if we go below 0 we skip subtracting that number. If we reach the end of the list and haven't hit 0 yet, then we just pop off the largest number and repeat t…
This file contains 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
def array_addition(array): | |
array = sorted(array) | |
largest = array.pop() | |
while (True): | |
result = largest | |
for x in reversed(array): | |
result = result - x | |
if result == 0: | |
return True | |
elif result < 0: | |
result = result + x | |
# If we each the end of the list and haven't returned, pop the largest off | |
try: | |
array.pop() | |
except: | |
return False | |
def main(): | |
tests = [ | |
([1,2,3,4], True), | |
([2,6,18], False), | |
([10,20,30,40,100], True), | |
([31,2,90,50,7], True), | |
([2,4,6,12,92], False), | |
([1,1,1,1,6], False), | |
([-2,-3,-4,-1,100], False), | |
([54,49,1,0,7,4], True), | |
([3,4,5,7], True), | |
([10,12,500,1,-5,1,0], False) | |
] | |
for array, answer in tests: | |
result = array_addition(array) | |
if result != answer: | |
print "WRONG" | |
else: | |
print "RIGHT" | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I was happy to find your code here, but unfortunately I think there may be a problem with the algorithm: try this array: [14,10,3,2,2]. It will add on the 3, but the correct answer requires both 2s but no 3...
Roy