Sometimes, while working with Python tuples, we can have a problem in which we need to extract all the tuples, which have all the elements in target tuple. This problem can have application in domains such as web development. Let's discuss certain way in which this problem can be solved.
Input : test_list = [(5, 6, 6), (4, 2, 7), (9, 6, 5, 6)] test_tuple = (6, 6) Output : [(5, 6, 6), (9, 6, 5, 6)] Input : test_list = [(5, 6, 6), (4, 2, 6), (9, 6, 5, 6)] test_tuple = (6, ) Output : [(5, 6, 6), (4, 2, 6), (9, 6, 5, 6)]
Output : The original list is : [(5, 6, 8), (4, 2, 7), (9, 6, 5, 6)]
The superset tuples : [(9, 6, 5, 6)]
Time Complexity: O(n*n) where n is the number of elements in the in the list “test_list”. The Counter() + list comprehension + all() is used to perform the task and it takes O(n*n) time.
Auxiliary Space: O(n), the algorithm uses an additional list to store the result, thus consuming linear space which is O(n).
Iterate through each tuple in the list.Check if the test tuple is a subset of the current tuple using the set() method.
If it is a subset, add the current tuple to a new list, which will contain all the supersets of the test tuple. Return the new list of supersets
1. Initialize a new empty list called result.
2. Loop through each tuple in the given list.
3. If the test tuple is a subset of the current tuple, append the current tuple to the result list.
4. Return the result list.
Output[(5, 6, 6), (9, 6, 5, 6)]
Time complexity: O(n*m) where n is the length of the list and m is the length of the longest tuple in the list. This is because we need to loop through each tuple in the list, and also need to check if the test tuple is a subset of each tuple, which takes O(m) time.
Space complexity: O(k) where k is the number of supersets found. This is because we need to create a new list to store the supersets.
Output[(5, 6, 6), (9, 6, 5, 6)]
We use filter function with a lambda function to filter out the tuples in the list which are the supersets of the given tuple.
1. Define the input list and tuple.
2. Use filter function with lambda to filter out the tuples which are supersets of the given tuple.
3. Convert the filtered tuples to list.
4. Return the list.
Output[(5, 6, 6), (9, 6, 5, 6)]
Time complexity: O(n*m), where n is the length of the input list and m is the length of the longest tuple in the list.
Auxiliary Space: O(1) (excluding the space required to store the result list).