4. Given an array of ints, your function should determine if it is possible to divide the numbers into two groups, so that the sums of the two groups are the same. Every number must be in one group or the other. You may add a "helper method" (this is a function that is called from within your recursive function). Your initial call should be to your recursive function with the helper function being called from within the recursive function. (If you don't need a "helper", that's ok too!). Define your function as sameSums(aList). The function should return true (the list can be split to contain two groups with the same sums) or false (it cannot be split to contain two groups with the same sum). For example:
sameSums([4, 7, 6, 3]) --> True //4+6 = 10 and 7 + 3 = 10
sameSums([3, 3]) --> True
sameSums([4, 12, 16]) --> True //4+12= 16 and 16
sameSums([5, 1]) --> False
You may use the built-in sum() function for this question but remember that your solution must be recursive.
Result = False # To judge the varaible of the result to question 4
def func(L):#This function numerates all different kinds of combinations in the list
for i in range(1, len(L)):
LL = L[i:]
for j in range(len(LL)):
v = len(LL) - j
s1 = LL[:v]
s2 = L[:i]
s3 = LL[v:]
#print(s2+s3, s1)
if sum(s2+s3) == sum(s1):#Judge are there any situation is equal or not
return True
def sameSums(aList, r = 0):
global Result
n = len(aList)-1
if r == n:
l=[]
ll=l.append
for i in range(n+1):
ll(aList[i])
if func(l):# Call helper function to judge are there any equal situation
Result = True
else:
Result = False
for i in range(r,n+1):
aList[r],aList[i] = aList[i],aList[r]
sameSums(aList, r+1)#recursion
aList[r],aList[i] = aList[i],aList[r]
return Result
这个上面是别人的写法而且当print(sameSums([])) 时会无法运行。
如果有人能帮忙解出来的话,小弟会直接私信转账。真的很急谢谢
sameSums([4, 7, 6, 3]) --> True //4+6 = 10 and 7 + 3 = 10
sameSums([3, 3]) --> True
sameSums([4, 12, 16]) --> True //4+12= 16 and 16
sameSums([5, 1]) --> False
You may use the built-in sum() function for this question but remember that your solution must be recursive.
Result = False # To judge the varaible of the result to question 4
def func(L):#This function numerates all different kinds of combinations in the list
for i in range(1, len(L)):
LL = L[i:]
for j in range(len(LL)):
v = len(LL) - j
s1 = LL[:v]
s2 = L[:i]
s3 = LL[v:]
#print(s2+s3, s1)
if sum(s2+s3) == sum(s1):#Judge are there any situation is equal or not
return True
def sameSums(aList, r = 0):
global Result
n = len(aList)-1
if r == n:
l=[]
ll=l.append
for i in range(n+1):
ll(aList[i])
if func(l):# Call helper function to judge are there any equal situation
Result = True
else:
Result = False
for i in range(r,n+1):
aList[r],aList[i] = aList[i],aList[r]
sameSums(aList, r+1)#recursion
aList[r],aList[i] = aList[i],aList[r]
return Result
这个上面是别人的写法而且当print(sameSums([])) 时会无法运行。
如果有人能帮忙解出来的话,小弟会直接私信转账。真的很急谢谢