Skip to content

Database Operations Using Set Theory

CS 5001/5002 - Strings, Sequences & Sets

Code

#!/usr/bin/env python3
"""
Filename: database_operations.py
Description: Database Operations Using Set Theory
CS 5001/5002 - Strings, Sequences & Sets

This script simulates database operations using sets to demonstrate
practical applications of set theory in data management.
"""

def database_operations():
    """Simulate database operations using sets"""

    # Employee database simulation
    employees = {
        "engineering": {"Alice", "Bob", "Charlie", "Diana"},
        "marketing": {"Eve", "Frank", "Alice", "Grace"},
        "sales": {"Bob", "Grace", "Henry", "Iris"},
        "management": {"Alice", "Frank", "Henry"}
    }

    print("Employee Database:")
    for dept, people in employees.items():
        print(f"  {dept}: {people}")
    print()

    # Query 1: Who works in multiple departments?
    all_employees = set()
    for dept_employees in employees.values():
        all_employees |= dept_employees

    multi_dept = set()
    for employee in all_employees:
        dept_count = sum(1 for dept_employees in employees.values() 
                        if employee in dept_employees)
        if dept_count > 1:
            multi_dept.add(employee)

    print(f"Employees in multiple departments: {multi_dept}")

    # Query 2: Engineering OR Marketing (union)
    eng_or_marketing = employees["engineering"] | employees["marketing"]
    print(f"Engineering OR Marketing: {eng_or_marketing}")

    # Query 3: Engineering AND Marketing (intersection)
    eng_and_marketing = employees["engineering"] & employees["marketing"]
    print(f"Engineering AND Marketing: {eng_and_marketing}")

    # Query 4: In Engineering but NOT in Management
    eng_not_mgmt = employees["engineering"] - employees["management"]
    print(f"Engineering but not Management: {eng_not_mgmt}")

    # Query 5: Department-specific analysis
    print(f"\nDepartment sizes:")
    for dept, people in employees.items():
        print(f"  {dept}: {len(people)} employees")

    # Query 6: Find employees unique to each department
    print(f"\nEmployees unique to each department:")
    for dept, people in employees.items():
        others = set()
        for other_dept, other_people in employees.items():
            if other_dept != dept:
                others |= other_people
        unique_to_dept = people - others
        print(f"  {dept} only: {unique_to_dept}")

def main():
    database_operations()

if __name__ == "__main__":
    main()

How to Use

  1. Copy the code above
  2. Save it as a .py file (e.g., database_operations.py)
  3. Run it with: python database_operations.py

Part of CS 5001/5002 - Strings, Sequences & Sets materials