Python Forum
First non-repeating char and some errors. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: First non-repeating char and some errors. (/thread-15160.html)



First non-repeating char and some errors. - blackknite - Jan-06-2019

Hey, I do some coding challenges online and I have issue with this one.

At first I did this:
>>> q = lambda s:['' if not s else c for c in s if s.count(c)<=1][0]
>>> q('~><#~><')
'#'
But it throw some assertion error on website, something is bugged with their tests so I cant use any indexing and lists cause it throws out of range error, sounds like more challenge but Im stuck with:
>>> def first_non_repeating_letter(x):
    f=0
     
    for i in list(x):
        if i.isalpha():
            f=x.count(i.lower())+x.count(i.upper())
        else:
            f+=x.count(i)
        if f==1:
            return i
    return ""

>>> first_non_repeating_letter('~><#~><')
''
It should return '#' but it returns "" or None so it basically jumps over the counting to the empty string case and I dont know why.


RE: First non-repeating char and some errors. - stullis - Jan-06-2019

The problem is line 8. Because f is defined outside of the loop, it never resets to 0. So, the function checks for "~" and add 2 to f; now that f = 2, it checks for "<" and adds two again; etc.

As an added challenge, I refactored this to only 8 lines (including two blank lines) and only called str.lower() once. Give that a shot.