如何拆分数组但不使用循环



确定是否可以在某个索引处划分列表(lst(,使列表前部分的值之和等于列表后部分的值的和
不使用循环

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:]

是这样的吗?

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
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

这是一个递归函数。在很多情况下,递归是循环的替代方法。

总是会有一些循环在进行,但您可以使用递归或库函数来隐藏它们(如果您只是想避免for/while构造(:

例如:

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))

如果你只需要确定这是否可能,你可以返回sum(lst[:i](==sum(lst[i:](,或者更好的是简单地检查sum(lst(/2是否在累加(lst(中。

最新更新