Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Generate Two Output Strings Depending upon Occurrence of Character in Input String - Python
Next article icon

Generate Two Output Strings Depending upon Occurrence of Character in Input String - Python

Last Updated : 30 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of generating two output strings based on the occurrence of characters in an input string in Python involves classifying characters based on their frequency. We need to create one string that contains characters that appear only once in the input string and another string for characters that appear more than once. For example, given the string s = "geeksforgeeks", the first output string should contain characters that appear once, while the second output string will contain characters that appear more than once.

Using collections.Counter

Counter from the collections module efficiently count the frequency of characters in a string. It then separates the characters into two lists . One for characters occurring once and another for those occurring more than once. Finally, both lists are sorted alphabetically and joined into strings for output.

Python
from collections import Counter  s = "hello" d = Counter(s) # create counter object  # Separate characters into those with count 1 and greater than 1 a = [char for char, count in d.items() if count == 1] b = [char for char, count in d.items() if count > 1]  print(''.join(sorted(a)))   print(''.join(sorted(b)))  

Output
eho l 

Explanation:

  • Two lists are created where a contains characters with count of 1 and b contains characters with count greater than 1.
  • Both lists are sorted alphabetically using sorted() and then joined into strings with ''.join().

Table of Content

  • Using for loop
  • Using defaultdict
  • Using itertools.groupby()

Using for loop

This method counts character frequencies in a string by going through it just once, storing the counts in a dictionary. After counting, it separates the characters into two lists. The lists are then sorted and combined into strings. This approach is efficient as it avoids repeatedly counting characters and ensures faster processing by using a single pass through the string.

Python
s = "hello"  d = {}   # Single pass over input string to count frequencies for char in s:     d[char] = d.get(char, 0) + 1  # Separate characters into two lists a = [char for char, count in d.items() if count == 1] b = [char for char, count in d.items() if count > 1]  print(''.join(sorted(a))) print(''.join(sorted(b))) 

Output
eho l 

Explanation:

  • split characters into two lists, one for those occurring once and another for those occurring more than once.
  • sort both lists alphabetically and join them into strings for display.

Using defaultdict

This approach uses defaultdict to count the frequency of characters in the input string, where each character is initialized with a default count of 0. The characters are then divided into two groups. Both groups are sorted alphabetically and returned as strings.

Example:

Python
from collections import defaultdict  s = "hello" count = defaultdict(int) # Creates a defaultdict  for char in s:     count[char] += 1  a = [char for char, freq in count.items() if freq == 1] b = [char for char, freq in count.items() if freq > 1]  print(''.join(sorted(a))) print(''.join(sorted(b))) 

Output
eho l 

Explanation:

  • for char in s loops through each character in the input string s and increments its count in the count dictionary. If the character doesn't exist, it's initialized to 0 and incremented by 1.
  • Two lists are created where a contains characters with count of 1 and b contains characters with count greater than 1 and Both lists are sorted alphabetically using sorted() and then joined into strings with ''.join().

Using itertools.groupby()

itertools.groupby from itertools groups consecutive occurrences of the same element. This method requires sorting the string first, making it less efficient compared to single-pass methods like Counter and defaultdict.

Python
from itertools import groupby  s = "hello" sorted_s = sorted(s) # Sorts the input string `s` alphabetically  a = [] # initialize empty list to store characters that appear once b = [] # initialize empty list to store characters that appear more than once  for char, group in groupby(sorted_s):     if len(list(group)) == 1:         a.append(char)     else:         b.append(char)  print(''.join(sorted(a))) print(''.join(sorted(b))) 

Output
eho l 

Explanation:

  • for char, group in groupby(sorted_s) iterates over the sorted string grouping consecutive occurrences of each character.
  • if len(list(group)) == 1 adds characters that appear once to a otherwise adds characters that appear more than once to b.

Next Article
Generate Two Output Strings Depending upon Occurrence of Character in Input String - Python

S

Shashank Mishra
Improve
Article Tags :
  • Strings
  • Python
  • DSA
  • python-string
Practice Tags :
  • python
  • Strings

Similar Reads

    Python - Replacing Nth occurrence of multiple characters in a String with the given character
    Replacing the Nth occurrence of multiple characters in a string with a given character involves identifying and counting specific character occurrences.Using a Loop and find()Using a loop and find() method allows us to search for the first occurrence of a substring within each list element. This app
    2 min read
    Python - Replace all occurrences of a substring in a string
    Replacing all occurrences of a substring in a string means identifying every instance of a specific sequence of characters within a string and substituting it with another sequence of characters. Using replace()replace () method is the most straightforward and efficient way to replace all occurrence
    2 min read
    Replacing Characters in a String Using Dictionary in Python
    In Python, we can replace characters in a string dynamically based on a dictionary. Each key in the dictionary represents the character to be replaced, and its value specifies the replacement. For example, given the string "hello world" and a dictionary {'h': 'H', 'o': 'O'}, the output would be "Hel
    2 min read
    Capitalize Each String in a List of Strings in Python
    In Python, manipulating strings is a common task, and capitalizing each string in a list is a straightforward yet essential operation. This article explores some simple and commonly used methods to achieve this goal. Each method has its advantages and use cases, providing flexibility for different s
    3 min read
    Python - Check if substring present in string
    The task is to check if a specific substring is present within a larger string. Python offers several methods to perform this check, from simple string methods to more advanced techniques. In this article, we'll explore these different methods to efficiently perform this check.Using in operatorThis
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences