实现一个函数,以确定是否可以将数组拆分为相等数量的对



我正在尝试实现一个函数,将数组拆分为相等的部分,并返回true或false。

a=[2,4,4,2]应该返回true,因为我们可以在[2,2]和[4,4]中拆分

a=[4,4,4]应为假

a=[2,4,5,2]应返回错误

def soln(n):

# traverse array element 
for i in range(0, n) : 

# add current element to left Sum 
leftSum += arr[i]  

# find sum of rest array elements (rightSum) 
rightSum = 0 
for j in range(i+1, n) : 
rightSum += arr[j]  

# split poindex 
if (leftSum == rightSum) : 
return true 


# if it is not possible to split array into 
# two parts 
return false

Counter在这里非常有用,它会为您提供每个元素的出现次数:

from collections import Counter
Counter([2,4,4,2])
#Counter({2: 2, 4: 2})
from collections import Counter
def soln(arr):
counter = Counter(arr)

if len(counter) != 2:
return False

element_counts = list(counter.values())

return element_counts[0] == element_counts[1]
print(soln([2,4,4,2]))
# True
print(soln([2,4,4,3]))
# False

在纯Python中,您可以按如下方式执行:

def check_if_partable(given_list):
dictionary = {}
for i in given_list:
if i in dictionary:
dictionary[i] += 1
else:
dictionary[i] = 1
for v in dictionary.values():
if v % 2 != 0:
return False
return True

最新更新