Created
May 19, 2018 22:22
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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