
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find First Non-Repeating Character from a Stream in Python
In this article, we will find the first non-repeating character from a stream of character. Let's say the following is our input ?
Thisisit
The following should be our output displaying first non-repeating character ?
H
Find the first non-repeating character from a stream of characters using while loop
We will find the first non-repeating character, by comparing each character with the other using a loop ?
Example
# String myStr = "thisisit" # Looping while myStr != "": slen0 = len(myStr) ch = myStr[0] myStr = myStr.replace(ch, "") slen1 = len(myStr) if slen1 == slen0-1: print ("First non-repeating character = ",ch) break; else: print ("No Unique Character Found!")
Output
No Unique Character Found! First non-repeating character = h
Find the first non-repeating character from a stream of characters using a function
We can also create a custom function and pass the string to it for finding the first non-repeating character ?
Example
# Custom function def RepeatingFunc(myStr): char_order = [] counts = {} for c in myStr: if c in counts: counts[c] += 1 else: counts[c] = 1 char_order.append(c) for c in char_order: if counts[c] == 1: return c return None print("First Non-Repeating Character = ",RepeatingFunc('thisisit'))
Output
First Non-Repeating Character = h
Find the first non-repeating character from a stream of characters using Counter()
The Counter can also be used from the Collections module to find the first non-repeating character. This module implements specialized container datatypes providing alternatives to Python's general purpose built-in containers, dict, list, set, and tuple ?
Example
from collections import Counter def repeatFunc(myStr): freq = Counter(myStr) # Traverse the string for i in myStr: if(freq[i] == 1): print(i) break # Driver code myStr = "thisisit" repeatFunc(myStr)
Output
h