Python - Concatenate Dynamic Frequency
Last Updated :
27 Apr, 2023
Given List of elements, perform concatenation with frequency dynamically, i.e each element is concatenated with its frequency till its index.
Input : test_list = ['z', 'z', 'e', 'f', 'f']
Output : ['1z', '2z', '1e', '1f', '2f']
Explanation : As occurrence increase, concat number is increased.
Input : test_list = ['g', 'f', 'g']
Output : ['1g', '1f', '2g']
Explanation : As occurrence increase, concat number is increased.
Method 1 : Using defaultdict() + "+" operator + str()
In this, the dynamic frequency computation is done using defaultdict() and str() is used to convert elements to string for valid concatenation using "+" operator.
Python3
# Python3 code to demonstrate working of
# Concatenate Dynamic Frequency
# Using defaultdict() + "+" operator + str()
from collections import defaultdict
# initializing list
test_list = ['z', 'z', 'e', 'f', 'f', 'e', 'f', 'z', 'c']
# printing original list
print("The original list is : " + str(test_list))
memo = defaultdict(int)
res = []
for ele in test_list:
memo[ele] += 1
# adding Frequency with element
res.append(str(memo[ele]) + str(ele))
# printing result
print("Dynamic Frequency list : " + str(res))
OutputThe original list is : ['z', 'z', 'e', 'f', 'f', 'e', 'f', 'z', 'c']
Dynamic Frequency list : ['1z', '2z', '1e', '1f', '2f', '2e', '3f', '3z', '1c']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 2: Using slicing and count() method
Python3
# Python3 code to demonstrate working of
# Concatenate Dynamic Frequency
# initializing list
test_list = ['z', 'z', 'e', 'f', 'f', 'e', 'f', 'z', 'c']
# printing original list
print("The original list is : " + str(test_list))
res = []
for i in range(0, len(test_list)):
a = test_list[:i+1].count(test_list[i])
b = str(a)+test_list[i]
res.append(b)
# printing result
print("Dynamic Frequency list : " + str(res))
OutputThe original list is : ['z', 'z', 'e', 'f', 'f', 'e', 'f', 'z', 'c']
Dynamic Frequency list : ['1z', '2z', '1e', '1f', '2f', '2e', '3f', '3z', '1c']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 3: Using operator.countOf() method
Python3
# Python3 code to demonstrate working of
# Concatenate Dynamic Frequency
import operator as op
# initializing list
test_list = ['z', 'z', 'e', 'f', 'f', 'e', 'f', 'z', 'c']
# printing original list
print("The original list is : " + str(test_list))
res = []
for i in range(0, len(test_list)):
a = op.countOf(test_list[:i+1], test_list[i])
b = str(a)+test_list[i]
res.append(b)
# printing result
print("Dynamic Frequency list : " + str(res))
OutputThe original list is : ['z', 'z', 'e', 'f', 'f', 'e', 'f', 'z', 'c']
Dynamic Frequency list : ['1z', '2z', '1e', '1f', '2f', '2e', '3f', '3z', '1c']
Time Complexity: O(N)
Auxiliary Space : O(N)
Method 4: Using dictionary comprehension + f-string
This approach also uses a dictionary to keep track of the frequency of each element and concatenates the frequency with the element using f-strings. Then, it creates a list of the concatenated strings using dictionary comprehension.
Follow the below steps to implement the above idea:
- Initialize the input list test_list with the given values.
- Create an empty dictionary memo to keep track of the frequency of each element.
- Iterate over each element ele in the test_list.
- Check if the element ele already exists in the memo dictionary.
- If the element ele exists in the memo dictionary, increment its frequency count by 1.
- If the element ele does not exist in the memo dictionary, set its frequency count to 1.
- Concatenate the frequency of the element ele with the element ele using f-strings and append it to the res list.
- Return the final concatenated list res using dictionary comprehension.
- Print the result.
Below is the implementation of the above approach:
Python3
# initializing list
test_list = ['z', 'z', 'e', 'f', 'f', 'e', 'f', 'z', 'c']
# printing original list
print("The original list is : " + str(test_list))
# create a dictionary to keep track of the frequency of each element
memo = {}
for ele in test_list:
if ele in memo:
memo[ele] += 1
else:
memo[ele] = 1
# concatenate frequency with element using f-strings and create a list of concatenated strings using dictionary comprehension
res = [f"{memo[ele]}{ele}" for ele in test_list]
# printing result
print("Dynamic Frequency list : " + str(res))
OutputThe original list is : ['z', 'z', 'e', 'f', 'f', 'e', 'f', 'z', 'c']
Dynamic Frequency list : ['3z', '3z', '2e', '3f', '3f', '2e', '3f', '3z', '1c']
Time complexity: O(n)
Auxiliary space: O(n)
Method 5: Using Counter() from collections module
Approach:
- Import the Counter() function from the collections module.
- Pass the original list as an argument to the Counter() function to create a dictionary with the frequency of each element.
- Use a list comprehension to iterate over the original list and concatenate the frequency with each element.
- Store the concatenated strings in a new list.
- Print the new list.
Below is the implementation of the above approach:
Python3
# Import the Counter() function from the collections module
from collections import Counter
# Initializing list
test_list = ['z', 'z', 'e', 'f', 'f', 'e', 'f', 'z', 'c']
# Printing original list
print("The original list is : " + str(test_list))
# Use Counter() function to create a dictionary with the frequency of each element
freq_dict = Counter(test_list)
# Concatenate frequency with element using f-strings and create a list of concatenated strings using dictionary comprehension
res = [f"{freq_dict[ele]}{ele}" for ele in test_list]
# Printing result
print("Dynamic Frequency list : " + str(res))
OutputThe original list is : ['z', 'z', 'e', 'f', 'f', 'e', 'f', 'z', 'c']
Dynamic Frequency list : ['3z', '3z', '2e', '3f', '3f', '2e', '3f', '3z', '1c']
Time complexity: O(n + k log k), where n is the length of the input list and k is the number of unique elements in the list.
Auxiliary space: O(n + k), where n is the length of the input list and k is the number of unique elements in the list.
Method 6: Using a loop and list comprehension
- We first initialize the input list test_list with some values.
- We print the original list using print().
- We use a loop and list comprehension to generate the dynamic frequency list.
- We iterate over the indices of the elements in test_list using enumerate().
- For each element ele in test_list, we slice the list up to that index using test_list[:i+1].
- We count the frequency of the element in the sliced list using the count() method.
- We concatenate the frequency with the element using the + operator and append it to the res list.
- Finally, we print the dynamic frequency list using print().
Example:
Python3
# Python3 code to demonstrate working of
# Concatenate Dynamic Frequency
# Using a loop and list comprehension
# initializing list
test_list = ['z', 'z', 'e', 'f', 'f', 'e', 'f', 'z', 'c']
# printing original list
print("The original list is : " + str(test_list))
# using loop and list comprehension to generate dynamic frequency list
res = [str(test_list[:i+1].count(ele)) + ele for i, ele in enumerate(test_list)]
# printing result
print("Dynamic Frequency list : " + str(res))
OutputThe original list is : ['z', 'z', 'e', 'f', 'f', 'e', 'f', 'z', 'c']
Dynamic Frequency list : ['1z', '2z', '1e', '1f', '2f', '2e', '3f', '3z', '1c']
Time complexity: O(n^2) due to the nested loops used in the count() method, where n is the length of the input list.
Auxiliary space: O(n) because we are using an additional list res to store the dynamic frequency list.
Method 7: Using default dictionary and loop to generate frequency list
- In this approach, we use a default dictionary to store the frequency of each character encountered in the list.
- We then loop over the list and append the frequency and character to a result list.
- We use the defaultdict to automatically initialize the frequency to 0 for any character not yet encountered in the list.
Python3
from collections import defaultdict
# initializing list
test_list = ['z', 'z', 'e', 'f', 'f', 'e', 'f', 'z', 'c']
# printing original list
print("The original list is : " + str(test_list))
# Using default dictionary and loop to generate frequency list
freq_dict = defaultdict(int)
res = []
for c in test_list:
freq_dict[c] += 1
res.append(str(freq_dict[c]) + c)
# printing result
print("Dynamic Frequency list : " + str(res))
OutputThe original list is : ['z', 'z', 'e', 'f', 'f', 'e', 'f', 'z', 'c']
Dynamic Frequency list : ['1z', '2z', '1e', '1f', '2f', '2e', '3f', '3z', '1c']
Time complexity: O(n)
Auxiliary space: O(n)
Similar Reads
Consecutive characters frequency - Python
This problem involves identifying characters that appear consecutively and counting how many times they appear together. Here, we will explore different methods to calculate the frequency of consecutive characters in a string.Using regular expressionsWe can use the re module to efficiently count con
3 min read
Python - Convert Frequency dictionary to list
When we convert a frequency dictionary to a list, we are transforming the dictionary into a list of key-value or just the keys/values, depending on needs. We can convert a frequency dictionary to a list using methods such as list comprehension, loops, extend() method and itertools.chain() function.F
3 min read
Create Dynamic Dictionary in Python
Creating a Dynamic Dictionary in Python is important in programming skills. By understanding how to generate dictionaries dynamically, programmers can efficiently adapt to changing data requirements, facilitating flexible and responsive code development. In this article, we will explore different me
3 min read
Python - Expand Character Frequency String
Given a string, which characters followed by its frequency, create the appropriate string. Examples: Input : test_str = 'g7f2g3i2s2b3e4' Output : gggggggffgggiissbbbeeee Explanation : g is succeeded by 7 and repeated 7 times. Input : test_str = 'g1f1g1' Output : gfg Explanation : f is succeeded by 1
4 min read
Python | Tuple Column element frequency
In Python, we need to handle various forms of data and one among them is a list of tuples in which we may have to perform any kind of operation. This particular article discusses the ways of finding the frequency of the Kth element in the list of tuples. Letâs discuss certain ways in which this can
5 min read
Python - Group concatenate Till K
Given list of strings, perform concatenation in groups till K. Input : test_list = ["Gfg", "is", "Best", "", "I", "Love", "", "Gfg"], K = "" Output : ['Gfg is Best', 'I Love', 'Gfg'] Explanation : Concatenated words with "" as new String separator. Input : test_list = ["Gfg", "is", "Best", "", "I",
9 min read
Python - Similar Consecutive elements frequency
Sometimes, while working with Python, we can have a problem in which we have to find the occurrences of elements that are present consecutively. This problem have usage in school programming and data engineering. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop
5 min read
Python | Concatenate dictionary value lists
Sometimes, while working with dictionaries, we might have a problem in which we have lists as it's value and wish to have it cumulatively in single list by concatenation. This problem can occur in web development domain. Let's discuss certain ways in which this task can be performed. Method #1 : Usi
5 min read
Python - Frequency Grouping Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the grouping of dictionary data, in a way in which we need to group all the similar dictionaries key with its frequency. This kind of problem has its application in web development domain. Let's disc
4 min read
Python - Concatenate Dictionary string values
The task of concatenating string values in a Python dictionary involves combining the values associated with the same key across multiple dictionaries. This operation allows us to merge string data in an efficient manner, especially when dealing with large datasets .For example, given two dictionari
4 min read