Python Forum
First non-repeating char and some errors.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
First non-repeating char and some errors.
#1
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.
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why is 2/3 not just .666 repeating? DocFro 4 643 Dec-12-2023, 09:09 AM
Last Post: buran
Sad How to split a String from Text Input into 40 char chunks? lastyle 7 1,054 Aug-01-2023, 09:36 AM
Last Post: Pedroski55
  repeating a user_input astral_travel 17 2,136 Oct-26-2022, 04:15 PM
Last Post: astral_travel
  if else repeating Frankduc 12 2,424 Jul-14-2022, 12:40 PM
Last Post: Frankduc
  matching a repeating string Skaperen 2 1,197 Jun-23-2022, 10:34 PM
Last Post: Skaperen
  Random Number Repeating Tzenesh 5 3,925 Jan-13-2021, 10:00 PM
Last Post: deanhystad
  How to replace on char with another in a string? korenron 3 2,293 Dec-03-2020, 07:37 AM
Last Post: korenron
  How to remove char from string?? ridgerunnersjw 2 2,482 Sep-30-2020, 03:49 PM
Last Post: ridgerunnersjw
  factorial, repeating Aldiyar 4 2,738 Sep-01-2020, 05:22 PM
Last Post: DPaul
  number repeating twice in loop JonnyEnglish 3 3,258 Nov-24-2019, 09:23 AM
Last Post: ThomasL

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020