![]() |
VOOZH | about |
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform concatenation of single values tuples, to make them into groups of a bigger size. This kind of problem can occur in web development and day-day programming. Let's discuss certain ways in which this task can be performed.
Input : test_list = [(3, ), (6, ), (8, ), (2, ), (9, ), (4, ), (7, ), (1, )], K = 4 Output : [(3, 6, 8, 2), (9, 4, 7, 1)]
Input : test_list = [(3, ), (6, ), (8, ), (2, ), (9, ), (4, ), (7, ), (1, )], K = 2 Output : [(3, 6), (8, 2), (9, 4), (7, 1)]
The combination of the above functions can be used to solve this problem. In this, we perform the task of forming groups using zip() and constructing values using list comprehension. The size of K can only be limited to 2.
The original list is : [(3, ), (6, ), (8, ), (2, ), (9, ), (4, )] Concatenated tuples : [(3, 6), (8, 2), (9, 4)]
Time complexity: O(N), where N is the length of the input list.
Auxiliary space: O(N), where N is the length of the input list. This is because the program creates a new list res to store the concatenated tuples, which could potentially be as large as the input list.
The combination of the above functions can be used to solve this problem. In this, we perform the task of concatenation using zip_longest(), and chain.from_iterables() is used to flatten tuples to list elements before concatenation.
The original list is : [(3, ), (6, ), (8, ), (2, ), (9, ), (4, )] Concatenated tuples : [(3, 6, 8), (2, 9, 4)]
Time complexity: O(nK), where n is the length of the input list and K is the value of K.
Auxiliary space: O(nK)
Algorithm:
The original list is : [(3,), (6,), (8,), (2,), (9,), (4,)] Concatenated tuples : [(3, 6), (8, 2), (9, 4)]
Time Complexity: O(n/2) = O(n), where n is the length of the test_list.
The for loop iterates n/2 times, as it iterates over the test_list by 2 steps at a time. The concatenation of two tuples takes constant time.
Auxiliary Space: O(n/2) = O(n), where n is the length of the test_list.
The space required to store the res list is proportional to the length of the test_list.
Note: This time complexity and space complexity assumes that the length of the test_list is even. If the length of the test_list is odd, the last tuple in the test_list will be ignored as there won't be any tuple to concatenate it with.
Method #4: Using a generator function and itertools.islice()
The original list is : [(3,), (6,), (8,), (2,), (9,), (4,)] Concatenated tuples : [(3, 6), (8, 2), (9, 4)]
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(k), where k is the size of the consecutive tuples to be formed.