Saturday, December 28, 2024
Google search engine
HomeLanguagesPython Program that prints elements common at specified index of list elements

Python Program that prints elements common at specified index of list elements

Given a list of strings, the task is to write a Python program to extract all characters that are same at a specified index of each element of a list.

Illustration:

Input : test_list = ["neveropen", "weak", "beak", "peek"] 
Output : ['e', 'k'] 
Explanation : e and k are at same at an index on all strings.
Input : test_list = ["neveropen", "weak", "beak", "peer"] 
Output : ['e'] 
Explanation : e is at same at an index on all strings. 

Method 1 : Using min(), len() and loop

In this, initially, a minimum length string is extracted to check indices to iterate to ensure all indices in strings. Then each index is checked for similar character using loop, if found, character is appended to result.

Python3




# initializing Matrix
test_list = ["neveropen", "weak", "beak", "peek"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# getting min length string
min_len = min(len(ele) for ele in test_list)
 
res = []
for idx in range(0, min_len):
    flag = True
    for ele in test_list:
 
        # checking for all equal columns
        if ele[idx] != test_list[0][idx]:
            flag = False
            break
 
    if flag:
        res.append(test_list[0][idx])
 
 
# printing result
print("Extracted similar characters : " + str(res))


Output

The original list is : ['neveropen', 'weak', 'beak', 'peek']
Extracted similar characters : ['e', 'k']

Time Complexity: O(n*n)
Auxiliary Space: O(n)

Method 2 : Using all(), min(), len() and loop

In this, we perform the task of checking all elements to match using all(), reducing a nested loop, increasing readability.

Python3




# initializing Matrix
test_list = ["neveropen", "weak", "beak", "peek"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# getting min length string
min_len = min(len(ele) for ele in test_list)
 
res = []
for idx in range(0, min_len):
 
    # using all() for condition injection
    if all(ele[idx] == test_list[0][idx] for ele in test_list):
        res.append(test_list[0][idx])
 
# printing result
print("Extracted similar characters : " + str(res))


Output

The original list is : ['neveropen', 'weak', 'beak', 'peek']
Extracted similar characters : ['e', 'k']

Time Complexity: O(n2)
Auxiliary Space: O(n)

Method 3: Using set comprehension + zip() function

Python3




test_list = ["neveropen", "weak", "beak", "peek"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Transpose the list of strings into a list of lists of characters
char_lists = [list(string) for string in test_list]
 
# Use zip to iterate over the columns of characters
columns = zip(*char_lists)
 
# Use a set comprehension to select only columns where all characters are equal
res = [char[0] for char in columns if len(set(char)) == 1]
 
# printing result
print("Extracted similar characters : " + str(res))
#This code is contributed by Vinay Pinjala.


Output

The original list is : ['neveropen', 'weak', 'beak', 'peek']
Extracted similar characters : ['e', 'k']

Time Complexity: O(n2)
Auxiliary Space: O(n)

Method 4: Using set intersection and loop

Approach:

  1. Initialize a set with the characters of the first string in the list.
  2. Now use the intersection_update method to only keep the common characters between the current set and each string in the list, one by one.
  3. Finally, we convert the set back to a list and print the result.

Example:

Python




# Initializing list
test_list = ["neveropen", "weak", "beak", "peek"]
 
# Printing original list
print("The original list is : " + str(test_list))
 
res = set(test_list[0])
 
for ele in test_list[1:]:
    res.intersection_update(ele)
 
res = list(res)
 
# Printing result
print("Extracted similar characters : " + str(res))


Output

The original list is : ['neveropen', 'weak', 'beak', 'peek']
Extracted similar characters : ['k', 'e']

Time Complexity: O(n)
Auxiliary Space: O(m), where m is the length of the longest string in the list.

Method 5: Using Counter from collections module

  1. The program first imports the Counter class from the collections module. The Counter class is a dictionary subclass which helps count the occurrences of items in a list.
  2. The program then creates a list called test_list that contains four strings: “neveropen”, “weak”, “beak”, and “peek”.
  3. The program prints the original list using the print() function and the str() function to convert the list to a string: “The original list is : ” + str(test_list).
  4. The program then initializes a Counter object called common_chars with the characters from the first string in test_list using the Counter() constructor.
  5. The program then loops through the remaining strings in test_list using a for loop with string as the loop variable.
  6. Inside the for loop, the program updates the common_chars object to contain only the characters that are common between the current string and common_chars using the &= operator.
  7. After the for loop, the program creates a list called res by calling the elements() method on common_chars and then converting the result to a list using the list() constructor.
  8. Finally, the program prints the list of common characters using the print() function and the str() function: “Extracted similar characters : ” + str(res)”.

Python3




from collections import Counter
 
test_list = ["neveropen", "weak", "beak", "peek"]
print("The original list is : " + str(test_list))
 
common_chars = Counter(test_list[0])
for string in test_list[1:]:
    common_chars &= Counter(string)
 
res = list(common_chars.elements())
print("Extracted similar characters : " + str(res))


Output

The original list is : ['neveropen', 'weak', 'beak', 'peek']
Extracted similar characters : ['e', 'k']

Time complexity: O(n*m), where n is the length of the list and m is the length of the longest string in the list.
Auxiliary space: O(K), where k is the number of unique characters in the list of strings.

Method 6: Using reduce() from functools module

Python3




from functools import reduce
 
# Initializing list
test_list = ["neveropen", "weak", "beak", "peek"]
 
# Pnting original list
print("The original list is: " + str(test_list))
 
res = list(reduce(lambda x, y: set(x) & set(y), test_list))
 
# Printing result
print("Extracted similar characters: " + str(res))


Output

The original list is: ['neveropen', 'weak', 'beak', 'peek']
Extracted similar characters: ['e', 'k']

Time complexity: O(n * m) 
Auxiliary space: O(k)

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