def pairs (x):
i = 0
z = []
while i < len(x)-1:
if x[i] == x[i+1]:
z.append(x[i])
i+=1
i+=1
return z
print (pairs([4, 5, 6, 6, 6, 6, 9, 12, 12]))
print (pairs([4, 5, 4, 10, 10, 8, 9, 8,9]))
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:
def pairs(x) :
i = 0
nums = set()
pairs = []
for item in x:
if item in nums:
pairs.append(item)
nums.remove(item)
else:
nums.add(item)
pairs.sort()
return pairs
print (pairs([4, 5, 4, 10, 10, 8, 9, 8,9]))
Result:
[4, 8, 9, 10]