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

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 string, while the duplicate 'a' appears much later than the duplicate 'b'

#2 'abcdefa' = None (because a is the only dup char in 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?



from Recent Questions - Stack Overflow https://ift.tt/3EwwzNT
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation