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
myStr = "thisisit" 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
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] for i in myStr: if[freq[i] == 1]: print[i] break myStr = "thisisit" repeatFunc[myStr]
Output
h
Updated on 11-Aug-2022 11:57:47
- Related Questions & Answers
- Find the first non-repeating character from a stream of characters in Python
- Java program to Find the first non-repeating character from a stream of characters
- Finding first non-repeating character JavaScript
- Finding the first non-repeating character of a string in JavaScript
- Find first repeating character using JavaScript
- How to find its first non-repeating character in a given string in android?
- First non-repeating character using one traversal of string in C++
- Find the last non repeating character in string in C++
- Write a program to find the first non-repeating number in an integer array using Java?
- Queries to find the last non-repeating character in the sub-string of a given string in C++
- Return index of first repeating character in a string - JavaScript
- First non-repeating in a linked list in C++
- Python Program to Remove the nth Index Character from a Non-Empty String
- Finding the index of the first repeating character in a string in JavaScript
- Detecting the first non-repeating string in Array in JavaScript