I read of a job interview question to write some code for the following:
Write an efficient function to find the first nonrepeated character in a st
from collections import defaultdict
word="googlethis"
dici=defaultdict(int)
#build up dici with counts of characters
for a in word:
if dici[a]:
dici[a]+=1
for a in word:
if didic[a] < 2:
return a
wouldn't that work?
input_str = "interesting"
#input_str = "aabbcc"
#input_str = "aaaapaabbcccq"
def firstNonRepeating(param):
counts = {}
for i in range(0, len(param)):
# Store count and index repectively
if param[i] in counts:
counts[param[i]][0] += 1
else:
counts[param[i]] = [1, i]
result_index = len(param) - 1
for x in counts:
if counts[x][0] == 1 and result_index > counts[x][1]:
result_index = counts[x][1]
return result_index
result_index = firstNonRepeating(input_str)
if result_index == len(input_str)-1:
print("no such character found")
else:
print("first non repeating charater found: " + input_str[result_index])
In [1033]: def firstNonRep(word):
......: c = collections.Counter(word)
......: for char in word:
......: if c[char] == 1:
......: return char
......:
In [1034]: word="googlethis"
In [1035]: firstNonRep(word)
Out[1035]: 'l'
EDIT: If you want to implement the same thing without using helpers like Counter
:
def firstNonRep(word):
count = {}
for c in word:
if c not in count:
count[c] = 0
count[c] += 1
for c in word:
if count[c] == 1:
return c
sorted(word,key=lambda x:(word.count(x),word.index(x)) )[0]
I think or DSM's also consice
next(c for c in word if word.count(c) == 1)
which is marginally more efficient
>>> word = "teeter"
>>> sorted(word,key=lambda x:(word.count(x),word.index(x)) )[0]
'r'
>>> word = "teetertotter"
>>> sorted(word,key=lambda x:(word.count(x),word.index(x)) )[0]
'o'
>>> word = "teetertotterx"
>>> sorted(word,key=lambda x:(word.count(x),word.index(x)) )[0]
'o'
Three lines of python code to get the solution:
word="googlethis"
processedList = [x for x in word if word.count(x)==1]
print("First non-repeated character is: " +processedList[0])
Or,
word="googlethis"
print([x for x in word if word.count(x)==1][0])
# I came up with another solution but not efficient comment?
str1 = "awbkkzafrocfbvwcqbb"
list1 = []
count = 0
newlen = len(str1)
find = False
def myfun(count, str1, list1, newlen):
for i in range(count, newlen):
if i == 0:
list1.append(str1[i])
else:
if str1[i] in list1:
str1 = str1.translate({ord(str1[i]): None})
print(str1)
newlen = len(str1)
count =0
i = count
list1.pop()
myfun(count,str1,list1,newlen)
else:
pass
if str1.find(list1[0], 1, len(str1)) != -1 :
pass
else:
print(list1[0]+" is your first non repeating character")
exit()
myfun(count, str1, list1, newlen)