Last active
February 2, 2021 20:01
-
-
Save Obayanju/e7181410b0528648072838e88d64516a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
You are given a snapshot of a queue of stocks that have changing prices coming in from a stream. Remove the outdated stocks from the queue. | |
Example: | |
$ snapshot = [ | |
{ sym: ‘GME’, cost: 280 }, | |
{ sym: ‘PYPL’, cost: 234 }, | |
{ sym: ‘AMZN’, cost: 3206 }, | |
{ sym: ‘AMZN’, cost: 3213 }, | |
{ sym: ‘GME’, cost: 325 } | |
] | |
$ stockQueue(snapshot) | |
$ [{ sym: ‘PYPL’, cost: 234 }, | |
{ sym: ‘AMZN’, cost: 3213 }, | |
{ sym: ‘GME’, cost: 325 }] | |
''' | |
from collections import defaultdict | |
def RemoveOutdatedStocks(snapshot): | |
stocks = defaultdict(int) | |
for stock in snapshot: | |
sym, cost = stock['sym'], stock['cost'] | |
stocks[sym] = cost | |
mostRecent = [] | |
for sym, cost in stocks.items(): | |
mostRecent.append({'sym': sym, 'cost': cost}) | |
return mostRecent | |
stocks = [ | |
{ 'sym': 'GME', 'cost': 280 }, | |
{ 'sym': 'PYPL','cost': 234 }, | |
{ 'sym': 'AMZN','cost': 3206 }, | |
{ 'sym': 'AMZN','cost': 3213 }, | |
{ 'sym': 'GME', 'cost': 325 } | |
] | |
print(RemoveOutdatedStocks(stocks)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment