Write a program to find the first non repeating character in a string
Answers
We will need a program to return the first element in a string which is repeated just once.
To achieve this, we will be using the following:
(1) List operation
(2) count() function
____________________________________________
count() -
What this function does is it counts the number of times a specific character repeats itself in a string,list,tuple,set.
We will be using this function to see how many times each character in a string repeats and add all the characters to an other list whose count would be 1 and we would be printing the first character of the new list we get.
_____________________________________________
PROCESS:
- Create an empty list
- Count the frequency of each element in the string
- Append the elements whose frequency is 1 to the new,empty list
- Print out the first element of the new list, index = 0
______________________________________________
CODE:
String = 'books in a rack'
letters_no_repeat = [x for x in String if String.count(x) == 1 ] #checks for the count of each element and adds the elements of count 1 to a list called letters_no_repeat
print(letters_no_repeat[0]) #prints the first element of the new list
OUTPUT:
b
SOURCE CODE:-
def first_non_repeating_character(str1):
char_order = []
ctr = {}
for c in str1:
if c in ctr:
ctr[c] += 1
else:
ctr[c] = 1 char_order.append(c)
for c in char_order:
if ctr[c] == 1:
return c
return None
print(first_non_repeating_character('abcdef'))
print(first_non_repeating_character('abcabcdef'))
print(first_non_repeating_character('aabbcc'))