Skip to content
🤔prompts chat🧠
🔍
question:Code: app/routers/trading.py ```python app/routers/trading.py from typing import List from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from app.db.session import get_db from app.models.trading import TradeCreate, TradeRead, Trade from app.services.trading import TradingService router = APIRouter() @router.post("/trades", response_model=TradeRead) def create_trade(trade: TradeCreate, db: Session = Depends(get_db)): Create a new trade using the provided trade details. trading_service = TradingService(db) created_trade = trading_service.create_trade(trade) if not created_trade: raise HTTPException(status_code=400, detail="Trade could not be created") return created_trade @router.get("/trades/{trade_id}", response_model=TradeRead) def get_trade(trade_id: int, db: Session = Depends(get_db)): Retrieve a trade by its ID. trading_service = TradingService(db) trade = trading_service.get_trade(trade_id) if not trade: raise HTTPException(status_code=404, detail="Trade not found") return trade @router.get("/trades", response_model=List[TradeRead]) def get_trades(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)): Retrieve a list of trades with pagination. trading_service = TradingService(db) trades = trading_service.get_trades(skip=skip, limit=limit) return trades ``` Code: app/models/trading.py ```python app/models/trading.py from typing import Optional from pydantic import BaseModel from datetime import datetime class TradeCreate(BaseModel): symbol: str price: float quantity: int strategy: str class TradeRead(TradeCreate): id: int timestamp: datetime class Config: orm_mode = True from sqlalchemy import Column, Integer, String, Float, DateTime, func from app.db.base import Base class Trade(Base): __tablename__ = "trades" id = Column(Integer, primary_key=True, index=True) symbol = Column(String, index=True) price = Column(Float, nullable=False) quantity = Column(Integer, nullable=False) strategy = Column(String, nullable=False) timestamp = Column(DateTime, server_default=func.now()) ``` Code: app/services/trading.py ```python app/services/trading.py from typing import List, Optional from sqlalchemy.orm import Session from app.models.trading import TradeCreate, TradeRead, Trade class TradingService: def __init__(self, db: Session): self.db = db def create_trade(self, trade_create: TradeCreate) -> Optional[TradeRead]: new_trade = Trade(**trade_create.dict()) self.db.add(new_trade) self.db.commit() self.db.refresh(new_trade) return TradeRead.from_orm(new_trade) def get_trade(self, trade_id: int) -> Optional[TradeRead]: trade = self.db.query(Trade).filter(Trade.id == trade_id).first() if trade: return TradeRead.from_orm(trade) return None def get_trades(self, skip: int = 0, limit: int = 10) -> List[TradeRead]: trades = self.db.query(Trade).offset(skip).limit(limit).all() return [TradeRead.from_orm(trade) for trade in trades] ``` Code: app/tests/test_trading.py ```python app/tests/test_trading.py from fastapi.testclient import TestClient from app.main import app from app.db.session import SessionLocal from app.models.trading import TradeCreate client = TestClient(app) def test_create_trade(): new_trade = { "symbol": "AAPL", "price": 150.0, "quantity": 10, "strategy": "order_imbalance" } response = client.post("/trades", json=new_trade) assert response.status_code == 200 data = response.json() assert data["symbol"] == new_trade["symbol"] assert data["price"] == new_trade["price"] assert data["quantity"] == new_trade["quantity"] assert data["strategy"] == new_trade["strategy"] def test_get_trade(): response = client.get("/trades/1") assert response.status_code == 200 data = response.json() assert data["id"] == 1 def test_get_trades(): response = client.get("/trades?skip=0&limit=10") assert response.status_code == 200 data = response.json() assert isinstance(data, list) assert len(data) <= 10 ```

answer:def add(a, b): Returns the sum of a and b. return a + b

question:Write a Python function that takes a list of strings and returns a dictionary where the keys are the lengths of the strings, and the values are lists of strings of that length. Ensure the function handles various edge cases, such as an empty input list or strings of varying lengths. Additionally, develop unit tests to verify that your function handles typical scenarios as well as edge conditions.

answer:def group_strings_by_length(strings): Groups strings by their lengths. :param strings: List of strings to be grouped :return: Dictionary with string lengths as keys and lists of strings as values result = {} for s in strings: length = len(s) if length not in result: result[length] = [] result[length].append(s) return result

question:Create a class named 'GraphTraversal' that implements both Breadth-First Search (BFS) and Depth-First Search (DFS) for an undirected graph. Your class should have the following methods: 1. `addEdge(u, v)`: Adds an undirected edge between nodes `u` and `v`. 2. `bfs(start)`: Performs a BFS starting from the node `start` and returns the list of nodes in the order they were visited. 3. `dfs(start)`: Performs a DFS starting from the node `start` and returns the list of nodes in the order they were visited. Additionally, ensure your class handles the following scenarios: - The graph can have disconnected components. - If the `start` node provided is not present in the graph, raise an appropriate exception. - Implement internal error handling to deal with cases such as adding an edge between a node and itself or adding multiple identical edges. Finally, include a method `showGraph` to display the adjacency list of the graph. Implement unit tests using the 'unittest' framework to verify the correctness of your BFS and DFS implementations, and test your graph creation for various edge cases.

answer:from collections import deque, defaultdict class GraphTraversal: def __init__(self): self.graph = defaultdict(list) def addEdge(self, u, v): if u == v: raise ValueError("Cannot add an edge between a node and itself") if v not in self.graph[u]: self.graph[u].append(v) self.graph[v].append(u) def bfs(self, start): if start not in self.graph: raise ValueError(f"Start node {start} is not present in the graph") visited = set() queue = deque([start]) result = [] while queue: node = queue.popleft() if node not in visited: visited.add(node) result.append(node) for neighbour in self.graph[node]: if neighbour not in visited: queue.append(neighbour) return result def dfs(self, start): if start not in self.graph: raise ValueError(f"Start node {start} is not present in the graph") visited = set() stack = [start] result = [] while stack: node = stack.pop() if node not in visited: visited.add(node) result.append(node) for neighbour in reversed(self.graph[node]): if neighbour not in visited: stack.append(neighbour) return result def showGraph(self): return dict(self.graph)

question:Develop a function that takes a binary tree and calculates the sum of all left leaves. A left leaf is defined as a node that is a leaf (it has no children) and is the left child of its parent. You need to design a BinaryTree class with an insert method to create the tree, and then a method to calculate the sum of left leaves. Consider edge cases such as a tree with only one node or no left leaves. ```python class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree: def __init__(self): self.root = None def insert(self, value): if self.root is None: self.root = Node(value) else: self._insert_recursive(self.root, value) def _insert_recursive(self, current, value): if value < current.value: if current.left is None: current.left = Node(value) else: self._insert_recursive(current.left, value) else: if current.right is None: current.right = Node(value) else: self._insert_recursive(current.right, value) def sum_of_left_leaves(self): def _sum_of_left_leaves(node, is_left): if node is None: return 0 if is_left and node.left is None and node.right is None: return node.value return _sum_of_left_leaves(node.left, True) + _sum_of_left_leaves(node.right, False) return _sum_of_left_leaves(self.root, False) # Example usage: # Construct the binary tree bt = BinaryTree() bt.insert(7) bt.insert(5) bt.insert(10) bt.insert(3) bt.insert(6) bt.insert(8) bt.insert(12) # Calculate the sum of left leaves print(bt.sum_of_left_leaves()) # Output should be the sum of values of left leaves nodes ```

answer:class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree: def __init__(self): self.root = None def insert(self, value): if self.root is None: self.root = Node(value) else: self._insert_recursive(self.root, value) def _insert_recursive(self, current, value): if value < current.value: if current.left is None: current.left = Node(value) else: self._insert_recursive(current.left, value) else: if current.right is None: current.right = Node(value) else: self._insert_recursive(current.right, value) def sum_of_left_leaves(self): def _sum_of_left_leaves(node, is_left): if node is None: return 0 if is_left and node.left is None and node.right is None: return node.value return _sum_of_left_leaves(node.left, True) + _sum_of_left_leaves(node.right, False) return _sum_of_left_leaves(self.root, False)

Released under the chat License.

has loaded