Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def calculate_net_profit_loss(events):
- stocks = {}
- transactions = []
- result = []
- for event in events:
- event_parts = event.split()
- if event_parts[0] == 'BUY':
- stock_name = event_parts[1]
- quantity = int(event_parts[2])
- if stock_name not in stocks:
- stocks[stock_name] = {'quantity': quantity, 'price': 0}
- else:
- stocks[stock_name]['quantity'] += quantity
- elif event_parts[0] == 'SELL':
- stock_name = event_parts[1]
- quantity = int(event_parts[2])
- if stock_name in stocks and stocks[stock_name]['quantity'] >= quantity:
- stocks[stock_name]['quantity'] -= quantity
- else:
- return "Invalid sell operation"
- elif event_parts[0] == 'CHANGE':
- stock_name = event_parts[1]
- price_change = float(event_parts[2])
- if stock_name in stocks:
- stocks[stock_name]['price'] += price_change
- else:
- return "Invalid stock price change operation"
- elif event_parts[0] == 'QUERY':
- net_profit_loss = sum(
- stocks[stock]['quantity'] * stocks[stock]['price'] for stock in stocks
- )
- result.append(net_profit_loss)
- return result
- events = [
- "BUY stock2 2", "BUY stock1 4", "CHANGE stock2 -8", "SELL stock1 2", "BUY stock3 3", "QUERY"
- ]
- print(calculate_net_profit_loss(events))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement