Python Program to Expand Character Frequency String


In Python, strings are among the most often used types. These are easily made by simply surrounding letters in quotations. Python treats single quotes and double quotes the same way. Assigning a value to a variable and creating a string is really straightforward.

In this article, we will learn how to expand a character frequency string in python.

Methods Used

The following are the various methods to accomplish this task:

  • Using zip() and join() functions

  • Using re(regex) module and join() function

  • Without using any built-in functions

Example

Assume we have taken an input string containing characters followed by their frequency. We will now expand the characters with the following frequency.

Input

inputString = 'p5y3t6h2o1n4'

Output

Resultant string after expanding − pppppyyytttttthhonnnn

In this input string, the character ‘p’ is expanded 5 times, y is expanded 3 times, …and so on as per the following frequency after the character.

Using zip() and join() functions

In this method, we are going to use zip() and join() functions of python to expand character’s frequency string and print the output.

Syntax

join()

join() is a string function in Python that is used to join elements of a sequence that are separated by a string separator. This function connects sequence elements to convert to a string.

zip() 

The zip() function can be used to combine two lists/iterators.

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task –.

  • Create a variable to store the input string containing characters followed by their frequency.

  • Print the input string.

  • Traverse through the zip() function of the string to combine iterators where the first iterator iterates over character and the second iterates over frequency.

  • Multiply the first iterator with the second iterator to repeat/expand the character.

  • Convert this zip object to a string using the join() function.

  • Print the resultant string after expanding.

Example

The following program returns the expanded character frequency string of an input string using zip() and join() functions –

# input string containing characters followed by their frequency.
inputString = 'p5y3t6h2o1n4'
# printing input string
print("Input String: ", inputString)
# Creating a pair(p,q) using zip function 
# where p stands for character and q stands for its frequency
# Multiplying character(p) with q to repeat q times
expandStr = "".join(p * int(q)
   for p, q in zip(inputString[0::2], inputString[1::2]))
# printing the resultant string after expanding
print("Resultant string after expanding:", expandStr)

Output

On executing, the above program will generate the following output –

Input String:  p5y3t6h2o1n4
Resultant string after expanding: pppppyyytttttthhonnnn

Time Complexity: O(n)

Auxiliary Space: O(n)

Using re(regex) module and join() function

In this method we are going to use regex module and join function to expand character frequency string.

re.findall()− 

All non-overlapping matches of pattern in a string, as a list of strings, is returned by the findall() function. The string is scanned from left to right, and matches are returned in the order they were found.

The following program returns the expanded character frequency string of an input string using regex module and join() functions –

# importing re i.e, regex module
import re
# input string containing characters followed by their frequency.
inputString = 'p5y3t6h2o1n4'
# printing input string
print("Input String: ", inputString)
# Longer digit strings can be included by using findall 
# to match together numbers and characters independently.
expandStr = ''.join(charactr * int(n or 1)
   for charactr, n in re.findall(r'(\w)(\d+)?', inputString))
# printing the resultant string after expanding
print("Resultant string after expanding:", expandStr)

Output

On executing, the above program will generate the following output –

Input String:  p5y3t6h2o1n4
Resultant string after expanding: pppppyyytttttthhonnnn

Without using any built-in functions

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task –

  • Create a variable to store the input string containing characters followed by their frequency.

  • Print the input string.

  • Initializing an empty list for storing characters.

  • Initializing another empty list for storing their respective frequencies.

  • Use the for loop to traverse through each character of the input string till its length with the len() function(returns a number of items in an object).

  • Use the if conditional statement to check whether the current index is even with the modulo(%) operator.

  • Use the append() function(adds the element to the list at the end) to append that corresponding element at the current index to the characters list if the condition is true

  • Else append that frequency character as an integer to the frequency list.

  • Create an empty string for storing the resultant expanded string.

  • Use again the for loop to traverse through the characters list till its length.

  • Multiply the character at the current index with its frequency and concatenate it to the resultant expanded string using the ‘+’ operator.

  • Print the resultant string after expanding.

Example

The following program returns the expanded character frequency string of an input string without using any built-in functions –

# input string containing characters followed by their frequency.
inputString = 'p5y3t6h2o1n4'
# printing input string
print("Input String: ", inputString)
# empty list for storing characters
charsList = []
# empty list for storing their frequencies
freqList = []
# traversing through each character of the input string till its length
for p in range(0, len(inputString)):
  # checking whether the current index is even
    if(p % 2 == 0):
        # appending that corresponding element at the current index to
        # the characters list if the condition is true
        charsList.append(inputString[p])
    else:
        # otherwise appending that @@ to the frequency list
        freqList.append(int(inputString[p]))
# storing resultant expanded string
expandStr = ""
# traversing through the characters list till its length
for p in range(0, len(charsList)):
  # multiplying character at current index with its frequency
  # and concatenating it to the expanded string
    expandStr += charsList[p]*freqList[p]
# printing the resultant string after expanding
print("Resultant string after expanding:", expandStr)

Output

On executing, the above program will generate the following output –

Input String:  p5y3t6h2o1n4
Resultant string after expanding: pppppyyytttttthhonnnn

Conclusion

In this article, we learned three distinct ways to expand character frequency strings. Additionally, we learned how to loop through the iterators while combining them using the zip() function. Finally, a straightforward method for solving this issue without the use of any built-in functions was demonstrated by utilizing the modulus(%) operator.

Updated on: 18-Aug-2023

152 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements