help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
python-pattern-generator
RSK World
python-pattern-generator
Python Number Pattern Generator - 22 Pattern Types + Fractals + Mathematical Algorithms + GUI & Web Interface + REST API + Educational Design
python-pattern-generator
  • __pycache__
  • static
  • templates
  • .gitignore1.6 KB
  • README.md9.7 KB
  • animation.py14.3 KB
  • api.py19.9 KB
  • config.py14 KB
  • demo.py9.3 KB
  • index.html10.1 KB
  • main.py30.9 KB
  • pattern_comparison.py15.4 KB
  • patterns.py23 KB
  • push_to_github.bat3.9 KB
  • requirements.txt1 KB
  • svg_export.py13.4 KB
  • test_gui.py2.2 KB
  • test_patterns.py13.7 KB
  • web_app.py13.6 KB
README.md.gitignoreconfig.py
README.md
Raw Download

README.md

# Python Number Pattern Generator 🔢

**Author:** Molla Samser (Founder, RSK World)
**Designer & Tester:** Rima Khatun
**Website:** https://rskworld.in
**Email:** hello@rskworld.in, support@rskworld.in
**Phone:** +91 93305 39277
**Address:** Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India - 713147
**Year:** 2026

## 📖 Description

A comprehensive number pattern generator using Python with an intuitive GUI interface. This application allows users to create various mathematical patterns, sequences, and geometric shapes using numbers. Perfect for learning Python loops, conditional statements, and algorithmic thinking.

## ✨ Features

- **22 Pattern Types:** Choose from 22 different patterns including fractals, cellular automata, and advanced mathematical patterns
- **Advanced Algorithms:** Sierpinski triangles, Mandelbrot sets, Hilbert curves, Dragon curves, Koch snowflakes
- **Web Interface:** Full Flask web application with modern UI and API endpoints
- **Multiple Export Formats:** Text, JSON, PNG images, and SVG vector graphics
- **Animation System:** Step-by-step pattern generation animations
- **Comprehensive API:** REST API for programmatic pattern generation
- **Pattern Comparison:** Advanced diff tools and similarity analysis
- **Configuration System:** Customizable settings and themes
- **Unit Testing:** Complete test suite with performance benchmarks
- **Theme Support:** Multiple themes (Default, Dark, Light, Color) with syntax highlighting
- **Real-time Features:** Live search, analysis, and validation

## 🎯 Pattern Types (22 Total)

### Basic Patterns
1. **Pyramid Pattern** - Classic pyramid shape with numbers
2. **Reverse Pyramid** - Inverted pyramid pattern
3. **Number Triangle** - Right-angled triangle with numbers
4. **Number Square** - Grid pattern with sequential numbers
5. **Diamond Pattern** - Diamond shape with numbers
6. **Hourglass Pattern** - Hourglass shape using numbers

### Mathematical Patterns
7. **Pascal's Triangle** - Binomial coefficients triangle
8. **Floyd's Triangle** - Sequential numbers in triangular arrangement
9. **Fibonacci Triangle** - Fibonacci sequence triangle
10. **Multiplication Table** - Math multiplication table
11. **Magic Square** - Mathematical magic square (odd sizes only)
12. **Prime Numbers** - Grid displaying prime numbers
13. **Number Spiral** - Spiral arrangement of numbers

### Advanced/Fractal Patterns
14. **Sierpinski Triangle** - Fractal triangle pattern
15. **Mandelbrot Set** - Mandelbrot set visualization
16. **Hilbert Curve** - Space-filling Hilbert curve
17. **Dragon Curve** - Dragon curve fractal
18. **Koch Snowflake** - Koch snowflake fractal
19. **Cellular Automaton** - Wolfram cellular automaton
20. **Binary Tree** - Binary tree visualization

### Special Features
- ⭐ **Animation Support**: Step-by-step generation for most patterns
- 🎨 **Syntax Highlighting**: Color-coded numbers and symbols in exports
- 📊 **Advanced Analysis**: Complexity metrics and pattern statistics

## 🚀 Getting Started

### Prerequisites

- Python 3.6 or higher
- Tkinter (usually comes pre-installed with Python)

### Installation

1. Clone or download the project
2. Navigate to the project directory
3. Run the main application:

```bash
python main.py
```

### Usage

#### Desktop Application
```bash
python main.py
```

#### Web Interface
```bash
python web_app.py
# Visit http://localhost:5000
```

#### Command-line Demo
```bash
python demo.py
```

#### API Usage
```python
from api import generate_pattern
pattern = generate_pattern('pyramid', 5, 1)
```

### Interfaces

#### 1. Desktop GUI (`main.py`)
- **22 Pattern Types** with real-time search and filtering
- **Advanced Analysis** with detailed statistics and complexity metrics
- **Multiple Export Formats** (Text, PNG, JSON)
- **Theme Support** (Default, Dark, Light, Color)
- **Animation System** for step-by-step pattern generation
- **Pattern Comparison** tools with diff visualization

#### 2. Web Application (`web_app.py`)
- **Modern Bootstrap UI** with responsive design
- **REST API** endpoints for programmatic access
- **Real-time Generation** with AJAX
- **Interactive Features** (search, analysis, export)
- **API Documentation** accessible via web interface

#### 3. Command-line Tools
- **Demo Interface** (`demo.py`) - Interactive pattern exploration
- **API Client** (`api.py`) - Programmatic pattern generation
- **Test Suite** (`test_patterns.py`) - Comprehensive testing
- **Configuration** (`config.py`) - Settings management

### Advanced Features

#### Analysis & Comparison
- **Detailed Statistics**: Lines, characters, numbers, complexity metrics
- **Pattern Comparison**: Side-by-side diff and similarity scoring
- **Performance Benchmarking**: Speed tests across pattern types
- **Complexity Analysis**: Mathematical complexity evaluation

#### Export & Visualization
- **Multiple Formats**: Text, JSON, PNG, SVG, PDF (planned)
- **Animated SVG**: Step-by-step pattern evolution
- **Syntax Highlighting**: Color-coded exports with themes
- **Batch Export**: Multiple patterns at once

#### Animation & Interactivity
- **Step-by-step Animation**: Watch patterns build incrementally
- **Interactive Controls**: Real-time parameter adjustment
- **Progress Tracking**: Visual feedback during generation
- **Speed Control**: Adjustable animation timing

#### API & Integration
- **RESTful API**: Full programmatic access
- **Batch Processing**: Generate multiple patterns
- **Error Handling**: Comprehensive validation and error reporting
- **Metadata Support**: Rich pattern information and statistics

## 📸 Screenshots

The application features a clean, modern interface with:
- Header with project information
- Left panel for controls and pattern selection
- Right panel for pattern output display
- Status bar for user feedback

## 🛠️ Technical Details

### Dependencies

- **tkinter:** GUI framework (built-in with Python)
- **datetime:** For timestamp generation
- **os:** For file operations
- **typing:** For type hints (built-in with Python 3.5+)
- **math:** For mathematical calculations (built-in with Python)
- **pillow (optional):** For PNG image export (`pip install pillow`)

### Project Structure

```
python-pattern-generator/
├── main.py # Desktop GUI application
├── patterns.py # Pattern generation algorithms
├── demo.py # Command-line demo interface
├── web_app.py # Flask web application
├── api.py # REST API for programmatic access
├── animation.py # Pattern animation system
├── svg_export.py # SVG/PDF export functionality
├── pattern_comparison.py # Pattern comparison and analysis tools
├── config.py # Configuration management
├── test_patterns.py # Comprehensive unit tests
├── index.html # Static web interface
├── README.md # Project documentation
├── requirements.txt # Python dependencies
├── templates/ # Flask HTML templates
│ └── index.html
└── static/ # Static web assets
├── css/
│ └── style.css
└── js/
└── app.js
```

### Code Architecture

- **PatternGenerator Class:** Main application class
- **Pattern Methods:** Individual methods for each pattern type
- **GUI Components:** Tkinter widgets for user interface
- **Export Functionality:** File saving capabilities

## 🎓 Educational Value

This project is excellent for learning:

- **Python Loops:** For loops, while loops, nested loops
- **Conditional Statements:** If-else logic for pattern generation
- **Algorithmic Thinking:** Problem-solving and pattern recognition
- **GUI Development:** Tkinter interface design
- **File Operations:** Reading and writing files
- **Mathematical Concepts:** Prime numbers, Pascal's triangle, etc.

## 🔧 Customization

You can easily add new patterns by:

1. Adding a new pattern method to the `PatternGenerator` class
2. Updating the pattern selection list in `setup_ui()`
3. Adding the pattern to the `generate_pattern()` method

Example of adding a new pattern:

```python
def generate_custom_pattern(self, size, start_num):
"""Generate custom pattern"""
pattern = []
# Your pattern logic here
return "\n".join(pattern)
```

## 📝 Examples

### Pyramid Pattern (Size: 5, Start: 1)
```
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
```

### Floyd's Triangle (Size: 4)
```
1 2 3
4 5 6
7 8 9
10 11 12
```

### Number Spiral (Size: 3)
```
1 2 3
8 9 4
7 6 5
```

## 🤝 Contributing

Contributions are welcome! Please feel free to submit issues, enhancement requests, or pull requests.

## 📄 License

This project is part of RSK World's educational resources. Content is used for educational purposes only.

## 📞 Contact

- **Website:** https://rskworld.in
- **Email:** hello@rskworld.in, support@rskworld.in
- **Phone:** +91 93305 39277
- **Address:** Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India - 713147

## 🌐 About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

### Development Categories
- Game Development
- Web Development
- Mobile Development
- Software Development
- Development Tools

---

**© 2026 RSK World. All rights reserved.**
*Developed with ❤️ for educational purposes*
.gitignore
Raw Download
Find: Go to:
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# IDE
.vscode/
.idea/
*.swp
*.swo
*~

# OS
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db

# Temporary files
*.tmp
*.temp
*.bak

# Log files
logs/
*.log

# Screenshots and exports
exports/
screenshots/

# Virtual environments
venv/
env/

# Database files
*.db
*.sqlite
*.sqlite3

# Configuration files that may contain sensitive data
config.json
settings.json
146 lines•1.6 KB
text
config.py
Raw Download
Find: Go to:
"""
Configuration Module for Python Number Pattern Generator
Author: Molla Samser (Founder, RSK World)
Designer & Tester: Rima Khatun
Website: https://rskworld.in
Year: 2026
Description: Centralized configuration management
"""

import json
import os
from typing import Dict, Any, Optional


class Config:
    """Configuration manager for the pattern generator"""

    # Default configuration
    DEFAULT_CONFIG = {
        # Application settings
        "app": {
            "name": "Python Number Pattern Generator",
            "version": "2.0",
            "author": "Molla Samser (RSK World)",
            "designer": "Rima Khatun",
            "website": "https://rskworld.in",
            "year": 2026,
            "description": "Comprehensive number pattern generator with GUI and web interface"
        },

        # GUI settings
        "gui": {
            "window": {
                "width": 800,
                "height": 600,
                "min_width": 600,
                "min_height": 400,
                "title": "Python Number Pattern Generator - RSK World"
            },
            "theme": {
                "default": "default",
                "available_themes": ["default", "dark", "light"],
                "auto_save_theme": True
            },
            "fonts": {
                "family": "Arial",
                "size": {
                    "title": 16,
                    "normal": 10,
                    "small": 8
                }
            },
            "colors": {
                "primary": "#3498db",
                "success": "#27ae60",
                "warning": "#f39c12",
                "danger": "#e74c3c",
                "info": "#17a2b8"
            }
        },

        # Web interface settings
        "web": {
            "host": "0.0.0.0",
            "port": 5000,
            "debug": True,
            "secret_key": "rsk-world-pattern-generator-2026",
            "max_content_length": 16 * 1024 * 1024,  # 16MB
            "session_timeout": 3600,  # 1 hour
            "rate_limit": {
                "enabled": False,
                "requests_per_minute": 60
            }
        },

        # Pattern settings
        "patterns": {
            "max_size": {
                "basic": 50,
                "advanced": 20,
                "fractal": 10
            },
            "max_start_number": 1000,
            "min_size": 1,
            "default_size": 5,
            "default_start_number": 1,
            "computation_timeout": 30,  # seconds
            "cache_enabled": True,
            "cache_max_size": 100
        },

        # Export settings
        "export": {
            "formats": {
                "text": {
                    "enabled": True,
                    "extension": ".txt",
                    "encoding": "utf-8"
                },
                "json": {
                    "enabled": True,
                    "extension": ".json",
                    "indent": 2
                },
                "png": {
                    "enabled": True,
                    "extension": ".png",
                    "font_size": 20,
                    "background_color": "#000000",
                    "text_color": "#00FF00",
                    "padding": 20
                },
                "svg": {
                    "enabled": False,  # Not implemented yet
                    "extension": ".svg"
                },
                "pdf": {
                    "enabled": False,  # Not implemented yet
                    "extension": ".pdf"
                }
            },
            "default_format": "text",
            "include_metadata": True,
            "timestamp_format": "%Y-%m-%d %H:%M:%S",
            "auto_open_after_export": False
        },

        # Analysis settings
        "analysis": {
            "enabled": True,
            "calculate_statistics": True,
            "performance_monitoring": True,
            "memory_tracking": False,
            "detailed_analysis": {
                "number_distribution": True,
                "pattern_complexity": True,
                "mathematical_properties": True
            }
        },

        # Logging settings
        "logging": {
            "enabled": True,
            "level": "INFO",  # DEBUG, INFO, WARNING, ERROR
            "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
            "file": {
                "enabled": True,
                "path": "logs/pattern_generator.log",
                "max_size": 10 * 1024 * 1024,  # 10MB
                "backup_count": 5
            },
            "console": {
                "enabled": True,
                "colored": True
            }
        },

        # Performance settings
        "performance": {
            "max_workers": 4,
            "thread_pool_size": 8,
            "cache_ttl": 3600,  # 1 hour
            "optimization": {
                "string_concatenation": True,
                "memory_pool": True,
                "lazy_evaluation": False
            }
        },

        # Security settings
        "security": {
            "input_validation": {
                "strict_mode": True,
                "sanitize_input": True,
                "max_input_size": 10000
            },
            "rate_limiting": {
                "enabled": False,
                "window_seconds": 60,
                "max_requests": 100
            },
            "cors": {
                "enabled": True,
                "origins": ["*"],
                "methods": ["GET", "POST"],
                "headers": ["Content-Type", "Authorization"]
            }
        },

        # Feature flags
        "features": {
            "gui": True,
            "web_interface": True,
            "api": True,
            "export": True,
            "analysis": True,
            "animation": False,  # Not implemented yet
            "comparison": False,  # Not implemented yet
            "plugins": False,     # Not implemented yet
            "themes": True,
            "search": True,
            "statistics": True
        },

        # External integrations
        "integrations": {
            "matplotlib": {
                "enabled": False,
                "backend": "Agg"
            },
            "pillow": {
                "enabled": True,
                "max_image_size": 4096
            },
            "flask": {
                "enabled": True,
                "cors_enabled": True
            }
        },

        # User preferences
        "user": {
            "last_used_pattern": "pyramid",
            "last_size": 5,
            "last_start_number": 1,
            "favorite_patterns": [],
            "recent_patterns": [],
            "auto_save_settings": True,
            "language": "en",
            "timezone": "UTC"
        }
    }

    def __init__(self, config_file: str = "config.json"):
        """Initialize configuration manager

        Args:
            config_file: Path to the configuration file
        """
        self.config_file = config_file
        self._config = self.DEFAULT_CONFIG.copy()
        self.load_config()

    def load_config(self) -> None:
        """Load configuration from file"""
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    user_config = json.load(f)
                    self._merge_config(self._config, user_config)
                print(f"✅ Configuration loaded from {self.config_file}")
            else:
                print(f"⚠️  Configuration file not found, using defaults")
                self.save_config()  # Create default config file
        except Exception as e:
            print(f"❌ Error loading configuration: {e}")
            print("Using default configuration")

    def save_config(self) -> None:
        """Save current configuration to file"""
        try:
            # Ensure directory exists
            os.makedirs(os.path.dirname(self.config_file), exist_ok=True)

            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self._config, f, indent=2, ensure_ascii=False)

            print(f"💾 Configuration saved to {self.config_file}")
        except Exception as e:
            print(f"❌ Error saving configuration: {e}")

    def _merge_config(self, base: Dict[str, Any], update: Dict[str, Any]) -> None:
        """Recursively merge configuration dictionaries"""
        for key, value in update.items():
            if key in base and isinstance(base[key], dict) and isinstance(value, dict):
                self._merge_config(base[key], value)
            else:
                base[key] = value

    def get(self, key: str, default: Any = None) -> Any:
        """Get configuration value by key

        Args:
            key: Dot-separated key (e.g., 'gui.window.width')
            default: Default value if key not found

        Returns:
            Configuration value or default
        """
        keys = key.split('.')
        value = self._config

        try:
            for k in keys:
                value = value[k]
            return value
        except (KeyError, TypeError):
            return default

    def set(self, key: str, value: Any) -> None:
        """Set configuration value by key

        Args:
            key: Dot-separated key (e.g., 'gui.window.width')
            value: Value to set
        """
        keys = key.split('.')
        config = self._config

        # Navigate to the parent dictionary
        for k in keys[:-1]:
            if k not in config:
                config[k] = {}
            config = config[k]

        # Set the value
        config[keys[-1]] = value

        # Auto-save if enabled
        if self.get('user.auto_save_settings', True):
            self.save_config()

    def reset_to_defaults(self) -> None:
        """Reset configuration to default values"""
        self._config = self.DEFAULT_CONFIG.copy()
        self.save_config()

    def validate_config(self) -> Dict[str, Any]:
        """Validate current configuration

        Returns:
            Dictionary with validation results
        """
        issues = []

        # Check required settings
        required_keys = [
            'app.name',
            'patterns.max_size.basic',
            'patterns.min_size'
        ]

        for key in required_keys:
            if self.get(key) is None:
                issues.append(f"Missing required key: {key}")

        # Check value ranges
        if not (1 <= self.get('patterns.min_size', 0) <= self.get('patterns.max_size.basic', 100)):
            issues.append("Invalid size range")

        if self.get('patterns.max_start_number', 0) < 0:
            issues.append("Invalid max start number")

        return {
            'valid': len(issues) == 0,
            'issues': issues
        }

    def get_all(self) -> Dict[str, Any]:
        """Get entire configuration dictionary"""
        return self._config.copy()

    def print_config(self, section: Optional[str] = None) -> None:
        """Print configuration (optionally for specific section)"""
        if section:
            config_section = self.get(section, {})
            print(f"\n=== {section.upper()} Configuration ===")
            print(json.dumps(config_section, indent=2))
        else:
            print("\n=== Full Configuration ===")
            print(json.dumps(self._config, indent=2))

    # Convenience methods for common settings
    @property
    def app_name(self) -> str:
        return self.get('app.name', 'Pattern Generator')

    @property
    def app_version(self) -> str:
        return self.get('app.version', '1.0')

    @property
    def max_pattern_size(self) -> int:
        return self.get('patterns.max_size.basic', 50)

    @property
    def min_pattern_size(self) -> int:
        return self.get('patterns.min_size', 1)

    @property
    def max_start_number(self) -> int:
        return self.get('patterns.max_start_number', 1000)

    @property
    def default_theme(self) -> str:
        return self.get('gui.theme.default', 'default')

    @property
    def web_host(self) -> str:
        return self.get('web.host', 'localhost')

    @property
    def web_port(self) -> int:
        return self.get('web.port', 5000)


# Global configuration instance
config = Config()

# Convenience functions
def get_config(key: str, default: Any = None) -> Any:
    """Get configuration value"""
    return config.get(key, default)

def set_config(key: str, value: Any) -> None:
    """Set configuration value"""
    config.set(key, value)

def save_config() -> None:
    """Save configuration to file"""
    config.save_config()

def load_config() -> None:
    """Load configuration from file"""
    config.load_config()

if __name__ == '__main__':
    print("Python Number Pattern Generator - Configuration Manager")
    print("=" * 60)
    print("Developed by Molla Samser (RSK World)")
    print("Designed by Rima Khatun")
    print("Website: https://rskworld.in")
    print("Year: 2026")
    print("=" * 60)

    # Example usage
    print(f"App Name: {config.app_name}")
    print(f"Version: {config.app_version}")
    print(f"Max Pattern Size: {config.max_pattern_size}")
    print(f"Default Theme: {config.default_theme}")

    # Modify some settings
    config.set('user.last_used_pattern', 'sierpinski')
    config.set('user.last_size', 8)

    # Validate configuration
    validation = config.validate_config()
    if validation['valid']:
        print("✅ Configuration is valid")
    else:
        print("❌ Configuration issues:")
        for issue in validation['issues']:
            print(f"  - {issue}")

    # Save configuration
    config.save_config()
    print("\nConfiguration saved to config.json")
457 lines•14 KB
python

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer