I'm new to python and I was going through a few problem to practice. The question is:
#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)
My understanding is that after the "break" it should end the loop, so I should just get 2. Instead it goes through the entire thing and I get 2, 5, and 1. What am I not getting?
Perhaps it is easier to understand if you put a print(repeats)
right after assigning repeats[arr] = ...
Iteration 1: arr == 2
{2: 1} # key `2` was created and assigned `0 + 1`
Iteration 2: arr == 5
{2: 1, 5: 1} # key `5` created and assigned `0 + 1`
Iteration 3: arr == 1
{2: 1, 5: 1, 1: 1} # key `1` created and assigned `0 + 1`
Iteration 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
The first time through the loop, arrs
is 2. That key does not yet exist in the dictionary, so repeats[2]
is created with a value of 1, and the program prints 2
.
The second time through the loop, arrs
is 5. That key does not yet exist in the dictionary, so repeats[5]
is created with a value of 1, and the program prints 5
.
The third time through the loop, arrs
is 1. That key does not yet exist in the dictionary, so repeats[1]
is created with a value of 1, and the program prints 1
.
The fourth time through the loop, arrs
is 2. That key already exists in the dictionary with a value of 1, so repeats[2]
is assigned a new value of 2, and the loop breaks.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.