Skip to content

Latest commit

 

History

History
535 lines (442 loc) · 12.3 KB

File metadata and controls

535 lines (442 loc) · 12.3 KB

Binary Math Education System - Quick Reference Card

For Developers and Implementers Version: 1.0


Core Classes at a Glance

Expression Parser

parser = ExpressionParser()
tree = parser.parse("A AND B OR NOT C")
variables = parser.extract_variables(expression)
is_valid, error = parser.validate_syntax(expression)

Truth Table Generator

generator = TruthTableGenerator()
table = generator.generate("A AND B")
text = table.to_text_table()
minterms = table.get_minterms()

Truth Table Validator

validator = TruthTableValidator()
result = validator.validate(expression, student_table)
score = result.get_score()
feedback = result.get_detailed_feedback()

Problem Generator

generator = ProblemGenerator(random_seed=42)
problem = generator.generate_problem(
    ProblemType.DECIMAL_TO_BINARY,
    DifficultyLevel.BEGINNER
)
hint = problem.get_hint(level=1)

Main System

system = BinaryEducationSystem()
session = system.start_practice_session(student_id)
problem = system.get_next_problem(student_id, session_id)
result = system.submit_answer(student_id, problem_id, answer, hints_used)
progress = system.get_student_progress(student_id)

Data Structures Quick Reference

ExpressionNode

@dataclass
class ExpressionNode:
    operator: Optional[str]  # 'AND', 'OR', 'NOT', 'XOR'
    left: Optional[ExpressionNode]
    right: Optional[ExpressionNode]
    variable: Optional[str]

    # Methods
    evaluate(values: Dict[str, bool]) -> bool
    to_string() -> str
    complexity_score() -> int

TruthTable

@dataclass
class TruthTable:
    expression: str
    variables: List[str]
    rows: List[TruthTableRow]

    # Methods
    to_text_table() -> str
    to_structured_dict() -> Dict
    get_minterms() -> List[str]
    get_maxterms() -> List[str]

Problem

@dataclass
class Problem:
    id: str
    type: ProblemType
    difficulty: DifficultyLevel
    question: str
    solution: Any
    hints: List[str]
    metadata: Dict[str, Any]

    # Methods
    check_answer(student_answer) -> AnswerResult
    get_hint(level: int) -> str
    get_difficulty_score() -> float

StudentProgress

@dataclass
class StudentProgress:
    student_id: str
    total_problems_attempted: int
    total_problems_correct: int
    current_mastery: Dict[ProblemType, float]
    current_difficulty: Dict[ProblemType, DifficultyLevel]
    problem_history: ProblemHistory

    # Methods
    get_overall_progress() -> float
    get_efficiency_score() -> float
    to_dict() -> Dict[str, Any]

Enums

ProblemType

ProblemType.DECIMAL_TO_BINARY
ProblemType.BINARY_TO_DECIMAL
ProblemType.BINARY_ADDITION
ProblemType.BINARY_SUBTRACTION
ProblemType.SIMPLE_GATE
ProblemType.COMPOUND_EXPRESSION
ProblemType.TRUTH_TABLE_FROM_EXPRESSION
ProblemType.EXPRESSION_FROM_TRUTH_TABLE
ProblemType.EXPRESSION_SIMPLIFICATION
ProblemType.BINARY_LOGIC_MIX

DifficultyLevel

DifficultyLevel.BEGINNER      # 1
DifficultyLevel.INTERMEDIATE  # 2
DifficultyLevel.ADVANCED      # 3

Key Algorithms

Generate Truth Table

1. Parse expression to AST
2. Extract and sort variables
3. Generate all 2^n input combinations
4. For each combination:
   - Create input dictionary
   - Evaluate AST with inputs
   - Create TruthTableRow
5. Return TruthTable object

Generate Problem

1. Check student history
2. Calculate success rates by type
3. Identify weak areas (< 70% success)
4. If weak areas exist:
   - Generate similar problem at same/lower difficulty
   Else:
   - Check mastery (> 80% success, > 5 problems)
   - If mastered: increase difficulty
   - Else: maintain current level
5. Select problem type ensuring variety
6. Generate hints (3 levels)
7. Return Problem object

Validate Truth Table

1. Generate correct table
2. Compare row counts
3. For each row:
   - Verify inputs match
   - Compare outputs
   - Track errors
4. Identify error patterns:
   - AND/OR confusion
   - NOT misapplication
   - Order of operations
5. Generate feedback and suggestions
6. Return ValidationResult

Hint Generation (3 Levels)

Level 1 (Nudge):
  - State relevant concept
  - No solution details
  - Example: "Remember division by 2 method"

Level 2 (Guide):
  - Show approach/method
  - Demonstrate first step
  - Example: "Start: 13 ÷ 2 = 6 remainder 1"

Level 3 (Almost There):
  - Show most of work
  - Student completes final step
  - Example: "Binary starts with 110... (finish last 2 bits)"

Difficulty Scoring Formula

score = (
    num_variables * 2.0 +
    num_operators * 1.5 +
    bit_width * 1.0 +
    nesting_depth * 2.5 +
    (requires_simplification ? 3.0 : 0) +
    (multiple_steps ? 2.0 : 0)
)

if score <= 30:
    return DifficultyLevel.BEGINNER
elif score <= 60:
    return DifficultyLevel.INTERMEDIATE
else:
    return DifficultyLevel.ADVANCED

Progression Rules

Advance to Next Difficulty

success_rate >= 80% AND
problems_completed >= 5 AND
avg_hints_used < 2

Stay at Current Level

70% <= success_rate < 80% OR
problems_completed < 5

Remedial Practice

success_rate < 70%

Problem Type Selection

if weak_areas_exist:
    select from weak_areas
elif recently_mastered:
    introduce new topic
else:
    mix of mastered and current topics

Common Patterns

Create and Validate Truth Table

# Generate
expression = "A AND B OR C"
generator = TruthTableGenerator()
correct_table = generator.generate(expression)

# Student attempts
student_table = [
    TruthTableRow({"A": False, "B": False, "C": False}, False),
    # ... more rows
]

# Validate
validator = TruthTableValidator()
result = validator.validate(expression, student_table)

# Feedback
if result.is_correct:
    print(f"Perfect! Score: {result.get_score():.1f}%")
else:
    print(result.get_detailed_feedback())

Complete Practice Session

# Initialize
system = BinaryEducationSystem()
session = system.start_practice_session("student_001")

# Problem loop
for i in range(5):
    # Get problem
    problem = system.get_next_problem("student_001", session.session_id)
    print(f"Problem {i+1}: {problem.question}")

    # Student attempts (simulated)
    answer = get_student_answer()  # Your input method
    hints_used = 0

    # Provide hints if needed
    while needs_hint():
        hints_used += 1
        print(system.get_hint(problem.id, hints_used))

    # Submit
    result = system.submit_answer(
        "student_001",
        problem.id,
        answer,
        hints_used
    )

    print(f"Result: {result.feedback}\n")

# End session and show progress
progress = system.get_student_progress("student_001")
print(f"Session complete! Overall progress: {progress.get_overall_progress():.1f}%")

Track Analytics

# Individual student
progress = system.get_student_progress("student_001")
print(f"Success Rate: {progress.get_overall_progress():.1f}%")
print(f"Efficiency: {progress.get_efficiency_score():.1f}")

for problem_type, mastery in progress.current_mastery.items():
    print(f"{problem_type.value}: {mastery:.1f}%")

# Class-wide
analytics = system.get_learning_analytics("week")
print(f"Class Avg Success: {analytics.average_success_rate:.1f}%")
print(f"Students Needing Help: {analytics.identify_struggling_students()}")

Testing Checklist

Expression Parser

  • Parse simple expression (A AND B)
  • Parse complex expression with parentheses
  • Handle NOT operator correctly
  • Evaluate expression with given values
  • Extract variables correctly

Truth Table Generator

  • Generate table for 2 variables
  • Generate table for 3+ variables
  • Calculate correct outputs
  • Format text table properly
  • Identify minterms/maxterms

Problem Generator

  • Generate each problem type
  • Respect difficulty levels
  • Generate unique problems
  • Create appropriate hints
  • Verify solutions

Validation

  • Detect correct answers
  • Identify specific errors
  • Provide helpful feedback
  • Award partial credit
  • Detect error patterns

Progression

  • Advance on mastery
  • Remediate on weakness
  • Ensure variety
  • Track history
  • Generate recommendations

Performance Tips

Caching

# Cache parsed expressions
expression_cache = {}

def parse_cached(expression: str):
    if expression not in expression_cache:
        expression_cache[expression] = parser.parse(expression)
    return expression_cache[expression]

Pre-generation

# Pre-generate common problems
problem_pool = {}

def init_problem_pool():
    for ptype in ProblemType:
        for difficulty in DifficultyLevel:
            problems = [
                generator.generate_problem(ptype, difficulty)
                for _ in range(10)
            ]
            problem_pool[(ptype, difficulty)] = problems

Lazy Evaluation

# Don't generate hints until requested
@dataclass
class Problem:
    _hints: List[str] = field(default=None, init=False)

    def get_hint(self, level: int) -> str:
        if self._hints is None:
            self._hints = self._generate_hints()
        return self._hints[level - 1]

Error Messages

Common Errors and Solutions

"Unexpected token at position X"

  • Syntax error in expression
  • Check for balanced parentheses
  • Verify operator spelling (AND, OR, NOT, XOR)

"Wrong number of rows"

  • With N variables, need 2^N rows
  • Ensure all input combinations present

"Expression must contain at least one variable"

  • Empty or constant-only expression
  • Add variables (A, B, C, etc.)

"Unknown operator"

  • Unsupported operator in expression
  • Use only: AND, OR, NOT, XOR

Configuration Options

@dataclass
class SystemConfiguration:
    # Problem generation
    max_problems_per_session: int = 20
    default_difficulty: DifficultyLevel = DifficultyLevel.BEGINNER
    difficulty_adaptation_enabled: bool = True

    # Hints
    max_hints_per_problem: int = 3
    hint_penalty: float = 0.1  # 10% per hint

    # Progression
    mastery_threshold: float = 80.0
    advancement_threshold: float = 80.0
    min_problems_before_advancement: int = 5

    # Scoring
    partial_credit_enabled: bool = True
    minimum_score: float = 0.0
    maximum_score: float = 100.0

File Organization

binary/
├── README.md                    # Project overview
├── ARCHITECTURE.md              # Complete architecture
├── IMPLEMENTATION_GUIDE.md      # Code templates
├── SYSTEM_DIAGRAMS.md           # Visual diagrams
├── EXAMPLE_SCENARIOS.md         # Usage examples
├── QUICK_REFERENCE.md           # This file
│
├── src/
│   ├── __init__.py
│   ├── parser.py                # Expression parser
│   ├── truth_tables.py          # Truth table generator
│   ├── problem_generator.py     # Problem generation
│   ├── hints.py                 # Hint system
│   ├── validation.py            # Answer validation
│   ├── progress.py              # Progress tracking
│   ├── analytics.py             # Analytics engine
│   └── main.py                  # Main system class
│
├── tests/
│   ├── test_parser.py
│   ├── test_truth_tables.py
│   ├── test_problem_generator.py
│   ├── test_validation.py
│   └── test_integration.py
│
└── demo.py                      # Demo script

Quick Troubleshooting

Issue Solution
Parser fails on valid expression Check operator spelling, ensure proper spacing
Truth table has wrong row count Verify all variables extracted correctly
Problem difficulty not adapting Check if adaptation enabled in config
Hints not showing Verify hint level (1-3), check hints generated
Progress not updating Ensure submit_answer called after each attempt
Mastery not advancing Check thresholds in configuration

Remember:

  • Always validate input expressions before parsing
  • Track hints used for accurate scoring
  • Update progress immediately after each attempt
  • Generate varied problem types for engagement
  • Provide specific, helpful error messages

For complete details, see ARCHITECTURE.md and IMPLEMENTATION_GUIDE.md