pythonpseudocode

Finding the first duplicate element in an ordered list


I'm new to coding and hit a wall as to what to do with my pseudo code. I am defining a first duplicate function that for a = [1 2 2 3 4 4] it returns 2,

def firstDuplicate(a):
# put first element into new list (blist)
# check second element to blist
# if same, return element and end
# else, try next blist element 
# if no next element, add to end of blist
# do the same with third element (counter) and so on until end of list

alist = list(a)
blist = list(a[1])
bleh = 1
comp = 2

if list(a[comp]) == blist[bleh]:
    return list(a[comp]) # and end
if else bleh = bleh+1 # and repeat til last blist element
# to stop? 

else blist = blist+list(a[2]) # append outside of blist? 

This is what I've done so far. Any suggestions what I do next?


Solution

  • If I understand you correctly, you want to return the first number that appears a second time while you're iterating over the list. To achieve this I would use a set and check if the current item is already in the set, if yes return it, otherwise add the item to the set. (You could do that with a list, too, but less efficiently.)

    def firstDuplicate(a):
        set_ = set()
        for item in a:
            if item in set_:
                return item
            set_.add(item)
        return None