我是python的新手,我经历了一些需要练习的问题。问题是:
#Given an array, return the first recurring character
#Example1 : array = [2,1,4,2,6,5,1,4]
#It should return 2
#Example 2 : array = [2,6,4,6,1,3,8,1,2]
#It should return 6
lsts = [2,5,1,2,3,5,1,2,4]
def findDouble(arrs):
repeats = dict()
for arr in arrs:
repeats[arr] = repeats.get(arr, 0) + 1
if repeats[arr] == 2: break
print(arr)
findDouble(lsts)
#0(n)
我的理解是;中断";它应该结束循环,所以我应该只得到2。相反,它会贯穿整个过程,得到2、5和1。我没有得到什么?
第一次通过循环时,arrs
为2。字典中还不存在该键,因此创建了值为1的repeats[2]
,程序打印2
。
第二次通过循环时,arrs
为5。字典中还不存在该键,因此创建了值为1的repeats[5]
,程序打印5
。
第三次通过循环,arrs
为1。字典中还不存在该键,因此创建了值为1的repeats[1]
,程序打印1
。
第四次通过循环,arrs
为2。该关键字已存在于字典中,值为1,因此repeats[2]
被分配了一个新值2,循环中断。
如果在分配repeats[arr] = ...
之后立即放置print(repeats)
,可能会更容易理解
迭代1:arr==2
{2: 1} # key `2` was created and assigned `0 + 1`
迭代2:arr==5
{2: 1, 5: 1} # key `5` created and assigned `0 + 1`
迭代3:arr==1
{2: 1, 5: 1, 1: 1} # key `1` created and assigned `0 + 1`
迭代4:arr==2
{2: 2, 5: 1, 1: 1} # key `2` was already present, assigned `1 + 1`
repeat[arr] == 2: # evaluates to True, so it breaks