Search TreesWrite a class Stock with attributes for Symbol, Name, Purchase Price, Quantity that you can add to a search treeWrite a program that allows the user to buy stock and adds it to a...




Write a class Stock with attributes for Symbol, Name, Purchase Price, Quantity that you can add to a search tree




Write a program that allows the user to buy stock and adds it to a search tree of stocks they own




Search Trees Write a class Stock with attributes for Symbol, Name, Purchase Price, Quantity that you can add to a search tree Write a program that allows the user to buy stock and adds it to a search tree of stocks they own Solution class Stock: def __init__(self, symbol, name, purchase_price, quantity): self.symbol = symbol self.name = name self.purchase_price = purchase_price self.quantity = quantity class Node: def __init__(self, stock): self.stock = stock self.left = None self.right = None class StockTree: def __init__(self): self.root = None def insert(self, stock): node = Node(stock) if self.root is None: self.root = node else: current = self.root while True: if stock.symbol < current.stock.symbol:="" if="" current.left="" is="" none:="" current.left="node" break="" else:="" current="current.left" elif="" stock.symbol=""> current.stock.symbol: if current.right is None: current.right = node break else: current = current.right else: current.stock.quantity += stock.quantity break def buy_stock(): symbol = input("Enter symbol: ") name = input("Enter name: ") purchase_price = float(input("Enter purchase price: ")) quantity = int(input("Enter quantity: ")) stock = Stock(symbol, name, purchase_price, quantity) return stock def main(): stock_tree = StockTree() while True: print("1. Buy stock\n2. Print portfolio\n3. Exit") choice = input("Enter choice: ") if choice == '1': stock = buy_stock() stock_tree.insert(stock) elif choice == '2': print("Symbol\tName\tPurchase Price\tQuantity") print("-----------------------------------------------") print_portfolio(stock_tree.root) elif choice == '3': break else: print("Invalid choice") def print_portfolio(node): if node is not None: print_portfolio(node.left) stock = node.stock print(f"{stock.symbol}\t{stock.name}\t{stock.purchase_price}\t\t{stock.quantity}") print_portfolio(node.right) if __name__ == '__main__': main()
Apr 01, 2023
SOLUTION.PDF

Get Answer To This Question

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here