Sunday, December 29, 2024
Google search engine
HomeLanguagesPython | Merge Range Characters in List

Python | Merge Range Characters in List

Sometimes, we require to merge some of the elements as single element in the list. This is usually with the cases with character to string conversion. This type of task is usually required in development domain to merge the names into one element. Let’s discuss certain ways in which this can be performed. 

Method #1 : Using join() + List Slicing The join function can be coupled with list slicing which can perform the task of joining each character in a range picked by the list slicing functionality. 

Python3




# Python3 code to demonstrate
# Merge Range Characters in List
# using join() + list slicing
 
# initializing list
test_list = ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
 
# printing original list
print ("The original list is : " + str(test_list))
 
# initializing Range, i, j
i, j = 3, 7
 
# using join() + list slicing
# Merge Range Characters in List
test_list[i : j] = [''.join(test_list[i : j])]
 
# printing result
print ("The list after merging elements : " + str(test_list))


Output : 

The original list is : ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
The list after merging elements : ['I', 'L', 'O', 'VEGF', 'G']

Time Complexity: O(n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

  Method #2 : Using reduce() + lambda + list slicing The task of joining each element in a range is performed by reduce function and lambda. reduce function performs the task for each element in the range which is defined by the lambda function. It works with Python2 only. 

Python3




# Python code to demonstrate
# Merge Range Characters in List
# using reduce() + lambda + list slicing
 
# initializing list
test_list = ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
 
# printing original list
print ("The original list is : " + str(test_list))
 
# initializing strt, end
strt, end = 3, 7
 
# using reduce() + lambda + list slicing
# Merge Range Characters in List
test_list[strt : end] = [reduce(lambda i, j: i + j, test_list[strt : end])]
 
# printing result
print ("The list after merging elements : " + str(test_list))


Output : 

The original list is : ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
The list after merging elements : ['I', 'L', 'O', 'VEGF', 'G']

Time Complexity: O(n*n) where n is the number of elements in the string list. The reduce() + lambda + list slicing is used to perform the task and it takes O(n*n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the test list.

Method#3:Using for loop

Approach

this approach involves using a for loop to iterate over the original list and merge the characters within the specified range.

Algorithm

1. Take input the original list and the range (i, j)
2. Create a new empty list to hold the merged result
3. Iterate over the original list using a for loop and an index variable
4. If the current index is within the range (i, j), then append the current element to a temporary string variable
5. If the current index is not within the range (i, j), then append the temporary string variable to the result list and reset the temporary string variable
6. After the loop is complete, append any remaining characters in the temporary string variable to the result list
7. Return the result list

Python3




def merge_range_characters(arr, i, j):
    result = []
    temp_str = ""
    for idx, char in enumerate(arr):
        if i <= idx < j:
            temp_str += char
        else:
            if temp_str:
                result.append(temp_str)
                temp_str = ""
            result.append(char)
    if temp_str:
        result.append(temp_str)
    return result
arr= ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
i=3
j=7
print(merge_range_characters(arr, i, j))


Output

['I', 'L', 'O', 'VEGF', 'G']

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

Method#4: Using reduce ():

Algorithm:

  1. Create an empty list merged to store the merged characters.
  2. Create an empty string temp_str to store the characters to be merged.
  3. Loop through each character in the input list arr along with its index:

                a. If the index is between i and j (inclusive), append the character to temp_str.

                 b. If temp_str is not empty, append it to merged and append the current character to merged.

                 c. If temp_str is empty, simply append the current character to merged.

        4.If temp_str is not empty after the loop, append it to merged.

        5.Return the merged list.

Python3




from functools import reduce
 
def merge_range_characters(arr, i, j):
    merged = []
    temp_str = ""
    for idx, char in enumerate(arr):
        if i <= idx < j:
            temp_str += char
        elif temp_str:
            merged.append(temp_str)
            merged.append(char)
            temp_str = ""
        else:
            merged.append(char)
    if temp_str:
        merged.append(temp_str)
    return merged
 
arr = ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
i = 3
j = 7
 
merged_list = merge_range_characters(arr, i, j)
print("The original list is : " + str(arr))
print("The list after merging elements : " + str(merged_list))
 
#This code is contributed by Jyothi pinjala


Output

The original list is : ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
The list after merging elements : ['I', 'L', 'O', 'VEGF', 'G']

Time complexity:
The time complexity of the merge_range_characters function is O(n), where n is the length of the input list arr. This is because the function loops through each character in arr once.

Auxiliary Space:

The space complexity of the merge_range_characters function is also O(n). This is because the function creates a new list merged to store the merged characters, which can be up to the same length as arr. Additionally, the function creates a string temp_str to store the characters to be merged, which can be up to the length of the range i to j. However, since the length of the range i to j is constant, it does not affect the overall space complexity.

METHOD 5:Using a loop

APPROACH:

Using a loop to iterate over the characters in the list, and merging adjacent characters if they form a contiguous range.

ALGORITHM:

1.Initialize index i as 0
2.Iterate over the list from 0 to n-2
a. If the current element’s ASCII value is one less than the next element’s ASCII value,
then iterate over the consecutive elements until a non-consecutive element is encountered
b. Join the consecutive elements using ”.join() method and replace the original consecutive elements with the joined element
3.Increment i by 1
4.Repeat steps 2-3 until i reaches the end of the list
5.Return the modified list

Python3




lst = ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
i = 0
while i < len(lst) - 1:
    if ord(lst[i]) + 1 == ord(lst[i+1]):
        j = i + 1
        while j < len(lst) - 1 and ord(lst[j]) + 1 == ord(lst[j+1]):
            j += 1
        lst[i:j+1] = [''.join(lst[i:j+1])]
    else:
        i += 1
print(lst)


Output

['I', 'L', 'O', 'V', 'E', 'G', 'FG']

Time complexity: O(n^2)
Auxiliary Space: O(1)

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments