查找有序列表中的第一个重复元素

Tar*_*rae 1 python pseudocode

我是编码新手,对于如何处理我的伪代码感到困惑。我正在定义第一个重复函数,对于 a = [1 2 2 3 4 4] 它返回 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? 
Run Code Online (Sandbox Code Playgroud)

这就是我到目前为止所做的。有什么建议我下一步要做什么吗?

skr*_*krx 6

如果我理解正确的话,您想在迭代列表时返回第二次出现的第一个数字。为了实现这一点,我将使用一个集合并检查当前项目是否已在集合中,如果是则返回它,否则将项目添加到集合中。(您也可以使用列表来做到这一点,但效率较低。)

def firstDuplicate(a):
    set_ = set()
    for item in a:
        if item in set_:
            return item
        set_.add(item)
    return None
Run Code Online (Sandbox Code Playgroud)