Saturday, December 28, 2024
Google search engine
HomeLanguagesPython | K length Padding in List

Python | K length Padding in List

In real world problems, we sometimes require to pad the element of list according to a condition that maximum characters have reached. Padding a number with 0 if it’s length is less than required by any field is one of the basic issues that occur in web forms in Web Development. Let’s discuss certain ways in which this issue can be solved. 

Method #1: Using list comprehension This problem can be solved easily using the basic list comprehension in which we just need to use string formatting to perform the optional padding with 0 if size of each element is less than the specified size. 

Python3




# Python3 code to demonstrate
# K length Padding in List
# using list comprehension
 
# initializing list
test_list = [3, 54, 4, 100, 10]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# initializing K
K = 4
 
# using list comprehension
# K length Padding in List
temp = "% 0" + str(K) + "d"
res = [temp % i for i in test_list]
 
# printing result
print ("The list after K size element padding : " + str(res))


Output : 

The original list is : [3, 54, 4, 100, 10]
The list after K size element padding ['0003', '0054', '0004', '0100', '0010']

Time Complexity: O(n) where n is the number of elements in the in the list “test_list”. The list comprehension is used to perform the task and it takes O(n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the in the list “test_list”.

Method #2: Using str.rjust() There is a function dedicated in python to do this job. The rjust function does the task of specifying the size of the string and also takes the character in which the character has to be padded. 

Python3




# Python3 code to demonstrate
# K length Padding in List
# using str.rjust()
 
# initializing list
test_list = [3, 54, 4, 100, 10]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# initializing K
K = 4
 
# using str.rjust()
# to perform list element padding
res = [str(i).rjust(K, '0') for i in test_list]
 
# printing result
print ("The list after K size element padding : " + str(res))


Output : 

The original list is : [3, 54, 4, 100, 10]
The list after K size element padding ['0003', '0054', '0004', '0100', '0010']

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 stringformatting

In this method, we use the f-string syntax to format each element of the original list with leading zeros using the :0{k} specifier. The 0 indicates that we want to pad with zeros, and k is the width of the padded string. Finally, we use a list comprehension to apply this formatting to each element of the original list and create the padded list.

Python3




# Define the original list
original_list = [3, 54, 4, 100, 10]
 
# Define the desired length of the padded elements
k = 4
 
# Pad each element with zeros using string formatting
padded_list = [f"{x:0{k}}" for x in original_list]
 
# Print the padded list
print(padded_list)


Output

['0003', '0054', '0004', '0100', '0010']

Time complexity: O(n)
Auxiliary Space: O(n)

Method #4: Using numpy library:

Algorithm:

1.Import the numpy library.
2.Define the original list and K value.
3.Convert the original list to a numpy array of strings using the astype() method.
4.Use the np.char.zfill() function to pad each string in the array with zeros to a length of K.
5.Convert the padded numpy array back to a list using the tolist() method.
6.Print the original list and the padded list for comparison.

Python3




# Import numpy library
import numpy as np
 
# Define the original list and K value
test_list = [3, 54, 4, 100, 10]
K = 4
 
# Convert the original list to a numpy array of strings
string_array = np.array(test_list).astype(str)
 
# Pad the strings in the array with zeros to a length of K
padded_array = np.char.zfill(string_array, K)
 
# Convert the padded numpy array back to a list
padded_list = padded_array.tolist()
 
# Print the original list and the padded list
print("Original List:", test_list)
print("Padded List:", padded_list)
#This code is contributed by Jyothi pinjala


Output:

Original List: [3, 54, 4, 100, 10]
Padded List: ['0003', '0054', '0004', '0100', '0010']

Time complexity:

The conversion of the original list to a numpy array takes O(n) time, where n is the length of the list.
The astype() method also takes O(n) time, since it needs to convert each element of the array to a string.
The np.char.zfill() function takes O(nk) time, where k is the length of the padded strings. Since we are padding each string to a length of K, this operation takes O(nK) time in total.
The tolist() method takes O(n) time, since it needs to convert the numpy array back to a list.
Therefore, the overall time complexity of the code is O(nK).
Auxiliary Space:

The numpy array created in step 3 requires O(nk) space, where k is the length of the padded strings. Since we are padding each string to a length of K, this array takes O(nK) space in total.
The padded list created in step 4 also requires O(nk) space, where k is the length of the padded strings. Therefore, the space complexity of the code is O(nK).

Method #5: Using a for loop and string concatenation: A simple way to pad the numbers with leading zeros is to loop over the list, convert each number to a string, and concatenate “0” characters to the left until the resulting string has the desired length.

Step-by-step approach:

  • Initialize an empty list to store the padded numbers.
  • Loop over the original list.
  • Convert each number to a string.
  • Check the length of the resulting string.
  • If the length is less than k, concatenate “0” characters to the left until the string has length k.
  • Append the padded string to the new list.

Python3




lst = [3, 54, 4, 100, 10]
k = 4
 
padded_lst = []
for num in lst:
    num_str = str(num)
    while len(num_str) < k:
        num_str = "0" + num_str
    padded_lst.append(num_str)
 
print("The list after k size element padding:", padded_lst)


Output

The list after k size element padding: ['0003', '0054', '0004', '0100', '0010']

Time complexity: O(nk), where n is the length of the list and k is the desired length of each element.
Auxiliary Space: O(nk), where n is the length of the list and k is the desired length of each element.

Method #6: Using re module

This program takes an input list of integers and pads each integer with leading zeros to a fixed length of 4 digits. The padded integers are then stored in a new list.

Step-by-step approach:

  • Define the input list.
  • Use a list comprehension to iterate through the input list, convert each integer to a string and pad it with leading zeros using the string format method with format specification of “04”.
  • Join the padded integers as a single string.
  • Use a regular expression to extract groups of four digits from the padded string using the findall() method.
  • Store the extracted groups of four digits in a new list.
  • Print the resulting padded list.

Python3




import re
 
# input list
lst = [3, 54, 4, 100, 10]
 
# convert each number to a string, add leading zeros, and join them as a single string
padded_str = ''.join([f"{num:04d}" for num in lst])
 
# extract groups of four digits from the padded string using regular expressions
padded_lst = re.findall(r'\d{4}', padded_str)
 
# print the result
print("The list after K size element padding:", padded_lst)


Output

The list after K size element padding: ['0003', '0054', '0004', '0100', '0010']

Time Complexity: O(n), The time complexity of the program is linear with respect to the number of integers in the input list, n. This is because the program performs a constant number of operations for each integer in the list.
Auxiliary Space: O(n), The space complexity of the program is also linear with respect to the number of integers in the input list, n. This is because the program creates a new list of padded integers of length n, and a string of length 4n to store the joined padded integers.

Method 7: Using the zfill() method 

Step-by-step approach:

  • Initialize the input list, test_list, and K (the number of digits to be padded) as follows:
  • Create an empty list res to store the output.
  • Loop through each element i of test_list using a for loop and apply the zfill() method to convert it into a string of K digits with leading zeroes.
  • Append the resulting string to the res list using the append() method.
  • Print the original list and the padded list using the str.join() method to convert the list elements into strings and concatenate them.

Python3




# Python3 code to demonstrate
# K length Padding in List
# using zfill() method
 
# initializing list
test_list = [3, 54, 4, 100, 10]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 4
 
# K length Padding in List using zfill() method
res = []
for i in test_list:
    res.append(str(i).zfill(K))
 
# printing result
print("The list after K size element padding : " + ' '.join(res))


Output

The original list is : [3, 54, 4, 100, 10]
The list after K size element padding : 0003 0054 0004 0100 0010

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 (used to store the output list).

RELATED ARTICLES

Most Popular

Recent Comments