While preparing for an interview I saw the following question as follows:
Following tuple is given as input, where first element is CustomerID and second element is ProductID. We need to find the output as consecutive longest in order sequence of ProductID which every customer buys.
Input: [('A','Milk'), ('B','Milk'), ('A','Apples'), ('A','Coffee'),
('B','Apples'),('C','Apples'), ('B','Coffee'), ('A','Vegetable'), ('B', 'Hat')]
Output: Milk, Apples, Coffee (Max order 3)
# Maintain the order of the tuple
My attempt is as follows:
Input= [('A','Milk'), ('B','Milk'), ('A','Apples'), ('A','Coffee'),
('B','Apples'),('C','Apples'), ('B','Coffee'), ('A','Vegetable'), ('B', 'Hat')]
result=[]
for a, b in Input:
if b not in result and len(result)<3:
result.append(b)
print ', '.join(result)
The answer for the above solution is as expected. Is there any easier solution or can I use other data structure to solve it? Thanks!