Skip to content
Related Articles
Open in App
Not now

Related Articles

Python – Extract range of Consecutive Similar elements ranges from string list

Improve Article
Save Article
Like Article
  • Last Updated : 26 Mar, 2023
Improve Article
Save Article
Like Article

Given a list, extract range of consecutive similar elements.

Input : test_list = [2, 3, 3, 3, 8, 8] 
Output : [(2, 0, 0), (3, 1, 3), (8, 4, 5)] 
Explanation : 2 occurs from 0th to 0th index, 3 from 1st to 3rd index.

Input : test_list = [3, 3, 3] 
Output : [(3, 0, 3)] 
Explanation : 3 from 0th to 3rd index. 

Approach: Using loop

This is a brute way to tackle this problem. In this, we loop for each element and get a similar element range. These are traced and appended in list accordingly with elements.

  1. Initialize a list test_list with integer values.
  2. Print the original list.
  3. Initialize an empty list res to store the results.
  4. Initialize a variable idx to 0.
  5. While the value of idx is less than the length of the test_list:
    a. Set the variable strt_pos equal to the current value of idx.
    b. Set the variable val equal to the value at index idx in test_list.
    c. While the value of idx is less than the length of test_list and the value at index idx is equal to val, increment idx by 1.
    d. Set the variable end_pos equal to idx – 1.
    e. Append the tuple (val, strt_pos, end_pos) to the list res.
  6. Print the elements with their range in the format [ele, strt_pos, end_pos] using the res list.

Python3




# Python3 code to demonstrate working of
# Consecutive Similar elements ranges
# Using loop
 
# initializing list
test_list = [2, 3, 3, 3, 8, 8, 6, 7, 7]
 
# printing original list
print("The original list is : " + str(test_list))
 
res = []
idx = 0
while idx < (len(test_list)):
    strt_pos = idx
    val = test_list[idx]
     
    # getting last pos.
    while (idx < len(test_list) and test_list[idx] == val):
        idx += 1
    end_pos = idx - 1
     
    # appending in format [ele, strt_pos, end_pos]
    res.append((val, strt_pos, end_pos))
 
# printing result
print("Elements with range : " + str(res))

Output:

The original list is : [2, 3, 3, 3, 8, 8, 6, 7, 7] Elements with range : [(2, 0, 0), (3, 1, 3), (8, 4, 5), (6, 6, 6), (7, 7, 8)]

Time Complexity: O(n2)

Space Complexity: O(n)

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!