fork download
  1. def pairSum(array,target,currentIndex):
  2. start=0
  3. end=len(array)-1
  4. while(start<end):
  5. if start==currentIndex:
  6. start+=1
  7. continue
  8. if end==currentIndex:
  9. end-=1
  10. continue
  11. if array[start]+array[end]==target:
  12. return [array[start],array[end]]
  13. elif array[start]+array[end]<target:
  14. start+=1
  15. elif array[start]+array[end]>target:
  16. end-=1
  17. return [-1,-1]
  18.  
  19. def tripletSum(array, target):
  20. countOfTriplets = 0
  21. for i in range(len(array)):
  22. newTarget = target - array[i]
  23. pairForNewTarget = pairSum(array,newTarget,i)
  24. if(pairForNewTarget[0]!=-1):
  25. countOfTriplets+=1
  26. if countOfTriplets >0 :
  27. return countOfTriplets//3
  28. else:
  29. return 0
  30.  
  31. def wrapperFunction():
  32. array = [int(i) for i in input().split()]
  33. target = int(input())
  34. array.sort()
  35. pair = pairSum(array,target,-1)
  36. numberOfTriplets = tripletSum(array, target)
  37. print("There exists a pair (" + str(pair[0]) + ", " + str(pair[1]) + ") whose sum is equal to target.")
  38. print("There exists total " + str(numberOfTriplets) + " triplets whose sum is equal to target." )
  39.  
  40. wrapperFunction()
Success #stdin #stdout 0.02s 9456KB
stdin
5 4 3 2 1
9
stdout
There exists a pair (4, 5) whose sum is equal to target.
There exists total 1 triplets whose sum is equal to target.