Skip to content

Instantly share code, notes, and snippets.

@lopezm1
Created May 19, 2018 22:22
Show Gist options
  • Save lopezm1/74f74cc8a160ba046f45b1f706d08d8f to your computer and use it in GitHub Desktop.
Save lopezm1/74f74cc8a160ba046f45b1f706d08d8f to your computer and use it in GitHub Desktop.
Given an array of distinct integers and a sum value. Find count of triplets with sum smaller than given sum value.
import os
from itertools import combinations
#Given an array of distinct integers and a sum value. Find count of triplets with sum smaller than given sum value.
"""
Input : arr[] = {-2, 0, 1, 3}
sum = 2.
Output : 2
Explanation : Below are triplets with sum less than 2
(-2, 0, 1) and (-2, 0, 3)
"""
def findCombinations(arr, r):
# return list of all subsets of length r
# finds all combinations
return list(combinations(arr, r))
def findTriplets(numbers, val):
# Get all combinations
triplets = findCombinations(numbers, 3)
for trip in triplets:
if sum(trip) < val: # if triplet sum is smaller than sum value
print(trip)
findTriplets([-2,0,1,3], 2)
findTriplets([5, 1, 3, 4, 7], 12)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment