RuslanKain/sorting-searching-recognized-gestures
0
1"""2╔══════════════════════════════════════════════════════════════════════════════╗3║ Models: step.py ║4║ Classes for representing algorithm execution steps ║5╚══════════════════════════════════════════════════════════════════════════════╝6 7This module contains:8• StepType (Enum) - Types of operations (compare, swap, merge, etc.)9• Step (dataclass) - A single step in algorithm execution10 11📚 WHY RECORD STEPS?12 To visualize algorithms step-by-step, we need to RECORD what happens.13 Each Step captures:14 - WHAT operation occurred (compare, swap, etc.)15 - WHERE it happened (which indices)16 - WHEN in the process (depth for recursive algorithms)17 - Additional context (metadata)18 19 This is the "data" that visualization will render.20"""21 22from dataclasses import dataclass, field23from enum import Enum, auto24from typing import List, TYPE_CHECKING25 26# Avoid circular import - only import for type checking27if TYPE_CHECKING:28 from oop_sorting_teaching.models.gesture import GestureImage29 30 31# ==============================================================================32# ENUM: StepType33# ==============================================================================34#35# 📚 CONCEPT: Enums for Type Safety36#37# Instead of using strings like "compare" or "swap", we use an Enum.38# This prevents bugs from typos:39# - String: if step_type == "comprae" # Typo! No error, silent bug40# - Enum: if step_type == StepType.COMPRAE # Python error! Bug caught41# ==============================================================================42 43class StepType(Enum):44 """45 Types of algorithm steps that can be visualized.46 47 Each step in our sorting/searching algorithms will have a type48 that determines how it's displayed in the visualization.49 50 📚 CONCEPT: auto()51 52 The auto() function automatically assigns incrementing values.53 We don't care what the actual numbers are - we just need54 unique identifiers for each step type.55 """56 # Comparison operations57 COMPARE = auto() # Comparing two elements58 59 # Movement operations60 SWAP = auto() # Swapping two elements (in-place algorithms)61 MOVE = auto() # Moving an element to a new position62 63 # Merge sort specific64 SPLIT = auto() # Splitting array into subarrays65 MERGE = auto() # Merging sorted subarrays66 67 # Quick sort specific68 PIVOT_SELECT = auto() # Selecting a pivot element69 PARTITION = auto() # Partitioning around pivot70 71 # Binary search specific72 SEARCH_RANGE = auto() # Showing current search range73 NARROW_LEFT = auto() # Target is in left half74 NARROW_RIGHT = auto() # Target is in right half75 FOUND = auto() # Target element found76 NOT_FOUND = auto() # Target element not in array77 78 # General79 PASS_COMPLETE = auto() # One pass through the data complete (Bubble Sort)80 COMPLETE = auto() # Algorithm finished81 MARK_SORTED = auto() # Mark element(s) as in final position82 83 # Stability detection84 INSTABILITY = auto() # Stability violation detected!85 INSTABILITY_WARNING = auto() # Warning for potential instability86 87 88# ==============================================================================89# DATACLASS: Step90# ==============================================================================91#92# 📚 CONCEPT: Recording Algorithm Execution93#94# When an algorithm runs, we want to show EVERY step:95# 1. What operation happened (StepType)96# 2. Which elements were involved (indices)97# 3. What the array looks like now (array_state)98# 4. Any additional info (metadata)99#100# By recording steps, we can:101# - Play back the algorithm visually102# - Step forward and backward103# - Analyze algorithm behavior104# ==============================================================================105 106@dataclass107class Step:108 """109 Represents a single step in an algorithm's execution.110 111 This is used to record what the algorithm is doing at each point,112 so we can visualize it step by step.113 114 Think of it like frames in a movie:115 - Each Step is one frame116 - Together they tell the story of the algorithm117 118 Attributes:119 step_type: What kind of operation (compare, swap, merge, etc.)120 indices: Which array positions are involved121 description: Human-readable explanation122 depth: Recursion depth (for merge sort / quick sort)123 array_state: Copy of the array at this step124 highlight_indices: Extra indices to highlight (e.g., sorted region)125 metadata: Additional algorithm-specific data126 127 Example:128 step = Step(129 step_type=StepType.COMPARE,130 indices=[3, 4],131 description="Comparing elements at positions 3 and 4",132 depth=0,133 array_state=[...],134 metadata={"comparison_count": 5}135 )136 """137 step_type: StepType138 indices: List[int]139 description: str140 depth: int = 0141 array_state: List['GestureImage'] = field(default_factory=list)142 highlight_indices: List[int] = field(default_factory=list)143 metadata: dict = field(default_factory=dict)144 145 @property146 def type(self) -> StepType:147 """148 Alias for step_type for cleaner access in renderers.149 150 This allows: step.type instead of step.step_type151 Makes the code more readable in visualization code.152 """153 return self.step_type154 155 def __str__(self) -> str:156 """Human-readable string for debugging."""157 indices_str = ', '.join(str(i) for i in self.indices)158 return f"[{self.step_type.name}] indices=[{indices_str}] depth={self.depth}: {self.description}"159 