Python: Create two strings from a given string
Separate single and multiple occurrence chars.
Write a Python program to generate two strings from a given string. For the first string, use the characters that occur only once, and for the second, use the characters that occur multiple times in the said string.
Visual Presentation:
Sample Solution:
Python Code:
# Import Counter from collections
from collections import Counter
# Function to generate two strings
def generateStrings(input):
# Create a character counter from input
str_char_ctr = Counter(input)
# Part 1 contains single occurrence characters
part1 = [key for (key,count) in str_char_ctr.items() if count==1]
# Part 2 contains multiple occurrence characters
part2 = [key for (key,count) in str_char_ctr.items() if count>1]
# Sort the characters in each part
part1.sort()
part2.sort()
return part1,part2
# Test input string
input = "aabbcceffgh"
# Generate the two strings
s1, s2 = generateStrings(input)
# Print first string
print(''.join(s1))
# Print second string
print(''.join(s2))
Sample Output:
egh abcf
Flowchart:
Python Code Editor:
Previous: Write a Python program to remove all consecutive duplicates of a given string.
Next: Write a Python program to find the longest common sub-string from two given strings.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics