Advertisement
rajeshinternshala

Untitled

Nov 18th, 2023
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.50 KB | None | 0 0
  1. def calculate_net_profit_loss(events):
  2.     stocks = {}
  3.     transactions = []
  4.     result = []
  5.  
  6.     for event in events:
  7.         event_parts = event.split()
  8.         if event_parts[0] == 'BUY':
  9.             stock_name = event_parts[1]
  10.             quantity = int(event_parts[2])
  11.             if stock_name not in stocks:
  12.                 stocks[stock_name] = {'quantity': quantity, 'price': 0}
  13.             else:
  14.                 stocks[stock_name]['quantity'] += quantity
  15.         elif event_parts[0] == 'SELL':
  16.             stock_name = event_parts[1]
  17.             quantity = int(event_parts[2])
  18.             if stock_name in stocks and stocks[stock_name]['quantity'] >= quantity:
  19.                 stocks[stock_name]['quantity'] -= quantity
  20.             else:
  21.                 return "Invalid sell operation"
  22.         elif event_parts[0] == 'CHANGE':
  23.             stock_name = event_parts[1]
  24.             price_change = float(event_parts[2])
  25.             if stock_name in stocks:
  26.                 stocks[stock_name]['price'] += price_change
  27.             else:
  28.                 return "Invalid stock price change operation"
  29.         elif event_parts[0] == 'QUERY':
  30.             net_profit_loss = sum(
  31.                 stocks[stock]['quantity'] * stocks[stock]['price'] for stock in stocks
  32.             )
  33.             result.append(net_profit_loss)
  34.  
  35.     return result
  36.  
  37.  
  38. events = [
  39.     "BUY stock2 2", "BUY stock1 4", "CHANGE stock2 -8", "SELL stock1 2", "BUY stock3 3", "QUERY"
  40. ]
  41.  
  42. print(calculate_net_profit_loss(events))
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement