├── Hospital_Tuple.py ├── Hospital_List.py ├── Hospital_Stack.py ├── Hospital_Set.py ├── Hospital_Queue.py ├── Hospital_Dict.py ├── Hosptal_Hash.py ├── README.md └── Hospital_hash.py /Hospital_Tuple.py: -------------------------------------------------------------------------------- 1 | #Immutable Hospital Layout -Fixed coordinates for critical stations 2 | # Emergency Exit Locations (Floor, X, Y) 3 | emergency_exits = ( 4 | ("Main Lobby", 1, 12.5), 5 | ("ER Back", 1, 87.3), 6 | ("ICU Wing", 3, 45.0) 7 | ) 8 | 9 | # Access data 10 | print("Exit near ICU:", emergency_exits[2][0]) # ICU Wing 11 | 12 | # Try to modify (will fail) 13 | try: 14 | emergency_exits[1] = ("Lab Zone", 2, 33.1) 15 | except TypeError as e: 16 | print("Security Alert! ", e) 17 | # Output: 'tuple' object does not support item assignment -------------------------------------------------------------------------------- /Hospital_List.py: -------------------------------------------------------------------------------- 1 | # Hospital Ward Management List - Ordered collections for patient beds 2 | # Ward 4A Patient Beds (Ordered by proximity to nurses' station) 3 | ward_4a = ["Bed1: Robert", "Bed2: Fatima", "Bed3: James"] 4 | 5 | # New admission 6 | ward_4a.append("Bed4: Aisha") 7 | print("Ward 4A:", ward_4a) 8 | # Output: ['Bed1: Robert', 'Bed2: Fatima', 'Bed3: James', 'Bed4: Aisha'] 9 | 10 | # Discharge patient 11 | discharged = ward_4a.pop(1) 12 | print(f"Discharged: {discharged} → Remaining: {ward_4a}") 13 | # Output: Discharged: Bed2: Fatima → Remaining: ['Bed1: Robert', 'Bed3: James', 'Bed4: Aisha'] -------------------------------------------------------------------------------- /Hospital_Stack.py: -------------------------------------------------------------------------------- 1 | #Medication Dispensing -Last-In-First-Out (LIFO) for efficient medicine access 2 | # Pharmacy Medication Stack 3 | medication_stack = [] 4 | 5 | # Stock medications (newest on top) 6 | medication_stack.append("Antibiotics") 7 | medication_stack.append("Painkillers") 8 | medication_stack.append("Insulin") 9 | 10 | print("Pharmacy Stock:", medication_stack) 11 | # Output: ['Antibiotics', 'Painkillers', 'Insulin'] 12 | 13 | # Dispense medications 14 | for _ in range(2): 15 | dispensed = medication_stack.pop() 16 | print(f"Dispensed: {dispensed} → Remaining: {medication_stack}") -------------------------------------------------------------------------------- /Hospital_Set.py: -------------------------------------------------------------------------------- 1 | #Equipment Tracking & Sterilization -Unique items for contamination control 2 | # Sterilized equipment sets 3 | sterile_lab_equipment = {"Microscope", "Centrifuge", "Pipettes"} 4 | sterile_er_equipment = {"Stethoscope", "Defibrillator", "Sutures"} 5 | 6 | # Contaminated items 7 | contaminated = {"Defibrillator", "Sutures", "Scalpel"} 8 | 9 | # Sterilize ER equipment 10 | sterile_er_equipment -= contaminated 11 | print("Sterile ER Equipment:", sterile_er_equipment) 12 | # Output: {'Stethoscope'} 13 | 14 | # Combine all sterile tools 15 | all_sterile = sterile_lab_equipment | sterile_er_equipment 16 | print("All Sterile Equipment:", all_sterile) 17 | # Output: {'Microscope', 'Centrifuge', 'Pipettes', 'Stethoscope'} -------------------------------------------------------------------------------- /Hospital_Queue.py: -------------------------------------------------------------------------------- 1 | #Patient Triage & Emergency Room Queue Management -First-In-First-Out (FIFO) for fair patient processing 2 | # Using deque for efficient queue operations 3 | from collections import deque 4 | 5 | # ER Patient Queue (Critical → Stable) 6 | er_queue = deque() 7 | 8 | # Patients arrive (critical cases jump queue) 9 | er_queue.append("Broken Arm") # Stable case 10 | er_queue.append("Severe Burn") # Critical case 11 | er_queue.appendleft("Heart Attack") # MOST critical 12 | 13 | print("ER Queue:", list(er_queue)) 14 | # Output: ['Heart Attack', 'Broken Arm', 'Severe Burn'] 15 | 16 | # Process patients 17 | while er_queue: 18 | current = er_queue.popleft() 19 | print(f"Treating: {current} → Remaining: {list(er_queue)}") -------------------------------------------------------------------------------- /Hospital_Dict.py: -------------------------------------------------------------------------------- 1 | #Staff & Patient Records -Key-value pairs for instant lookups 2 | # Staff Directory (ID → Details) 3 | staff = { 4 | 101: {"name": "Dr. Smith", "role": "Cardiologist", "station": "ER"}, 5 | 202: {"name": "Nurse Lee", "role": "ICU", "station": "Ward 3B"}, 6 | 303: {"name": "Dr. Patel", "role": "Radiologist", "station": "Lab 2"} 7 | } 8 | 9 | # Patient Records (ID → Medical History) 10 | patients = { 11 | "P881": {"name": "John Munae", "allergies": ["Penicillin"], "ward": "ICU"}, 12 | "P882": {"name": "Maria Garcia", "allergies": ["Smoke"], "ward": "Ward 4A"} 13 | } 14 | 15 | # Access data 16 | print("Cardiologist on duty:", staff[101]['name']) # Dr. Smith 17 | print("John's allergies:", patients["P881"]["allergies"]) # ['Penicillin'] 18 | 19 | # Add new patient 20 | patients["P883"] = {"name": "Alex Kim", "allergies": ["Latex"], "ward": "ER"} -------------------------------------------------------------------------------- /Hosptal_Hash.py: -------------------------------------------------------------------------------- 1 | #Enhanced Doctor Login System 2 | import hashlib 3 | import os 4 | import binascii 5 | 6 | # Doctor Database (Hash Map: Username → Security Data) 7 | doctors_db = { 8 | # Format: {username: {"hash": "...", "salt": "...", "name": "...", "access": ["records", "labs"]}} 9 | "dr_grey": { 10 | "hash": "e9a2...", # Will generate below 11 | "salt": "b6f3...", # Will generate below 12 | "name": "Meredith Grey", 13 | "access": ["patient_records", "surgery_schedule"] 14 | } 15 | } 16 | 17 | # Generate secure credentials for Dr. Grey 18 | password = "SeattleGrace1!".encode() 19 | salt = os.urandom(16) # Random 16-byte salt 20 | dk = hashlib.pbkdf2_hmac('sha256', password, salt, 100000) # Key stretching 21 | 22 | # Update database 23 | doctors_db["dr_grey"]["salt"] = binascii.hexlify(salt).decode() 24 | doctors_db["dr_grey"]["hash"] = binascii.hexlify(dk).decode() 25 | 26 | def authenticate_doctor(username: str, password: str) -> bool: 27 | """Verify doctor credentials using PBKDF2-HMAC-SHA256""" 28 | if username not in doctors_db: 29 | return False 30 | 31 | # Retrieve stored security data 32 | stored_salt = binascii.unhexlify(doctors_db[username]["salt"].encode()) 33 | stored_hash = doctors_db[username]["hash"] 34 | 35 | # Hash the attempt with stored salt 36 | attempt_dk = hashlib.pbkdf2_hmac( 37 | 'sha256', 38 | password.encode(), 39 | stored_salt, 40 | 100000 41 | ) 42 | 43 | # Constant-time comparison to prevent timing attacks 44 | return binascii.hexlify(attempt_dk).decode() == stored_hash 45 | 46 | def doctor_login(): 47 | """Hospital login interface""" 48 | print("🏥 MEDICAL PORTAL AUTHENTICATION") 49 | username = input("Username: ").strip() 50 | password = input("Password: ").strip() 51 | 52 | if authenticate_doctor(username, password): 53 | doctor = doctors_db[username] 54 | print(f"\n🔓 ACCESS GRANTED: Welcome Dr. {doctor['name']}") 55 | print(f"🩺 Privileges: {', '.join(doctor['access'])}") 56 | return True 57 | else: 58 | print("\n❌ ACCESS DENIED: Invalid credentials") 59 | return False 60 | 61 | # Simulate login attempt 62 | if __name__ == "__main__": 63 | doctor_login() -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### Comprehensive Guide: Python Data Structures in Hospital Management 🏥🐍 2 | 3 | ```markdown 4 | Python Data Structures for Hospital Management Systems 5 | 6 | This guide explores Python data structures through hospital management analogies, making complex concepts intuitive and practical. All code uses **Python 3.13** with zero external dependencies. 7 | 8 | --- 9 | 10 | ### Key Workflows 11 | 1. **Patient Admission**: `admit_patient("John Doe", "Fracture", priority=True)` 12 | 2. **ER Processing**: `next_patient = er_queue.popleft()` 13 | 3. **Medication Dispensing**: `med = medication_stack.pop()` 14 | 4. **Doctor Login**: `verify_password(stored_hash, salt, attempt)` 15 | 5. **Equipment Sterilization**: `sterile_tools -= contaminated_tools` 16 | 17 | --- 18 | 19 | ## 🏃 Running the System 20 | 21 | 1. Clone the repository: 22 | ```bash 23 | git clone https://github.com/chankjen/Python_Data_Structures.git 24 | cd hospital-ds 25 | ``` 26 | 27 | 2. Run the demo simulation: 28 | ```bash 29 | python hospital_system.py 30 | ``` 31 | 32 | 3. Sample test credentials: 33 | ``` 34 | Username: dr_grey 35 | Password: SeattleGrace1! # Pre-registered in demo 36 | ``` 37 | 38 | --- 39 | 40 | ## 🔒 Security Best Practices 41 | 42 | 1. **Password Storage** 43 | - Always use PBKDF2, bcrypt or scrypt 44 | - Never store plaintext passwords 45 | - Minimum 100,000 iterations for PBKDF2 46 | 47 | 2. **Data Protection** 48 | ```python 49 | # Sensitive data handling 50 | from cryptography.fernet import Fernet 51 | 52 | key = Fernet.generate_key() 53 | cipher = Fernet(key) 54 | encrypted_data = cipher.encrypt(b"Sensitive patient info") 55 | ``` 56 | 57 | 3. **Access Control** 58 | - Implement role-based access control (RBAC) 59 | - Use decorators for permission checks: 60 | ```python 61 | def requires_access(permission): 62 | def decorator(func): 63 | def wrapper(*args, **kwargs): 64 | if permission not in current_user.access: 65 | raise PermissionError("Access denied") 66 | return func(*args, **kwargs) 67 | return wrapper 68 | return decorator 69 | 70 | @requires_access("patient_records") 71 | def view_medical_history(patient_id): 72 | # ... function logic 73 | ``` 74 | 75 | --- 76 | 77 | ## Data Structure Selection Guide 78 | | Scenario | Recommended Structure | Hospital Use Case | 79 | |----------|------------------------|-------------------| 80 | | First-In-First-Out | `deque` | Patient triage | 81 | | Last-In-First-Out | `list` as stack | Medication dispensing | 82 | | Key-Value Lookups | `dict` | Patient records | 83 | | Unique Items | `set` | Sterile equipment | 84 | | Immutable Data | `tuple` | Hospital coordinates | 85 | | Ordered Collection | `list` | Ward bed assignments | 86 | 87 | --- 88 | > "Good data structures are like well-organized hospital wards - they save lives (and runtime)!" 🐍💉 89 | ``` 90 | -------------------------------------------------------------------------------- /Hospital_hash.py: -------------------------------------------------------------------------------- 1 | # Doctor Authentication System 2 | import hashlib 3 | 4 | # Database of Doctors (Hash Map: Username → Hashed Password + Details) 5 | doctors_db = { 6 | # Format: {username: {"password_hash": "...", "name": "...", "department": "..."}} 7 | "dr_strange": { 8 | "password_hash": hashlib.sha256("Spell@2024".encode()).hexdigest(), 9 | "name": "Stephen Strange", 10 | "department": "Neurosurgery" 11 | }, 12 | "dr_house": { 13 | "password_hash": hashlib.sha256("Lupus!123".encode()).hexdigest(), 14 | "name": "Gregory House", 15 | "department": "Diagnostics" 16 | } 17 | } 18 | 19 | # Patient Records (Secured behind authentication) 20 | patient_records = { 21 | "ICU-101": {"name": "Tony Stark", "condition": "Shrapnel injury"}, 22 | "ER-205": {"name": "Bruce Banner", "condition": "Gamma radiation exposure"} 23 | } 24 | 25 | def register_doctor(username: str, password: str, name: str, department: str): 26 | """Add new doctor with hashed password""" 27 | if username in doctors_db: 28 | print("⚠️ Username already exists!") 29 | return False 30 | 31 | # Create password hash (add salt in real systems!) 32 | password_hash = hashlib.sha256(password.encode()).hexdigest() 33 | doctors_db[username] = { 34 | "password_hash": password_hash, 35 | "name": name, 36 | "department": department 37 | } 38 | print(f"✅ {name} registered in {department}!") 39 | return True 40 | 41 | def doctor_login(username: str, password: str): 42 | """Authenticate doctor using hash comparison""" 43 | if username not in doctors_db: 44 | print("❌ User not found") 45 | return False 46 | 47 | # Hash the attempt 48 | attempt_hash = hashlib.sha256(password.encode()).hexdigest() 49 | stored_hash = doctors_db[username]["password_hash"] 50 | 51 | if attempt_hash == stored_hash: 52 | print(f"🔓 Access granted! Welcome Dr. {doctors_db[username]['name']}") 53 | return True 54 | else: 55 | print("❌ Invalid password") 56 | return False 57 | 58 | def access_patient_record(username: str, patient_id: str): 59 | """Securely access patient data after auth""" 60 | if doctor_login(username, input("Password: ")): 61 | record = patient_records.get(patient_id) 62 | if record: 63 | print(f"\n📝 Patient {patient_id}:") 64 | for key, value in record.items(): 65 | print(f" {key.capitalize()}: {value}") 66 | else: 67 | print("⚠️ Record not found") 68 | else: 69 | print("🚫 Access denied to patient records") 70 | 71 | # Demo Workflow 72 | if __name__ == "__main__": 73 | # Register new doctor 74 | register_doctor( 75 | username="dr_grey", 76 | password="Heal$oul123", 77 | name="Meredith Grey", 78 | department="General Surgery" 79 | ) 80 | 81 | # Attempt login 82 | print("\n[ Login Attempt ]") 83 | doctor_login("dr_strange", "Spell@2024") # Correct → Success 84 | doctor_login("dr_house", "wrong!pass") # Incorrect → Failure 85 | 86 | # Access patient data (simulate) 87 | print("\n[ Access Patient Record ]") 88 | access_patient_record("dr_strange", "ICU-101") --------------------------------------------------------------------------------