Project: Binary Math Education Modules Target Audience: Freshman Computer Science Students Version: 1.0 Date: 2025-10-15
- System Overview
- Module 1: Truth Tables Generator
- Module 2: Practice Generator
- Integration Architecture
- Data Structures
- Implementation Guidelines
- Modularity: Each module functions independently but integrates seamlessly
- Progressive Complexity: Problems scale from beginner to advanced
- Educational Focus: Every feature designed to enhance learning
- Data-Driven: Track progress and adapt to student performance
┌─────────────────────────────────────────────────────────┐
│ Binary Education System │
├─────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────┐ ┌──────────────────┐ │
│ │ Truth Tables │◄────────►│ Practice │ │
│ │ Generator │ │ Generator │ │
│ └────────┬────────┘ └────────┬─────────┘ │
│ │ │ │
│ └────────┬──────────────────┘ │
│ │ │
│ ┌────────▼────────┐ │
│ │ Core Modules │ │
│ ├─────────────────┤ │
│ │ binary_basics │ │
│ │ logic_gates │ │
│ └─────────────────┘ │
│ │ │
│ ┌────────▼────────┐ │
│ │ Progress Tracker│ │
│ └─────────────────┘ │
└─────────────────────────────────────────────────────────┘
Expression := OrExpr
OrExpr := AndExpr ( "OR" AndExpr )*
AndExpr := XorExpr ( "AND" XorExpr )*
XorExpr := NotExpr ( "XOR" NotExpr )*
NotExpr := "NOT" NotExpr | Primary
Primary := "(" Expression ")" | Variable
Variable := [A-Z]
class ExpressionParser:
"""
Recursive descent parser for logic expressions.
Supports: AND, OR, NOT, XOR operators
Precedence: NOT > AND > XOR > OR
"""
def parse(self, expression: str) -> ExpressionNode
def tokenize(self, expression: str) -> List[Token]
def validate_syntax(self, tokens: List[Token]) -> bool
def extract_variables(self, expression: str) -> Set[str]@dataclass
class ExpressionNode:
"""AST node for logic expressions"""
operator: Optional[str] # 'AND', 'OR', 'NOT', 'XOR', None for leaf
left: Optional[ExpressionNode]
right: Optional[ExpressionNode]
variable: Optional[str] # Only for leaf nodes
def evaluate(self, values: Dict[str, bool]) -> bool
def to_string(self) -> str
def complexity_score(self) -> int- Tokenization: Split expression into tokens (operators, variables, parentheses)
- Validation: Check for balanced parentheses, valid operators, valid variables
- AST Construction: Build abstract syntax tree using recursive descent
- Optimization: Simplify expressions where possible (optional)
@dataclass
class TruthTableRow:
"""Single row in a truth table"""
inputs: Dict[str, bool]
output: bool
def to_string(self, variables: List[str]) -> str
"""Format as: A=0, B=1, C=0 => 1"""
class TruthTableGenerator:
"""Generate and validate truth tables"""
def generate(self, expression: str) -> TruthTable
def validate_student_table(
self,
expression: str,
student_table: List[TruthTableRow]
) -> ValidationResult
def format_for_display(
self,
table: TruthTable,
format: str = "text"
) -> str@dataclass
class TruthTable:
expression: str
variables: List[str] # Sorted alphabetically
rows: List[TruthTableRow]
def to_text_table(self) -> str
"""
A | B | C | Result
--|---|---|-------
0 | 0 | 0 | 0
0 | 0 | 1 | 1
...
"""
def to_structured_dict(self) -> Dict
"""JSON-serializable structure"""
def get_minterms(self) -> List[str]
"""Return minterms (rows where output is 1)"""
def get_maxterms(self) -> List[str]
"""Return maxterms (rows where output is 0)"""class TruthTableGuide:
"""Generate learning guides for truth table structure"""
def generate_template(self, variables: List[str]) -> str
"""Create empty truth table template"""
def generate_partial_solution(
self,
expression: str,
reveal_percentage: float = 0.5
) -> str
"""Show partial solution as a hint"""
def explain_row(
self,
expression: str,
row_index: int
) -> str
"""Explain how to calculate a specific row"""@dataclass
class ValidationResult:
is_correct: bool
errors: List[str]
suggestions: List[str]
correct_rows: int
total_rows: int
def get_score(self) -> float
"""Return percentage correct"""
def get_detailed_feedback(self) -> str
"""Return formatted feedback for student"""
class TruthTableValidator:
"""Validate student-created truth tables"""
def validate_structure(
self,
student_table: List[TruthTableRow]
) -> List[str]
"""Check for structural errors (missing rows, wrong format)"""
def validate_logic(
self,
expression: str,
student_table: List[TruthTableRow]
) -> ValidationResult
"""Check correctness of outputs"""
def identify_pattern_errors(
self,
student_table: List[TruthTableRow]
) -> List[str]
"""Identify common mistakes (e.g., AND vs OR confusion)"""class ProblemType(Enum):
# Binary Conversion
DECIMAL_TO_BINARY = "decimal_to_binary"
BINARY_TO_DECIMAL = "binary_to_decimal"
BINARY_ADDITION = "binary_addition"
BINARY_SUBTRACTION = "binary_subtraction"
# Logic Gates
SIMPLE_GATE = "simple_gate"
COMPOUND_EXPRESSION = "compound_expression"
TRUTH_TABLE_FROM_EXPRESSION = "truth_table_from_expression"
EXPRESSION_FROM_TRUTH_TABLE = "expression_from_truth_table"
EXPRESSION_SIMPLIFICATION = "expression_simplification"
# Mixed
BINARY_LOGIC_MIX = "binary_logic_mix"
class DifficultyLevel(Enum):
BEGINNER = 1 # Single concept, 2-4 bits
INTERMEDIATE = 2 # Multiple steps, 4-6 bits
ADVANCED = 3 # Complex logic, 6-8 bits, optimizationclass ProblemGenerator:
"""Generate randomized practice problems"""
def __init__(self, random_seed: Optional[int] = None):
self.rng = random.Random(random_seed)
self.used_problems = set() # Avoid duplicates
def generate_problem(
self,
problem_type: ProblemType,
difficulty: DifficultyLevel,
constraints: Optional[Dict] = None
) -> Problem
def generate_problem_set(
self,
count: int,
difficulty_distribution: Dict[DifficultyLevel, float]
) -> List[Problem]
def get_next_recommended_problem(
self,
student_history: StudentProgress
) -> Problem@dataclass
class Problem:
id: str # Unique identifier
type: ProblemType
difficulty: DifficultyLevel
question: str
solution: Any # Type depends on problem type
hints: List[str] # Progressive hints
metadata: Dict[str, Any] # Additional info
def check_answer(self, student_answer: Any) -> AnswerResult
def get_hint(self, level: int) -> str
def get_difficulty_score(self) -> floatclass BinaryConversionGenerator:
"""Generate binary conversion problems"""
def generate_decimal_to_binary(
self,
difficulty: DifficultyLevel
) -> Problem:
"""
Beginner: 0-15 (4 bits)
Intermediate: 16-127 (7 bits)
Advanced: 128-255 (8 bits)
"""
def generate_binary_to_decimal(
self,
difficulty: DifficultyLevel
) -> Problem:
"""Similar to above but reversed"""
def generate_binary_arithmetic(
self,
operation: str, # 'add' or 'subtract'
difficulty: DifficultyLevel
) -> Problem:
"""
Beginner: 2-bit + 2-bit
Intermediate: 4-bit + 4-bit with carry
Advanced: 8-bit with overflow detection
"""class LogicExpressionGenerator:
"""Generate logic gate problems"""
def generate_simple_gate(
self,
difficulty: DifficultyLevel
) -> Problem:
"""
Beginner: Single gate (A AND B)
Intermediate: Two gates (A AND (B OR C))
Advanced: Three+ gates with NOT
"""
def generate_truth_table_problem(
self,
difficulty: DifficultyLevel
) -> Problem:
"""Generate truth table completion problems"""
def generate_simplification_problem(
self,
difficulty: DifficultyLevel
) -> Problem:
"""
Generate expressions that can be simplified.
E.g., (A AND B) OR (NOT A AND B) => B
"""class MixedProblemGenerator:
"""Generate problems combining binary and logic"""
def generate_mixed_problem(
self,
difficulty: DifficultyLevel
) -> Problem:
"""
Example: "What is the binary result of (5 AND 3)?"
Requires: decimal->binary, logic operation, binary->decimal
"""- Level 1 (Nudge): Point to relevant concept, no solution details
- Level 2 (Guide): Show approach/method, partial work
- Level 3 (Almost There): Show most of the solution, student completes
class HintGenerator:
"""Generate progressive hints for problems"""
def generate_hints(self, problem: Problem) -> List[str]:
"""Generate all three hint levels"""
return [
self._generate_level1_hint(problem),
self._generate_level2_hint(problem),
self._generate_level3_hint(problem)
]
def _generate_level1_hint(self, problem: Problem) -> str:
"""
Level 1: Conceptual nudge
Examples:
- "Remember how to convert decimal to binary by repeated division"
- "Think about what AND means - both inputs must be true"
- "Draw out the truth table rows systematically"
"""
def _generate_level2_hint(self, problem: Problem) -> str:
"""
Level 2: Methodological guide
Examples:
- "Start by dividing 13 by 2: 13 ÷ 2 = 6 remainder 1"
- "First evaluate (A AND B), then apply NOT to the result"
- "You have 3 variables, so you need 2^3 = 8 rows"
"""
def _generate_level3_hint(self, problem: Problem) -> str:
"""
Level 3: Near-complete solution
Examples:
- "13 = 1101 in binary. Here's how: [shows work]"
- "When A=1, B=0: A AND B = 0, so NOT(0) = 1"
- "First 4 rows completed: [shows rows]. Now you complete the rest"
"""HINT_STRATEGIES = {
ProblemType.DECIMAL_TO_BINARY: {
"level1": "concept_reminder", # Remind about division method
"level2": "first_step_shown", # Show first division
"level3": "partial_solution" # Show 60% of work
},
ProblemType.TRUTH_TABLE_FROM_EXPRESSION: {
"level1": "structure_guide", # Remind about number of rows
"level2": "example_row", # Show how to do one row
"level3": "most_rows_complete" # Complete all but 2 rows
},
ProblemType.EXPRESSION_SIMPLIFICATION: {
"level1": "simplification_laws", # Remind about boolean laws
"level2": "identify_pattern", # Point out which law to use
"level3": "show_steps" # Show simplification steps
}
}@dataclass
class AnswerResult:
is_correct: bool
feedback: str
partial_credit: float # 0.0 to 1.0
detailed_errors: List[str]
suggestions: List[str]
class SolutionVerifier:
"""Verify student answers across problem types"""
def verify_binary_conversion(
self,
problem: Problem,
student_answer: str
) -> AnswerResult:
"""Verify binary conversion answers"""
def verify_arithmetic(
self,
problem: Problem,
student_answer: str
) -> AnswerResult:
"""Verify binary arithmetic with partial credit"""
def verify_logic_expression(
self,
problem: Problem,
student_answer: str
) -> AnswerResult:
"""Verify logic expressions (handles equivalent forms)"""
def verify_truth_table(
self,
problem: Problem,
student_table: List[TruthTableRow]
) -> AnswerResult:
"""Verify truth table answers"""@dataclass
class ProblemAttempt:
problem_id: str
timestamp: datetime
student_answer: Any
is_correct: bool
hints_used: int
time_spent: int # seconds
difficulty: DifficultyLevel
problem_type: ProblemType
class ProblemHistory:
"""Track student's problem-solving history"""
def __init__(self, student_id: str):
self.student_id = student_id
self.attempts: List[ProblemAttempt] = []
def add_attempt(self, attempt: ProblemAttempt):
"""Record a new attempt"""
def get_success_rate(
self,
problem_type: Optional[ProblemType] = None,
difficulty: Optional[DifficultyLevel] = None
) -> float:
"""Calculate success rate, optionally filtered"""
def get_weak_areas(self) -> List[ProblemType]:
"""Identify problem types with low success rates"""
def get_average_hints_used(self) -> float:
"""Calculate average hints per problem"""
def get_progress_trend(self) -> Dict[str, Any]:
"""Analyze improvement over time"""class BinaryBasics:
"""Core binary operations module"""
@staticmethod
def decimal_to_binary(decimal: int, width: Optional[int] = None) -> str
@staticmethod
def binary_to_decimal(binary: str) -> int
@staticmethod
def binary_add(a: str, b: str) -> Tuple[str, bool]
"""Returns (result, overflow)"""
@staticmethod
def binary_subtract(a: str, b: str) -> Tuple[str, bool]
"""Returns (result, borrow)"""
@staticmethod
def validate_binary_string(binary: str) -> boolclass LogicGates:
"""Core logic operations module"""
@staticmethod
def AND(a: bool, b: bool) -> bool
@staticmethod
def OR(a: bool, b: bool) -> bool
@staticmethod
def NOT(a: bool) -> bool
@staticmethod
def XOR(a: bool, b: bool) -> bool
@staticmethod
def NAND(a: bool, b: bool) -> bool
@staticmethod
def NOR(a: bool, b: bool) -> bool
@staticmethod
def evaluate_expression(
expression: str,
values: Dict[str, bool]
) -> boolclass IntegratedProblemGenerator:
"""Generates problems using both modules"""
def __init__(
self,
binary_basics: BinaryBasics,
logic_gates: LogicGates,
truth_table_gen: TruthTableGenerator,
practice_gen: ProblemGenerator
):
self.binary = binary_basics
self.logic = logic_gates
self.truth_tables = truth_table_gen
self.practice = practice_gen
def generate_mixed_problem(
self,
difficulty: DifficultyLevel
) -> Problem:
"""
Example mixed problems:
1. "What is 1011 AND 1101 in decimal?"
2. "Create a truth table for the circuit that adds two 2-bit numbers"
3. "Simplify: (A AND 1) OR (A AND 0)"
"""
def generate_progressive_problem_set(
self,
start_difficulty: DifficultyLevel,
count: int
) -> List[Problem]:
"""Generate set that progressively increases difficulty"""class DifficultyScorer:
"""Calculate difficulty scores for problems"""
WEIGHTS = {
'num_variables': 2.0, # More variables = harder
'num_operators': 1.5, # More operators = harder
'bit_width': 1.0, # More bits = harder
'nesting_depth': 2.5, # Deeper nesting = harder
'requires_simplification': 3.0,
'multiple_steps': 2.0
}
def calculate_score(self, problem: Problem) -> float:
"""
Returns score from 0-100:
0-30: Beginner
31-60: Intermediate
61-100: Advanced
"""
def classify_difficulty(self, score: float) -> DifficultyLevel:
"""Convert score to difficulty level"""
def adjust_problem_difficulty(
self,
problem: Problem,
target_score: float
) -> Problem:
"""Modify problem to hit target difficulty"""class ProgressionEngine:
"""Recommend next problems based on student progress"""
def __init__(self, history: ProblemHistory):
self.history = history
def recommend_next_problem(self) -> Tuple[ProblemType, DifficultyLevel]:
"""
Algorithm:
1. Identify weak areas (success rate < 70%)
2. If weak areas exist, generate similar problems at same/lower difficulty
3. If no weak areas, increase difficulty in strong areas
4. Ensure variety - don't repeat same type too often
5. Occasionally introduce new problem types
"""
def get_mastery_level(
self,
problem_type: ProblemType
) -> float:
"""
Return mastery (0-100) for a problem type:
- Based on success rate
- Weighted by difficulty of problems solved
- Recent performance weighted more heavily
"""
def should_advance_difficulty(
self,
problem_type: ProblemType
) -> bool:
"""
Determine if student is ready for harder problems.
Criteria:
- 80%+ success rate on current difficulty
- At least 5 problems completed at current difficulty
- Average hints used < 2
"""
def generate_learning_path(
self,
target_mastery: Dict[ProblemType, float]
) -> List[Problem]:
"""Generate sequence of problems to reach target mastery"""from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from typing import List, Dict, Optional, Any, Set
# Previously defined enums and classes...
@dataclass
class StudentProgress:
"""Complete student progress tracking"""
student_id: str
registration_date: datetime
problem_history: ProblemHistory
current_mastery: Dict[ProblemType, float]
current_difficulty: Dict[ProblemType, DifficultyLevel]
total_problems_attempted: int = 0
total_problems_correct: int = 0
total_hints_used: int = 0
total_time_spent: int = 0 # seconds
def get_overall_progress(self) -> float:
"""Overall progress percentage (0-100)"""
if self.total_problems_attempted == 0:
return 0.0
return (self.total_problems_correct / self.total_problems_attempted) * 100
def get_efficiency_score(self) -> float:
"""Score based on hints used and time spent"""
if self.total_problems_attempted == 0:
return 0.0
avg_hints = self.total_hints_used / self.total_problems_attempted
# Lower is better (max 3 hints per problem)
return max(0, 100 - (avg_hints / 3 * 100))
def to_dict(self) -> Dict[str, Any]:
"""Serialize for storage"""@dataclass
class PracticeSession:
"""Single practice session"""
session_id: str
student_id: str
start_time: datetime
end_time: Optional[datetime] = None
problems_attempted: List[str] = field(default_factory=list) # Problem IDs
problems_correct: int = 0
session_type: str = "practice" # 'practice', 'quiz', 'review'
def get_duration(self) -> int:
"""Return session duration in seconds"""
if self.end_time is None:
return 0
return int((self.end_time - self.start_time).total_seconds())
def get_success_rate(self) -> float:
"""Return success rate for this session"""
if not self.problems_attempted:
return 0.0
return (self.problems_correct / len(self.problems_attempted)) * 100@dataclass
class LearningAnalytics:
"""Aggregate analytics for instructors"""
time_period: str # 'day', 'week', 'month'
student_count: int
total_problems_generated: int
total_problems_attempted: int
average_success_rate: float
problem_type_distribution: Dict[ProblemType, int]
difficulty_distribution: Dict[DifficultyLevel, int]
most_difficult_problems: List[str] # Problem IDs
most_common_errors: List[Dict[str, Any]]
def get_engagement_score(self) -> float:
"""Overall engagement metric"""
def identify_struggling_students(self) -> List[str]:
"""Students who may need intervention"""
@dataclass
class ProblemStatistics:
"""Statistics for a specific problem"""
problem_id: str
times_attempted: int = 0
times_correct: int = 0
average_hints_used: float = 0.0
average_time_spent: float = 0.0
success_rate: float = 0.0
def update_with_attempt(self, attempt: ProblemAttempt):
"""Update statistics with new attempt"""@dataclass
class SystemConfiguration:
"""System-wide configuration"""
# Problem generation settings
max_problems_per_session: int = 20
default_difficulty: DifficultyLevel = DifficultyLevel.BEGINNER
difficulty_adaptation_enabled: bool = True
# Hint settings
max_hints_per_problem: int = 3
hint_penalty: float = 0.1 # Reduce score by 10% per hint
# Progression settings
mastery_threshold: float = 80.0 # % to consider "mastered"
advancement_threshold: float = 80.0 # % to advance difficulty
min_problems_before_advancement: int = 5
# Time limits (optional)
problem_time_limit: Optional[int] = None # seconds
session_time_limit: Optional[int] = None # seconds
# Scoring
partial_credit_enabled: bool = True
minimum_score: float = 0.0
maximum_score: float = 100.0- Implement
BinaryBasicsmodule - Implement
LogicGatesmodule - Create basic data structures
- Set up testing framework
- Implement expression parser
- Build truth table generator
- Create validation system
- Add visual guides
- Implement problem generators for each type
- Build hint system
- Create solution verifier
- Add problem history tracking
- Integrate both modules
- Implement difficulty scoring
- Build progression engine
- Create analytics system
- Comprehensive testing
- User acceptance testing with students
- Performance optimization
- Documentation
# MVP-level testing: 2-5 tests per component
# Truth Table Tests
def test_parse_simple_expression()
def test_generate_truth_table_basic()
def test_validate_student_table()
# Practice Generator Tests
def test_generate_binary_problem()
def test_generate_logic_problem()
def test_hint_progression()
def test_verify_answer()
# Integration Tests
def test_mixed_problem_generation()
def test_difficulty_scoring()
def test_progression_recommendation()Language: Python 3.9+
Core Libraries:
- dataclasses: Data structures
- enum: Type safety
- typing: Type hints
- datetime: Time tracking
Optional Enhancements:
- pydantic: Data validation
- pytest: Testing
- sqlite3: Persistence
- rich: Terminal formatting-
Truth Table Generation
- Cache parsed expressions
- Limit to 6 variables (64 rows) for interactive use
- Pre-generate common expressions
-
Problem Generation
- Seed random generator for reproducibility
- Keep pool of pre-generated problems
- Lazy load solutions
-
Analytics
- Aggregate statistics periodically
- Index by student_id and problem_type
- Archive old session data
- Immediate Feedback: Validate answers as soon as submitted
- Progressive Disclosure: Show hints incrementally, not all at once
- Mastery-Based: Don't rush through difficulty levels
- Variety: Mix problem types to maintain engagement
- Celebrate Success: Acknowledge milestones and improvements
- Error Analysis: Help students understand mistakes, not just mark them wrong
# High-level API for instructors/systems
class BinaryEducationSystem:
"""Main system interface"""
def __init__(self, config: SystemConfiguration):
self.config = config
self.truth_tables = TruthTableGenerator()
self.practice = ProblemGenerator()
self.progress_tracker = {} # student_id -> StudentProgress
# Truth Table Operations
def generate_truth_table(self, expression: str) -> TruthTable
def validate_truth_table(
self,
expression: str,
student_table: List[TruthTableRow]
) -> ValidationResult
# Practice Operations
def start_practice_session(
self,
student_id: str
) -> PracticeSession
def get_next_problem(
self,
student_id: str,
session_id: str
) -> Problem
def submit_answer(
self,
student_id: str,
problem_id: str,
answer: Any,
hints_used: int = 0
) -> AnswerResult
def get_hint(
self,
problem_id: str,
hint_level: int
) -> str
# Progress & Analytics
def get_student_progress(self, student_id: str) -> StudentProgress
def get_learning_analytics(self, time_period: str) -> LearningAnalytics
def get_recommendations(self, student_id: str) -> List[str]system = BinaryEducationSystem(SystemConfiguration())
# Generate truth table
expression = "(A AND B) OR NOT C"
table = system.generate_truth_table(expression)
print(table.to_text_table())
# Student submits their answer
student_table = [
# ... student's rows ...
]
result = system.validate_truth_table(expression, student_table)
print(f"Score: {result.get_score():.1f}%")
print(f"Feedback: {result.get_detailed_feedback()}")# Start session
session = system.start_practice_session(student_id="student123")
# Get problem
problem = system.get_next_problem("student123", session.session_id)
print(problem.question)
# Student needs hint
hint = system.get_hint(problem.id, hint_level=1)
print(f"Hint: {hint}")
# Submit answer
result = system.submit_answer(
student_id="student123",
problem_id=problem.id,
answer="1011",
hints_used=1
)
print(f"Correct: {result.is_correct}")
print(f"Feedback: {result.feedback}")# View progress
progress = system.get_student_progress("student123")
print(f"Overall Progress: {progress.get_overall_progress():.1f}%")
print(f"Efficiency Score: {progress.get_efficiency_score():.1f}")
# Get recommendations
recommendations = system.get_recommendations("student123")
for rec in recommendations:
print(f"- {rec}")This architecture provides a comprehensive foundation for building an educational system that:
- Teaches Binary Math: Through generated problems and interactive truth tables
- Adapts to Students: Via difficulty scoring and progression recommendations
- Provides Support: Through progressive hint system
- Tracks Progress: With detailed analytics and history
- Scales Complexity: From beginner single-bit operations to advanced multi-variable logic
The modular design allows for independent development and testing of components while ensuring seamless integration. The system focuses on educational effectiveness through immediate feedback, adaptive difficulty, and comprehensive progress tracking.
Next Steps:
- Review and approve architecture
- Set up development environment
- Begin Phase 1 implementation
- Create sample problems for testing
- Develop student-facing interface