Home > Mobile >  Python: Get the first "encountered" duplicated character in a string
Python: Get the first "encountered" duplicated character in a string

Time:10-29

I am wondering if there is a more efficient way to resolve the following coding test:

Problem: Get the first duplicate char ENCOUNTERED in a string only if more than one dup char is detected, else return None'

Examples:

#1 'abbcdefa' = return 'b' because it is the first encountered DUPLICATE character in the string, while the duplicate 'a' character appears much later than the duplicate 'b'.

#2 'abcdefa' = None (because a is the only dup char in the string)

def first_dup_char(A):
    seen, dups = [], []
    for i in A:
        if i in seen:
            dups.append(i)
        else:
            seen.append(i)
    # if dups list items > 1 then return the first dup else print None
    return dups[0] if len(dups) > 1 else 'None'

My solution above works by utiizing two lists. I wanted to use set() and dict, but unfortunately both of them are unordered, unless I miss something?

CodePudding user response:

you can use a set to update with the letters you encounter while you loop through like this

def first_dup_char(A) :

    seen = set()
    first_dup = None 

    for c in A :
        if c in seen  : 
            if first_dup == None : first_dup = c
            else : return first_dup
        else :
            seen.add(c)
    
    return None

A = "abbcdefa"
print(first_dup_char(A)) # b
B = "abcdefa"
print(first_dup_char(B)) # None

using the variable first_dup you don't lose the information on which one is the first duplicate and also you get to know when you already achieved two pairs of duplicates so that you can return the first one without running the loop till the end.

CodePudding user response:

Do the following :

def duplicated(s):
    for i in range(len(s)-1):
        for j in range(i,len(s)):
            if s[j] == s[i] :
                return s[i]
    return None
  • Related