Python – Check if Tuple contains only K elements
Sometimes, while working with Python tuples, we can have a problem in which we need to test if any tuple contains elements from set K elements. This kind of problem is quite common and have application in many domains such as web development and day-day programming. Let’s discuss certain ways in which this task can be done.
Input : test_tuple = (1, 2, 3, 2, 1, 2), K = [1, 2, 3, 4] Output : True Input : test_tuple = (1, 2, 3), K = [1, 2] Output : False
Method #1 : Using all() This is one of the ways in which this task can be performed. In this, we check for the presence of all the elements in tuple are just from certain set of numbers using inbuilt function all().
Python3
test_tuple = ( 3 , 5 , 6 , 5 , 3 , 6 )
print ("The original tuple : " + str (test_tuple))
K = [ 3 , 6 , 5 ]
res = all (ele in K for ele in test_tuple)
print ("Does tuples contains just from K elements : " + str (res))
|
Output :
The original tuple : (3, 5, 6, 5, 3, 6)
Does tuples contains just from K elements : True
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2 : Using set() This is yet another way to solve this problem. In this, we convert the tuples, to set and then test the less and equal to relation with the query K elements.
Python3
test_tuple = ( 3 , 5 , 6 , 5 , 3 , 6 )
print ("The original tuple : " + str (test_tuple))
K = [ 3 , 6 , 5 ]
res = set (test_tuple) < = set (K)
print ("Does tuples contains just from K elements : " + str (res))
|
Output :
The original tuple : (3, 5, 6, 5, 3, 6)
Does tuples contains just from K elements : True
Time Complexity: O(n), where n is length of test_tuple.
Auxiliary Space: O(1)
Method #3 : Using recursive method.
Python3
def isonlycontains_K(start,lst,k):
if start = = len (lst):
return True
if lst[start] not in k:
return False
return isonlycontains_K(start + 1 ,lst,k)
test_tuple = ( 3 , 5 , 6 , 5 , 3 , 6 )
print ( 'The original tuple : ' + str (test_tuple))
K = [ 3 , 6 , 5 ]
res = isonlycontains_K( 0 ,test_tuple,K)
print ( 'Does tuples contains just from K elements :' + str (res))
|
Output
The original tuple : (3, 5, 6, 5, 3, 6)
Does tuples contains just from K elements :True
Time Complexity: O(n)
Space Complexity:O(n)
Last Updated :
12 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...