Python - Fill Strings for size K in Tuple List
Last Updated :
18 Apr, 2023
Sometimes while working with Tuple lists, we can have a problem in which we need to perform filling of strings to complete certain size in lists. This type of ask can occur in data domains and data preprocessing. Let's discuss certain ways in which this task can be performed.
Input : test_list = [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')], K = 6, fill_char = '#'
Output : [('Gfg###', 'is####'), ('best##', 'for###'), ('CS####', 'Geeks#')]
Input : test_list = [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')], K = 5, fill_char = '!'
Output : [('Gfg!!', 'is!!!'), ('best!', 'for!!'), ('CS!!!', 'Geeks')]
Method #1 : Using list comprehension + len() This functionality is shorthand to brute force method that can be applied to solve this problem. In this, we perform task of checking for K size using len(), and perform required fill by a character.
Python3
# Python3 code to demonstrate working of
# Fill Strings for size K in Tuple List
# Using list comprehension + len()
# initializing list
test_list = [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 8
# initializing fill_char
fill_char = '*'
# Fill Strings for size K in Tuple List
# Using list comprehension + len()
res = [(a + fill_char * (K - len(a)), b + fill_char * (K - len(b))) for a, b in test_list]
# printing result
print("The modified list : " + str(res))
Output : The original list is : [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')]
The modified list : [('Gfg*****', 'is******'), ('best****', 'for*****'), ('CS******', 'Geeks***')]
Time Complexity: O(n*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 list “test_list”.
Method #2 : Using list comprehension + ljust() The combination of above functions can be used to solve this problem. In this, we perform the task of filling trailing characters using ljust().
Python3
# Python3 code to demonstrate working of
# Fill Strings for size K in Tuple List
# Using list comprehension + ljust()
# initializing list
test_list = [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 8
# initializing fill_char
fill_char = '*'
# Fill Strings for size K in Tuple List
# Using list comprehension + ljust()
res = [(a.ljust(K, fill_char), b.ljust(K, fill_char)) for a, b in test_list]
# printing result
print("The modified list : " + str(res))
Output : The original list is : [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')]
The modified list : [('Gfg*****', 'is******'), ('best****', 'for*****'), ('CS******', '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 list “test_list”.
Method #3 : Using Lambda Function and Map
Approach
The approach here is to use the map() function to apply a lambda function to each string in each tuple in the input list. The lambda function concatenates the fill character with the string until the resulting string has a length of K. The resulting map objects are then converted back to tuples and returned as a list of tuples.
Algorithm
1. Define a lambda function fill_func that takes a string and returns the string concatenated with the fill character up to the size of K.
2. Use a list comprehension to iterate through each tuple in the input list test_list.
3. Use the map() function to apply the fill_func lambda function to each string in the current tuple tpl, and convert the resulting map object to a tuple.
4. Append the resulting tuple to a list result.
5. Return the list of tuples with the filled strings.
Python3
def fill_strings_map(test_list, K, fill_char):
# Define a lambda function that takes a string and returns the string concatenated with the fill character up to the size of K
fill_func = lambda string: string + fill_char * (K - len(string))
# Use the map() function to apply the lambda function to each string in each tuple in the list, and convert the resulting map objects to tuples
result = [tuple(map(fill_func, tpl)) for tpl in test_list]
# Return the list of tuples with the filled strings
return result
test_list = [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')]
K=5
fill_char='!'
print(fill_strings_map(test_list, K, fill_char))
Output[('Gfg!!', 'is!!!'), ('best!', 'for!!'), ('CS!!!', 'Geeks')]
Time complexity: O(nmk), where n is the number of tuples in the input list, m is the number of strings in each tuple, and k is the length of the longest string in the input list. However, in practice, the function is likely to have a much lower time complexity, as most input lists will be small and have relatively short strings.
Auxiliary Space: O(nmk), where n, m, and k are as defined above. Additionally, the function creates a new lambda function, which has a space complexity of O(1). However, in practice, the lambda function is likely to have a negligible space complexity compared to the size of the input list.
Method #4 :Using nested loops and string concatenation:
Algorithm:
1.Iterate over each tuple in the given list.
2.For each tuple, get the two strings.
3.Check the length of each string.
4.If the length is less than K, append fill_char to the string until the length becomes equal to K.
5.Append the modified tuple to the result list.
6.Return the result list.
Python3
# Python3 code to demonstrate working of
# Fill Strings for size K in Tuple List
# Using for loop
# initializing list
test_list = [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 8
# initializing fill_char
fill_char = '*'
# Fill Strings for size K in Tuple List
# Using for loop
res = []
for tpl in test_list:
s1 = tpl[0]
s2 = tpl[1]
if len(s1) < K:
s1 += fill_char * (K - len(s1))
if len(s2) < K:
s2 += fill_char * (K - len(s2))
res.append((s1, s2))
# printing result
print("The modified list : " + str(res))
# This code is contributed by Jyothi pinjala.
OutputThe original list is : [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')]
The modified list : [('Gfg*****', 'is******'), ('best****', 'for*****'), ('CS******', 'Geeks***')]
Time Complexity: O(N*K), where N is the number of tuples in the input list and K is the length of the strings to be filled.
Auxiliary Space: O(N*K), the space required to store the modified tuples in the result list.
Method#5: Using Recursive method.
In the recursive case, the method takes the first tuple in the list and extracts the two strings a and b. It then constructs a new tuple with a and b filled up to size K using the fill_char character. This new tuple is then concatenated with the result of recursively calling the method with the rest of the list.
Note that this method is less efficient than the list comprehension method because it uses recursion and creates new tuples for each element. However, it demonstrates an alternative approach to solving the problem using recursion.
Python3
def fill_strings_recursive(test_list, K, fill_char):
if not test_list:
return []
a, b = test_list[0]
return [(a + fill_char * (K - len(a)), b + fill_char * (K - len(b)))] + fill_strings_recursive(test_list[1:], K, fill_char)
# initializing list
test_list = [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 8
# initializing fill_char
fill_char = '*'
res = fill_strings_recursive(test_list,K,fill_char)
# printing result
print("The modified list : " + str(res))
OutputThe original list is : [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')]
The modified list : [('Gfg*****', 'is******'), ('best****', 'for*****'), ('CS******', 'Geeks***')]
Time complexity:
Best case: O(1) when the input list is empty.
Worst case: O(n*K) where n is the length of the input list and K is the size to fill strings up to. This is because the method needs to iterate over each tuple in the list, and for each tuple it needs to construct a new tuple with filled strings up to size K. The operation of filling a string takes O(K) time.
Auxiliary Space:
Best case: O(1) when the input list is empty.
Worst case: O(n*K) where n is the length of the input list and K is the size to fill strings up to. This is because the method needs to create a new tuple for each tuple in the input list with filled strings up to size K. The space needed to store a tuple with filled strings is proportional to K.
Method#6: Using re module
Algorithm:
- Initialize the original list of tuples.
- Set the value of K to the desired length of the strings.
- Set the fill character to the character that will be used to fill the strings.
- Using list comprehension, iterate over the list of tuples.
- For each tuple, apply the zip_longest() function from the itertools module to the two strings, left-justifying them with the fill character to a length of K.
- Concatenate the two formatted strings using the format() method with the appropriate format string.
- Return the modified list of tuples.
Python3
import re
test_list = [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')]
K = 8
fill_char = '*'
filler = fill_char * (K - 1) # create a string of K-1 fill_char characters
res = [tuple(re.sub(fr'\b(\w{{1,{K}}})\b', fr'\1{filler}', s) for s in tpl) for tpl in test_list]
print(res)
Output[('Gfg*******', 'is*******'), ('best*******', 'for*******'), ('CS*******', 'Geeks*******')]
Time Complexity:
The time complexity of this approach is O(n), where n is the number of tuples in the list. The zip_longest() function has a time complexity of O(max(len(a), len(b))), where a and b are the strings being zipped. Since the strings are padded to a fixed length of K, the zip_longest() function will have a time complexity of O(K) for each tuple. Therefore, the overall time complexity of the algorithm is O(n*K).
Auxiliary Space Complexity:
The auxiliary space complexity of this approach is O(n*K), where n is the number of tuples in the list and K is the length of the padded strings. This is because the modified list of tuples is stored in memory, and each string in the tuples has a maximum length of K.
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