Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Python program to Find the first non-repeating character from a stream of characters?


1 Answer
George John

In this section we are going to find the first unique or non-repeating character from a string or stream of characters. There are multiple ways to solve this problem. We will try to create two different program for the same stream of characters.

Method 1: Using function

def firstNonRepeatingChar(str1):
   char_order = []
   counts = {}
   for c in str1:
      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(firstNonRepeatingChar('PythonforallPythonMustforall'))
print(firstNonRepeatingChar('tutorialspointfordeveloper'))
print(firstNonRepeatingChar('AABBCC'))

Result

M
u
None

Above program give O(n) solution. In above program we first loop through the string once. Once we find a new character, we store it in counts object with a value of 1 and append it to char_order. When we come across a repeated character, we increment the value of counts by 1. Finally, we loop through char_order until we find a character with a value of 1 in char_order and return it.

Method 2: Using while loop

s = "tutorialspointfordeveloper"
while s != "":
   slen0 = len(s)
   ch = s[0]
   s = s.replace(ch, "")
   slen1 = len(s)
   if slen1 == slen0-1:
      print ("First non-repeating character is: ",ch)
      break;
   else:
   print ("No Unique Character Found!")

Result

First non-repeating character is: u

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.