Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to find list of triplets for which i+j+k is not same as n
Sometimes we need to find all possible combinations of three numbers that don't sum to a specific value. This problem involves generating all triplets (i, j, k) where each value is within given ranges and their sum is not equal to a target number n.
We can solve this efficiently using list comprehension with a filtering condition to exclude triplets that sum to n.
Problem Statement
Given three upper bounds i, j, and k, and a target sum n, find all triplets [x, y, z] where:
x ranges from 0 to i (inclusive)
y ranges from 0 to j (inclusive)
z ranges from 0 to k (inclusive)
x + y + z ? n
Example
Let's implement the solution using list comprehension ?
def solve(i, j, k, n):
arr = [[x, y, z] for x in range(i+1) for y in range(j+1) for z in range(k+1) if x+y+z != n]
return arr
# Test with example values
i = 1
j = 1
k = 2
n = 3
result = solve(i, j, k, n)
print("Triplets where sum is not equal to", n, ":")
for triplet in result:
print(triplet, "sum =", sum(triplet))
Triplets where sum is not equal to 3 : [0, 0, 0] sum = 0 [0, 0, 1] sum = 1 [0, 0, 2] sum = 2 [0, 1, 0] sum = 1 [0, 1, 1] sum = 2 [1, 0, 0] sum = 1 [1, 0, 1] sum = 2 [1, 1, 0] sum = 2 [1, 1, 2] sum = 4
How It Works
The list comprehension generates all possible combinations using nested loops:
for x in range(i+1)- generates values 0 to ifor y in range(j+1)- generates values 0 to jfor z in range(k+1)- generates values 0 to kif x+y+z != n- filters out triplets that sum to n
Alternative Approach with Nested Loops
Here's the same solution using traditional nested loops for better understanding ?
def solve_with_loops(i, j, k, n):
result = []
for x in range(i+1):
for y in range(j+1):
for z in range(k+1):
if x + y + z != n:
result.append([x, y, z])
return result
# Test the function
i, j, k, n = 1, 1, 2, 3
result = solve_with_loops(i, j, k, n)
print("Result using nested loops:")
print(result)
Result using nested loops: [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 2]]
Conclusion
List comprehension provides an elegant one-liner solution to generate filtered triplets. The condition x+y+z != n efficiently excludes unwanted combinations, making the code both readable and performant.
