Open In App

Generate two output strings depending upon occurrence of character in input string in Python

Last Updated : 22 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an input string str[], generate two output strings. One of which consists of that character that occurs only once in the input string and the second consists of multi-time occurring characters. Output strings must be sorted. 

Examples:

Input : str = "geeksforgeeks"
Output : String with characters occurring once:
"for".
String with characters occurring multiple times:
"egks"
Input : str = "geekspractice"
Output : String with characters occurring once:
"agikprst"
String with characters occurring multiple times:
"ce"

We have an existing solution for this problem please refer Generate two output strings depending upon occurrence of character in input string link. We can solve this problem quickly in python using Counter(iterable) method. 

The approach is simple,

  1. Convert string into dictionary having characters as keys and their frequencies as value using counter() method.
  2. Now separate out list of characters having frequency 1 and having frequency more than 1.
  3. Sort characters in both lists to get output strings.

Implementation:

Python3




# Function Generate two output strings depending upon
# occurrence of character in input string
 
from collections import Counter
 
def generateStrings(input):
     
    # convert string into dictionary
    # having characters as keys and frequency as value
    freqDict = Counter(input)
 
    # separate out characters having frequency 1 and more than 1
    freq1 = [ key for (key,count) in freqDict.items() if count==1]
    freqMore1 = [ key for (key,count) in freqDict.items() if count>1]
 
    # sort lists and concatenate characters
    # with out space to print resultant strings
    freq1.sort()
    freqMore1.sort()
 
    # print output strings
    print ('String with characters occurring once:')
    print (''.join(freq1))
    print ('String with characters occurring multiple times:')
    print (''.join(freqMore1))
 
# Driver program
if __name__ == "__main__":
    input = "geeksforgeeks"
    generateStrings(input)


Output

String with characters occurring once:
for
String with characters occurring multiple times:
egks

Time complexity: O(NlogN)
Auxiliary space: O(N)

Method 2: The given program generates two output strings depending upon the occurrence of characters in the input string. Here is an alternative implementation of the same functionality:

Steps:

  1. Define the function generateStrings that takes an input string as a parameter.
  2. Create two empty lists freq1 and freqMore1 to store characters occurring once and multiple times respectively.
  3. Create an empty dictionary char_count to keep track of the count of each character in the input string.
  4. Loop through each character in the input string and check if it is already in the dictionary.
  5. If the character is not in the dictionary, add it with count 1 and append it to freq1.
  6. If the character is already in the dictionary, increment its count and append it to freqMore1.
  7. Sort the lists freq1 and freqMore1 in ascending order.
  8. Concatenate the characters in the lists without spaces.
  9. Print the output strings.
  10. In the driver program, define an input string and call the generateStrings function with this string as a parameter.
  11. The function will print the two output strings.

Example:

Python3




def generateStrings(input_string):
    # Create two empty lists to store characters occurring once and multiple times
    freq1 = []
    freqMore1 = []
 
    # Create a dictionary to keep track of the count of each character
    char_count = {}
 
    # Loop through each character in the input string
    for char in input_string:
        # If the character is not in the dictionary, add it with count 1
        if char not in char_count:
            char_count[char] = 1
            freq1.append(char)
        # If the character is already in the dictionary, increment its count
        else:
            char_count[char] += 1
            freqMore1.append(char)
 
    # Sort the lists and concatenate the characters without spaces
    freq1.sort()
    freqMore1.sort()
 
    # Print the output strings
    print('String with characters occurring once:')
    print(''.join(freq1))
    print('String with characters occurring multiple times:')
    print(''.join(freqMore1))
 
 
# Driver program
if __name__ == "__main__":
    input_string = "geeksforgeeks"
    generateStrings(input_string)


Output

String with characters occurring once:
efgkors
String with characters occurring multiple times:
eeegks

Time Complexity: O(NlogN), where n is the length of the input string. 
Auxiliary Space: O(N) , where n is the length of the input string. 



Similar Reads

Generate two output strings depending upon occurrence of character in input string.
Given an input string str[], generate two output strings. One of which consists of those character which occurs only once in input string and second which consists of multi-time occurring characters. Output strings must be sorted.Examples: Input : str[] = "geeksforgeeks" Output : String with characters occurring once: for String with characters occ
6 min read
PyQt5 - Check box checked state depending upon another check box
Sometimes while creating a GUI(Graphical User Interface) application there is a need to make lot of check boxes, and some check box depend upon the previous check box for example there are two following check box first check box is "Do you have Laptop ?" and second check box is "Your laptop has i7 Processor?" Here we can see that if first check box
3 min read
Index of character depending on frequency count in string
Given a string str containing only lowercase characters, the task is to answer Q queries of the following type: 1 C X: Find the largest i such that str[0...i] has exactly X occurrence of the character C.2 C X: Find the smallest i such that str[0...i] has exactly X occurrence of the character C. Example: Input: str = "geeksforgeeks", query[] = {{1,
10 min read
Divide given numeric string into at most two increasing subsequences which form an increasing string upon concatenation
Given a string S consisting of N digits, the task is to partition the string into at most two increasing subsequences such that concatenation of them also forms an increasing string. If it is not possible to do so, then print "-1". Examples: Input: S = “040425524644”Output: 0022444 44556Explanation:One of the possible way to partition the given str
10 min read
Python - Custom Rows Removal depending on Kth Column
Sometimes, while working with Python Matrix, we can have a problem in which we need to remove elements from Matrix depending on its Kth Column element present in the argument list. This can have application in many domains. Let us discuss certain ways in which this task can be performed. Method #1: Using loop This is a brute way in which this task
7 min read
Python | Prefix extraction depending on size
Sometimes, while working with Python, we can have a problem in which we need to extract prefix from a string. This can be conditional sometimes, and we just need to extract specific length substring if size of string is larger than some N. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop This is brute force way
3 min read
Repeat last occurrence of each alphanumeric character to their position in character family times
Given a string str[] of size N, the task is to encode it in such a way that the last occurrence of each character occurs as long as its position in its family. As 'a' is the first character of its family (lower case alphabet), so it will remain 'a', but 'b' becomes 'bb', 'D' becomes 'DDDD' and so on. In case of numeric characters, the character occ
12 min read
Minimum count of starting elements chosen to visit whole Array depending on ratio of values to positions
Given an array arr[], the task is to calculate the minimum number of starting elements to choose from such that all other elements of the array can be visited. An element can be visited by another element only if the ratio of their values is not inversely proportional to the position of those elements in the array. The position of an element in the
5 min read
Python program to sort matrix based upon sum of rows
Given a Matrix, perform sort based upon the sum of rows. Input : test_list = [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]] Output : [[2, 1], [4, 5], [4, 6, 1], [2, 5, 7]] Explanation : 3 < 9 < 11 < 14. Sorted sum. Input : test_list = [[4, 5], [2, 5, 7], [4, 6, 1]] Output : [[4, 5], [4, 6, 1], [2, 5, 7]] Explanation : 9 < 11 < 14. Sorted sum
6 min read
Group multiple occurrence of array elements ordered by first occurrence
Given an unsorted array with repetitions, the task is to group multiple occurrence of individual elements. The grouping should happen in a way that the order of first occurrences of all elements is maintained. Examples: Input: arr[] = {5, 3, 5, 1, 3, 3} Output: {5, 5, 3, 3, 3, 1} Input: arr[] = {4, 6, 9, 2, 3, 4, 9, 6, 10, 4} Output: {4, 4, 4, 6, 6
11 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg