Determine if it possible to divide a list (lst) at some index such that the sum of values in the first part of the list equals the sum in the latter part of the list.
No loops are used.
def split_array2(lst, all_sum=0):
first = split_array(lst[0:-1])
last = lst[-1]
def sum_(lst):
if len(lst) == 0:
return 0
return lst[0] sum_[1:]
CodePudding user response:
So something like this?
def canBeSplitted(lst,ind=1):
if ind == len(lst):
return false
return sum(lst[0:ind]) == sum(lst(ind:)) || canBeSplitted(lst,ind 1)
canBeSplitted(lst) #usage
CodePudding user response:
a = [1, 2, 3, 4, 5, 7, 8]
def split_array(a, i=1): # changed to 1 to save 1 function call. AND to be sure that there is a valid split when sum(a)=0.
if i == len(a):
return False
if sum(a[:i]) == sum(a[i:]):
return i
return split_array(a, i 1)
split_array(a)
>>> 5
#sum(a[:5]) = 15
#sum(a[5:]) = 15
This is a recursive function. Recursion is in a lot of cases an alternative to loops.
CodePudding user response:
There is always going to be some loops going on but you can hide them using recursion or library functions (if you're merely aiming to avoir the for/while constructs):
For example:
from itertools import accumulate
from bisect import bisect_right
def splitsum(lst):
i = bisect_right([*accumulate(lst)],sum(lst)/2)
return lst[:i],lst[i:]
L = [1,2,3,4,5,7,8]
print(*splitsum(L))
If you only need to determine if it is possible or not, you could return sum(lst[:i])==sum(lst[i:]) or better yet simply check if sum(lst)/2 is in accumulate(lst).
