Tuesday, November 19, 2024
Google search engine
HomeLanguagesPython – Assign Alphabet to each element

Python – Assign Alphabet to each element

Given a list of elements, assign a similar alphabet to the same element.

Input : test_list = [4, 5, 2, 4, 2, 6] 
Output : ['a', 'b', 'c', 'a', 'c', 'd'] 
Explanation : Alphabets assigned to elements as occurring.  
Input : test_list = [4, 5, 2, 4, 2, 6] 
Output : ['a', 'b', 'c', 'a', 'c'] 
Explanation : Alphabets assigned to elements as occurring.

Method #1: Using ascii_lowercase() + loop + list comprehension 

In this, we extract all lowercase alphabets using lowercase(), and create dictionary mapping same element to similar character, post that we flatten that to appropriate index using list comprehension.

Python3




# Python3 code to demonstrate working of
# Assign Alphabet to each element
# Using ascii_lowercase() + loop + list comprehension
 
import string
 
# initializing list
test_list = [4, 5, 2, 4, 2, 6, 5, 2, 5]
 
# printing list
print("The original list : " + str(test_list))
 
temp = {}
cntr = 0
for ele in test_list:
    if ele in temp:
        continue
 
    # assigning same Alphabet to same element
    temp[ele] = string.ascii_lowercase[cntr]
    cntr += 1
 
# flattening
res = [temp.get(ele) for ele in test_list]
 
# printing results
print("The mapped List : " + str(res))


Output

The original list : [4, 5, 2, 4, 2, 6, 5, 2, 5]
The mapped List : ['a', 'b', 'c', 'a', 'c', 'd', 'b', 'c', 'b']

Time complexity: O(n*n), where n is the length of the test_list. The  ascii_lowercase() + loop + list comprehension takes O(n*n) time
Auxiliary Space: O(n), extra space of size n is required

Method #2 : Using defaultdict() + ascii_lowercase() + iter()

In this we use defaultdict() to assign values to similar elements, ascii_lowercase() is used to get all lowercase all lowercased alphabets.

Python3




# Python3 code to demonstrate working of
# Assign Alphabet to each element
# Using defaultdict() + ascii_lowercase() + iter()
 
from collections import defaultdict
import string
 
# initializing list
test_list = [4, 5, 2, 4, 2, 6, 5, 2, 5]
 
# printing list
print("The original list : " + str(test_list))
 
# assigning lowercases as iterator
temp = iter(string.ascii_lowercase)
 
# lambda functions fits to similar elements
res = defaultdict(lambda: next(temp))
 
# flatten in list
res = [res[key] for key in test_list]
 
# printing results
print("The mapped List : " + str(list(res)))


Output

The original list : [4, 5, 2, 4, 2, 6, 5, 2, 5]
The mapped List : ['a', 'b', 'c', 'a', 'c', 'd', 'b', 'c', 'b']

The Time and Space Complexity for all the methods are the same:

Time Complexity: O(N)

Auxiliary Space: O(N)

Method #3: Without using isalpha()

Python3




# Python3 code to demonstrate working of
# Assign Alphabet to each element
 
# initializing list
test_list = [4, 5, 2, 4, 2, 6, 5, 2, 5]
 
# printing list
print("The original list : " + str(test_list))
x=[]
for i in test_list:
    if i not in x:
        x.append(i)
alphabets="abcdefghijklmopqrstuvwxyz"
al=alphabets[:len(x)]
d=dict()
for i in range(0,len(x)):
    d[x[i]]=al[i]
res=[]
for i in test_list:
    res.append(d[i])
# printing results
print("The mapped List : " + str(res))


Output

The original list : [4, 5, 2, 4, 2, 6, 5, 2, 5]
The mapped List : ['a', 'b', 'c', 'a', 'c', 'd', 'b', 'c', 'b']

Method #4:  using defaultdict and the enumerate function 

Step-by-step algorithm:

  1. Initialize an empty ordered dictionary called temp.
  2. Initialize a counter variable cntr to 0.
  3. Iterate over each element ele in the test_list:
    a. Check if the element ele is already in the dictionary temp.
    b. If it is not, then add it to the dictionary as a key with its corresponding value set as the cntrth lowercase letter of the English alphabet 
  4. using string.ascii_lowercase[cntr]. Increment cntr by 1.
  5. Create a new list res by mapping each element ele in the test_list to its corresponding value in the temp dictionary.
    Print the original list and the mapped list.

Python3




import string
from collections import OrderedDict
 
# initializing list
test_list = [4, 5, 2, 4, 2, 6, 5, 2, 5]
 
# printing list
print("The original list : " + str(test_list))
 
temp = OrderedDict()
cntr = 0
for ele in test_list:
    if ele not in temp:
        temp[ele] = string.ascii_lowercase[cntr]
        cntr += 1
 
# flattening
res = [temp[ele] for ele in test_list]
 
# printing results
print("The mapped List : " + str(res))


Output

The original list : [4, 5, 2, 4, 2, 6, 5, 2, 5]
The mapped List : ['a', 'b', 'c', 'a', 'c', 'd', 'b', 'c', 'b']

Time complexity:
The time complexity of the algorithm is O(n), where n is the length of the input list test_list. This is because the algorithm iterates over each element in test_list exactly once to create the temp dictionary, and then iterates over each element again to create the mapped list res.

Auxiliary space:
The auxiliary space complexity of the algorithm is O(k), where k is the number of unique elements in test_list. This is because the temp dictionary has a key-value pair for each unique element in test_list, and the size of the dictionary is proportional to the number of unique elements. The additional memory used for the res list is also proportional to the length of the input list, which is already accounted for in the time complexity analysis.

Method #5:  Using numpy:

Algorithm:

  1. Create a defaultdict object to map each unique number in the input list to an alphabet.
  2. Create an iterator from the string.ascii_lowercase to iterate over the lower case alphabets.
  3. Use the defaultdict object to map the numbers in the input list to their respective alphabets.
  4. Convert the input list to a numpy array.
  5. Use np.vectorize() to apply the mapping function to each element of the array.
  6. Convert the resulting numpy array to a list.

Python3




import numpy as np
from collections import defaultdict
import string
test_list = [4, 5, 2, 4, 2, 6, 5, 2, 5]
temp = iter(string.ascii_lowercase)
res = defaultdict(lambda: next(temp))
arr = np.array(test_list)
output = np.vectorize(res.__getitem__)(arr)
print("The original list : " + str(test_list))
print("The mapped List : " + str(output.tolist()))
 
#This code is contributed by Jyothi Pinjala.


Output:

The original list : [4, 5, 2, 4, 2, 6, 5, 2, 5]
The mapped List : [‘a’, ‘b’, ‘c’, ‘a’, ‘c’, ‘d’, ‘b’, ‘c’, ‘b’]

Time Complexity:
The time complexity of this code is O(n), where n is the length of the input list. Creating a defaultdict object takes O(1) time. Iterating over the input list and mapping the elements to their corresponding alphabets takes O(n) time. Converting the input list to a numpy array takes O(n) time. Using np.vectorize() takes O(n) time. Converting the resulting numpy array to a list takes O(n) time.

Auxiliary Space:
The space complexity of this code is O(n), where n is the length of the input list. Creating a defaultdict object takes O(k) space, where k is the number of unique elements in the input list. Creating an iterator from string.ascii_lowercase takes O(1) space. The numpy array created from the input list takes O(n) space. The resulting numpy array and the final list both take O(n) space. Overall, the space used by this code is dominated by the numpy array created from the input list.

Method #6: Using dictionary comprehension

This method will use dictionary comprehension to create a dictionary with each unique element of the list as key and an assigned alphabet as value. Then, a list comprehension will be used to map each element of the original list to the assigned alphabet.

Step-by-step approach:

Initialize an empty dictionary temp.
Loop through the elements of the test_list.
Check if the element is already in the dictionary using if ele not in temp.
If the element is not in the dictionary, assign an alphabet to it using the length of the dictionary as the index for the string.ascii_lowercase string.
Use dictionary comprehension to create a new dictionary temp with each unique element of the test_list as key and an assigned alphabet as value.
Use list comprehension to map each element of the test_list to the assigned alphabet.
Print the mapped list.

Python3




import string
 
# initializing list
test_list = [4, 5, 2, 4, 2, 6, 5, 2, 5]
 
# printing list
print("The original list : " + str(test_list))
 
# assigning same Alphabet to same element
temp = {}
for ele in test_list:
    if ele not in temp:
        temp[ele] = string.ascii_lowercase[len(temp)]
 
# flattening
res = [temp[ele] for ele in test_list]
 
# printing results
print("The mapped List : " + str(res))


Output

The original list : [4, 5, 2, 4, 2, 6, 5, 2, 5]
The mapped List : ['a', 'b', 'c', 'a', 'c', 'd', 'b', 'c', 'b']

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

RELATED ARTICLES

Most Popular

Recent Comments