Python 3 Write a function, triple_sum(a,x), that takes a list ,a, as input and r
ID: 3768413 • Letter: P
Question
Python 3
Write a function, triple_sum(a,x), that takes a list ,a, as input and returns True if there exists i, j and k (where i and j and k are not necessarily distinct) such that a[i]+a[j]+a[k]=x. Otherwise it returns False. For example, if a=[1, 5, 8, 2, 6, 55, 90] and x=103, then triple_sum(a, x) would return True since a[1]+a[2]+a[6]=5+8+90=103. If a=[-1, 1, 5, 8, 2, 6] and x=-3, triple_sum(a, x) would return True since a[0]+a[0]+a[0]=-1+ -1 + -1 = -3. If a=[-10,2] and x=-18, triple_sum(a, x) would return True since a[0]+a[0]+a[1]=-10+-10+2=18. If a=[1, 1, 5, 8, 2, 6] and x=1000 would return False, since there are not indices i, j and k such that a[i]+a[j]+a[k]=1000.
Explanation / Answer
def triple_sum(a,x) :
a.sort()
size = len(a) - 1;
for i in range(0,7):
j = i + 1
k = size
while j <= k :
if 3*a[i] == x or a[i] + 2*a[j] == x or a[i] + 2*a[size] == x or a[i] + a[j] + a[k] == x:
return 1
elif a[i] + a[j] + a[k] > x :
k -= 1
else :
j += 1
return 0
print triple_sum([1, 5, 8, 2, 6, 55, 90],103)
print triple_sum([-1, 1, 5, 8, 2, 6],-3)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.