Last active
July 23, 2021 20:38
-
-
Save CraigTheKiwi/6744588cbbf6e5e2944103550ec6ec62 to your computer and use it in GitHub Desktop.
Solution for Cassidoo Newsletter (July 19) in Python
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
#!/bin/python3 | |
def subarraySum(arr, n): | |
arr_len = len(arr) | |
count = 0 | |
for x in range(0, arr_len - 1): | |
total = arr[x] | |
for y in range(x+1, arr_len): | |
total += arr[y] | |
if total == n: | |
count += 1 | |
return -1 if count==0 else count | |
def subarraySum2(arr, n): | |
count = 0 | |
for x in range(len(arr)-1): | |
for y in range(x+1, len(arr)): | |
if sum(arr[x:y+1]) == n: | |
count += 1 | |
return -1 if count==0 else count | |
if __name__ == '__main__': | |
arr = [ 10, 2, -2, -20, 10 ] | |
n = -10 | |
print(subarraySum(arr, n)) | |
print(subarraySum2(arr, n)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment