Open In App

Python – Concatenate Maximum Tuples

Improve
Improve
Like Article
Like
Save
Share
Report

Given a tuple list with string and its magnitude, the task is to write a python program to join all the strings with maximum magnitudes.

Examples:

Input : test_list = [(“Gfg is best”, 8), (“gfg is good”, 7), (“for”, 2), (“for all geeks”, 8)]
Output : “Gfg is best for all geeks”

Explanation : 8 is maximum tuple element and concatenation of keys yield the result.

Input : test_list = [(“Gfg is best”, 7), (“gfg is good”, 8), (“for”, 2), (“for all geeks”, 8)]
Output : “gfg is good for all geeks”
Explanation : 8 is maximum tuple element and concatenation of keys yield the result.

Method #1 : Using max() + itemgetter() + list comprehension + join()

In this, we perform task of getting maximum magnitude numbers using max(), itemgetter handles the index to query. The strings are joined by join() after matching using list comprehension.

  1. Import the itemgetter function from the operator module.
  2. Initialize the list of tuples.
  3. Print the original list.
  4. Use the max() function along with itemgetter() to get the tuple with the maximum value at index 1.
  5. Use a list comprehension to extract the keys (strings) from the tuples where the value at index 1 is equal to max_ele.
  6. Join the extracted strings using the join() method.
  7. Print the concatenated string with maximum length.

Python3




# Python3 code to demonstrate working of
# Concatenate Maximum Tuples
# Using max() + itemgetter() + list comprehension + join()
from operator import itemgetter
 
# initializing list
test_list = [("Gfg is best", 8), ("gfg is good", 7),
             ("for", 2), ("for all geeks", 8)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# getting maximum
max_ele = max(test_list, key=itemgetter(1))[1]
 
# joining maximum
res = ' '.join([key for key, ele in test_list if ele == max_ele])
 
# printing result
print("The maximum concatenated strings : " + str(res))


Output

The original list is : [('Gfg is best', 8), ('gfg is good', 7), ('for', 2), ('for all geeks', 8)]
The maximum concatenated strings : Gfg is best for all geeks

Time complexity: O(n), where n is the number of elements in the list ‘test_list’. 
Auxiliary space: O(n), where n is the number of elements in the filtered list after filtering the maximum elements from ‘test_list’. 

Method #2 : Using filter() + max() + itemgetter()

In this, we perform task of filtering using filter() rather than list comprehension. Rest all the functionalities is similar to all the method.

Follow the below steps to implement the above idea:

  • Import the itemgetter module from the operator library
  • Create a list of tuples called test_list, where each tuple contains a string and an integer
  • Print the original list using the print() function
  • Use the max() function and itemgetter() method to get the maximum value from the list of tuples. itemgetter(1) refers to the second element in the tuple (the integer)
  • Store the maximum value in the variable max_ele
  • Use a lambda function and the filter() method to iterate over the test_list and return only the tuples whose second element matches the maximum value, max_ele.
  • Use list comprehension to join the strings from the tuples that were returned by the filter() function into a single string separated by spaces. Store this string in the variable res.
  • Print the concatenated string using the print() function.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Concatenate Maximum Tuples
# Using filter() + max() + itemgetter()
from operator import itemgetter
 
# initializing list
test_list = [("Gfg is best", 8), ("gfg is good", 7),
             ("for", 2), ("for all geeks", 8)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# getting maximum
max_ele = max(test_list, key=itemgetter(1))[1]
 
# joining maximum
# filter checks for maximum values and concats
res = " ".join([ele[0]
                for ele in filter(lambda ele: ele[1] == max_ele, test_list)])
 
# printing result
print("The maximum concatenated strings : " + str(res))


Output

The original list is : [('Gfg is best', 8), ('gfg is good', 7), ('for', 2), ('for all geeks', 8)]
The maximum concatenated strings : Gfg is best for all geeks

Time complexity: O(nlogn), where n is the length of the input list. 
Auxiliary space: O(n), where n is the length of the input list. 

Method #3 : Using max() and for loop

Python3




# Python3 code to demonstrate working of
# Concatenate Maximum Tuples
 
# initializing list
test_list = [("Gfg is best", 8), ("gfg is good", 7),
            ("for", 2), ("for all geeks", 8)]
 
# printing original list
print("The original list is : " + str(test_list))
x=[]
for i in test_list:
    x.append(i[1])
ma=max(x)
res=[]
for i in test_list:
    if ma in i:
        res.append(i[0])
res=" ".join(res)
 
# printing result
print("The maximum concatenated strings : " + str(res))


Output

The original list is : [('Gfg is best', 8), ('gfg is good', 7), ('for', 2), ('for all geeks', 8)]
The maximum concatenated strings : Gfg is best for all geeks

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), as we are creating a new list to store the second element of each tuple.

Method #4: Using a generator expression and the built-in function ‘max()’

 Using a generator expression to create a tuple of the concatenated string and its length, and then passing the resulting tuple to the ‘max()’ function to get the tuple with the maximum length. Finally, we can return the concatenated string from the tuple.

Python3




test_list = [("Gfg is best", 8), ("gfg is good", 7),
            ("for", 2), ("for all geeks", 8)]
 
# Generator expression to create a tuple of concatenated string and length
concatenated = ((s, l) for s, l in test_list if l == max([l for _, l in test_list]))
 
# Get the tuple with the maximum length
max_tuple = max(concatenated, key=lambda x: len(x[0]))
 
# Return the concatenated string
result = max_tuple[0]
 
# Printing result
print("The maximum concatenated strings : " + str(result))


Output

The maximum concatenated strings : for all geeks

The time complexity of this method is O(n) for iterating over the list and creating the generator expression, and then O(n) for the max() function to find the maximum tuple, so the overall time complexity is O(n).

The auxiliary space is O(1) for the generator expression and O(1) for the ‘max_tuple’ variable, so the overall space complexity is O(1).

Method #5: Using a loop and a conditional statement to find the maximum and concatenate the strings

This method iterates through the list and keeps track of the maximum element seen so far. If a new maximum is found, it replaces the current maximum and sets the result string to the current key. If the current element is equal to the maximum, it appends the current key to the result string with a space separator.

Python3




test_list = [("Gfg is best", 8), ("gfg is good", 7),
             ("for", 2), ("for all geeks", 8)]
 
max_ele = 0
res = ""
 
for key, ele in test_list:
    if ele > max_ele:
        max_ele = ele
        res = key
    elif ele == max_ele:
        res += " " + key
 
print("The maximum concatenated strings : " + str(res))


Output

The maximum concatenated strings : Gfg is best for all geeks

Time complexity of this code is O(n), where n is the length of the input list. This is because we are iterating through the list once.

Auxiliary space complexity of this code is O(1), as we are only storing a few variables to keep track of the maximum element seen so far and the concatenated string.

Method #6: Using reduce():

Algorithm:

  1. Initialize the list of tuples.
  2. Find the maximum value of the tuples by using max() function and passing a lambda function which takes an element and returns the second value of tuple.
  3. Filter the tuples from the list which have the second value equal to the maximum value found in step 2, using filter() function.
  4. Join the first values of filtered tuples using ” “.join() function and return the result.

Python3




from operator import itemgetter
from functools import reduce
 
# initializing list
test_list = [("Gfg is best", 8), ("gfg is good", 7),
            ("for", 2), ("for all geeks", 8)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# getting maximum
max_ele = max(test_list, key=itemgetter(1))[1]
 
# joining maximum
# filter checks for maximum values and concats
res = reduce(lambda x, y: x + " " + y[0] if y[1] == max_ele else x, test_list, "")
 
# printing result
print("The maximum concatenated strings : " + str(res))
 
#This code is contrinuted by Pushpa.


Output

The original list is : [('Gfg is best', 8), ('gfg is good', 7), ('for', 2), ('for all geeks', 8)]
The maximum concatenated strings :  Gfg is best for all geeks

Time Complexity: O(n), where n is the length of the input list.

Finding the maximum value using max() function takes O(n) time in the worst case.
Filtering the tuples using filter() function also takes O(n) time in the worst case.
Joining the strings using ” “.join() function takes O(n) time in the worst case.
Auxiliary Space: O(n), where n is the length of the input list.

We are not using any extra data structure in the algorithm except for the result string which can be of maximum size n.



Last Updated : 15 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads