I read a bit about this topic and found that I have to return the Function instead of a value...but I dont to get it to Work in this specific case:
'''Recursive Solution'''
def find_even_index(arr, index=0):
#break condition if non found
if len(arr) == index:
return -1
#init sum vars
sum_up = 0
sum_down = 0
#calculate up
for x in range(0, index):
sum_up += arr[x]
print(sum_up)
#caculate down
for x in range(index + 1, len(arr)):
sum_down += arr[x]
print(sum_down)
#break condition if found
if sum_up == sum_down:
print('return: ', index)
return index
index = index + 1
find_even_index(arr, index)
Here are the Test-Cases:
Test.assert_equals(find_even_index([1,2,3,4,3,2,1]),3)
Test.assert_equals(find_even_index([1,100,50,-51,1,1]),1,)
Test.assert_equals(find_even_index([1,2,3,4,5,6]),-1)
Test.assert_equals(find_even_index([20,10,30,10,10,15,35]),3)
Test.assert_equals(find_even_index([20,10,-80,10,10,15,35]),0)
Test.assert_equals(find_even_index([10,-80,10,10,15,35,20]),6)
Test.assert_equals(find_even_index(range(1,100)),-1)
Test.assert_equals(find_even_index([0,0,0,0,0]),0,"Should pick the first
index if more cases are valid")
Test.assert_equals(find_even_index([-1,-2,-3,-4,-3,-2,-1]),3)
Test.assert_equals(find_even_index(range(-100,-1))
And here is the initial Task:
You are going to be given an array of integers. Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1.
EDIT: (The Solution)
Ok, so I figured it out. I read through different other Questions about this Topic and came to the conclusion that I should have done it the other way around i.e. return the function in case of unsuccess.
So I had to put the returnvalue at the end of the function and just in case of unsuccess call the function recursively:
'''Recursive Solution'''
def find_even_index(arr, index=0):
#break condition if non found
if len(arr) == index:
return -1
#init sum vars
sum_up = 0
sum_down = 0
#calculate up
for x in range(0, index):
sum_up += arr[x]
#caculate down
for x in range(index + 1, len(arr)):
sum_down += arr[x]
#break condition if found
if sum_up != sum_down:
index = index + 1
return find_even_index(arr, index)
return index