JavaScript
x
13
13
1
def pairs (x):
2
i = 0
3
z = []
4
while i < len(x)-1:
5
if x[i] == x[i+1]:
6
z.append(x[i])
7
i+=1
8
i+=1
9
return z
10
11
print (pairs([4, 5, 6, 6, 6, 6, 9, 12, 12]))
12
print (pairs([4, 5, 4, 10, 10, 8, 9, 8,9]))
13
My problem is on the last line. In the last line, I wanted to return 4, 8, 9, 10 but it’s only returning 10 instead. Where should I put the sort operation? I tried assigning first, it worked, but only on the assigned value and not whatever the test case would use.
Advertisement
Answer
I used a set to track pair elements and sorted the resulting list.
Program:
JavaScript
1
16
16
1
def pairs(x) :
2
i = 0
3
nums = set()
4
pairs = []
5
for item in x:
6
if item in nums:
7
pairs.append(item)
8
nums.remove(item)
9
else:
10
nums.add(item)
11
pairs.sort()
12
return pairs
13
14
15
print (pairs([4, 5, 4, 10, 10, 8, 9, 8,9]))
16
Result:
JavaScript
1
2
1
[4, 8, 9, 10]
2