Python Forum

Full Version: First non-repeating char and some errors.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.
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.