Python - Check if all tuples have element difference less than K
Last Updated :
16 May, 2023
Given a Tuple list, check if each tuple has a difference less than K.
Input : test_list = [(3, 4), (1, 2), (7, 8), (9, 13)], K = 2
Output : False
Explanation : 13 - 9 = 4 > 2.
Input : test_list = [(3, 4), (1, 2), (7, 8)], K = 2
Output : True
Explanation : All have abs. diff 1 < 2.
Method #1 : Using loop
In this, we keep a boolean variable and check if any element is greater than or equal to K, then mark it False and break.
Python3
# Python3 code to demonstrate working of
# Check if all tuples have element difference less than K
# Using loop
# initializing list
test_list = [(3, 4), (1, 2), (7, 8), (9, 8)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
res = True
for ele1, ele2 in test_list:
# using abs() to compute absolute difference
if abs(ele1 - ele2) >= K:
res = False
# printing result
print("Are all elements difference less than K ? : " + str(res))
OutputThe original list is : [(3, 4), (1, 2), (7, 8), (9, 8)]
Are all elements difference less than K ? : True
Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary space: O(1), as we are not using any extra data structures that depend on the size of the input.
Method #2 : Using all()
In this, we use all() to check if all the tuples have differences within K.
Python3
# Python3 code to demonstrate working of
# Check if all tuples have element difference less than K
# Using all()
# initializing list
test_list = [(3, 4), (1, 2), (7, 8), (9, 8)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
# shorthand to solve this problem
res = all(abs(sub1 - sub2) < K for sub1, sub2 in test_list)
# printing result
print("Are all elements difference less than K ? : " + str(res))
OutputThe original list is : [(3, 4), (1, 2), (7, 8), (9, 8)]
Are all elements difference less than K ? : True
Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary space: O(1), as only constant extra space is used to store the value of K and the result.
Method#3: Using Recursive method.
Python3
# Python3 code to demonstrate working of
# Check if all tuples have element difference less than K
# Using recursive function
def is_lessthanK(lst, K, start=0):
if start == len(lst): # base condition
return True
if abs(lst[start][0] - lst[start][1]) > K:
return False
return is_lessthanK(lst, K, start+1)
# initializing list
test_list = [(3, 4), (1, 2), (7, 8), (9, 8)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
# callling function and storing value
res = is_lessthanK(test_list, K)
# printing result
print("Are all elements difference less than K ? : " + str(res))
# this code contributed by tvsk
OutputThe original list is : [(3, 4), (1, 2), (7, 8), (9, 8)]
Are all elements difference less than K ? : True
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4 Using combinations
Using combinations from the itertools module to generate all possible pairs of tuples.
Approach:
- Import the combinations function from the itertools module.
- Generate all possible pairs of tuples using the combinations function.
- Iterate through each pair of tuples and calculate the absolute difference between each pair of elements in the two tuples.
- If the absolute difference is greater than or equal to K, return False.
- If all pairs have absolute differences less than K, return True.
Python3
from itertools import combinations
# function to check tuple differences
def check_tuple_difference(test_list, K):
for i, j in combinations(test_list, 2):
diff = abs(i[0]-j[0]) + abs(i[1]-j[1])
if diff >= K:
return False
return True
# Input list
test_list = [(3, 4), (1, 2), (7, 8), (9, 13)]
# Custom value
K = 2
print(check_tuple_difference(test_list, K))
Time complexity: O(n^2) because we generate all possible pairs of tuples.
Auxiliary Space: O(1)
Method #5: Using any() and filter() function
Approach:
- Initialize the test_list and K.
- Use the filter() function to filter out the tuples from the test_list that have an element difference greater than or equal to K.
- Check if any tuples are left in the filtered result using the any() function.
- Negate the result using the not operator to get the final result.
- Print the final result.
Python3
# initializing list
test_list = [(3, 4), (1, 2), (7, 8), (9, 8)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
res = not any(filter(lambda x: abs(x[0]-x[1])>=K, test_list))
# printing result
print("Are all elements difference less than K ? : " + str(res))
#This code is contributed by Vinay Pinjala.
OutputThe original list is : [(3, 4), (1, 2), (7, 8), (9, 8)]
Are all elements difference less than K ? : True
Time Complexity: O(n), where n is the length of test_list. The filter() function iterates over each tuple in the list once to check the element difference, and the any() function also iterates over the filtered result to check if any tuples are left.
Auxiliary Space: O(1), because we use only a single boolean variable to store the result. The filter() function and lambda function use negligible space, and the any() function does not create any additional data structure.
Method 6: Using numpy library
- Import the numpy module using the "import" statement.
- Create a list of tuples "test_list" with 4 tuples.
- Initialize an integer variable "K" with a value of 2.
- Convert the list of tuples "test_list" to a numpy array "arr" using the "numpy.array()" method.
- Perform element-wise subtraction on the numpy array "arr" using the expression "arr[:,0]-arr[:,1]".
- Take the absolute value of the result of step 5 using the "numpy.abs()" method.
- Check if all the elements in the numpy array from step 6 are less than the integer variable "K" using the "numpy.all()" method.
- Store the result of step 7 in a boolean variable "res".
- Print the value of "res" with an appropriate message.
Python3
import numpy as np
# initializing list
test_list = [(3, 4), (1, 2), (7, 8), (9, 8)]
# initializing K
K = 2
# converting list of tuples to numpy array
arr = np.array(test_list)
# using numpy element-wise operation and all() function
res = np.all(np.abs(arr[:, 0]-arr[:, 1]) < K)
# printing result
print("Are all elements difference less than K ? : " + str(res))
OUTPUT :
Are all elements difference less than K ? : True
Time complexity: O(n), where n is the length of the list, due to the element-wise operation and the all() function.
Auxiliary space: O(n), due to the use of the numpy array.
Method 7: Use the map() function along with the lambda function.
Step-by-step approach:
- Initialize the test_list and K values as given in the problem.
- Define a lambda function that takes each tuple from the test_list, finds the absolute difference between its elements, and checks if the difference is less than K. The lambda function returns True or False.
- Use the map() function to apply the lambda function to each tuple in the test_list. The map() function returns a list of True/False values.
- Use the all() function to check if all the values in the list are True.
- Print the result.
Python3
# initializing list
test_list = [(3, 4), (1, 2), (7, 8), (9, 8)]
# initializing K
K = 2
# using map() and lambda function
res_list = list(map(lambda x: abs(x[0]-x[1]) < K, test_list))
# using all() function
res = all(res_list)
# printing result
print("Are all elements difference less than K ? : " + str(res))
OutputAre all elements difference less than K ? : True
Time complexity: O(n), where n is the length of the test_list.
Auxiliary space: O(n), for storing the list of True/False values returned by the map() function.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read