Skip to the content.

Team Teach HW

  • Computing Bias
  • Crowdsourcing
  • Legal / Ethical Concerns
  • Safe Computing
  • Binary Search
  • List Filter
  • Big O and Algorithmic Complexity
  • Undecidable Problems, Graphs, Heuristics
  • Binary Base 2 Math
  • Color Code
  • Digital Divide

    Code Running

    %%js
    function exploreDigitalDivide() {
      // Select what data to display
      const metric = prompt(
        "Which digital divide metric would you like to explore?\n" +
        "1: Income-based internet access\n" +
        "2: Urban vs rural access\n" +
        "3: Age-based internet usage\n" +
        "4: Global connectivity rates"
      );
    
      // Sample data
      const incomeData = {
        categories: ["Lowest 20%", "Second 20%", "Middle 20%", "Fourth 20%", "Highest 20%"],
        values: [62, 71, 80, 88, 95]
      };
    
      const locationData = {
        categories: ["Urban", "Rural"],
        values: [94, 83]
      };
    
      const ageData = {
        categories: ["18-29", "30-49", "50-64", "65+"],
        values: [97, 93, 88, 61]
      };
    
      const globalData = {
        categories: ["North America", "Europe", "Asia Pacific", "Latin America", "Middle East/Africa"],
        values: [90, 87, 54, 68, 40]
      };
    
      // Select dataset based on user choice
      let data;
      let title;
    
      switch(metric) {
        case "1":
          data = incomeData;
          title = "Internet Access by Income Level (%)";
          break;
        case "2":
          data = locationData;
          title = "Urban vs Rural Internet Access (%)";
          break;
        case "3":
          data = ageData;
          title = "Internet Usage by Age Group (%)";
          break;
        case "4":
          data = globalData;
          title = "Internet Access by Region (%)";
          break;
        default:
          alert("Invalid selection!");
          return;
      }
    
      // Display the data (in a real app, this would create a chart)
      console.log(title);
      console.log("=".repeat(title.length));
    
      const maxValue = Math.max(...data.values);
      const maxBarLength = 40;
    
      for (let i = 0; i < data.categories.length; i++) {
        const barLength = Math.round((data.values[i] / maxValue) * maxBarLength);
        const bar = "█".repeat(barLength);
        console.log(`${data.categories[i].padEnd(12)}: ${bar} ${data.values[i]}%`);
      }
    }
    
    // Run this function to explore different aspects of the digital divide
    // exploreDigitalDivide();
    
      Cell In[2], line 1
        function exploreDigitalDivide() {
                 ^
    SyntaxError: invalid syntax
    
    %%js
    function bridgeTheDivideGame() {
      console.log("===============================================");
      console.log("🌉 BRIDGE THE DIVIDE: Digital Inclusion Challenge");
      console.log("===============================================");
      console.log("You are a technology policy advisor tasked with");
      console.log("helping communities overcome the digital divide.");
      console.log("Analyze each scenario and make the best decision!\n");
    
      let score = 0;
      const totalQuestions = 5;
    
      // Scenario 1
      console.log("SCENARIO 1: Rural Connectivity");
      console.log("A rural community of 500 families is located 50 miles from");
      console.log("the nearest broadband infrastructure. You have $200,000");
      console.log("in funding. What's your best approach?");
      console.log("A: Lay fiber optic cable to each home");
      console.log("B: Set up a wireless tower system");
      console.log("C: Provide satellite internet subsidies");
      console.log("D: Create a community center with high-speed internet");
    
      const answer1 = prompt("Your choice (A/B/C/D):").toUpperCase();
      if (answer1 === "B") {
        console.log("✓ Correct! A wireless tower system provides the best");
        console.log("  coverage for the investment in this rural setting.");
        score++;
      } else {
        console.log("✗ The best answer is B. Fiber would be too expensive,");
        console.log("  satellite has high latency issues, and a single center");
        console.log("  wouldn't provide sufficient access for all families.");
      }
    
      // Scenario 2
      console.log("\nSCENARIO 2: Digital Literacy");
      console.log("An urban neighborhood has new affordable internet access,");
      console.log("but adoption remains low at 30%. Investigation reveals many");
      console.log("residents lack digital skills. What approach would help most?");
      console.log("A: Reduce internet prices further");
      console.log("B: Distribute free tablets to all residents");
      console.log("C: Launch digital literacy workshops at local library");
      console.log("D: Create a tech support hotline");
    
      const answer2 = prompt("Your choice (A/B/C/D):").toUpperCase();
      if (answer2 === "C") {
        console.log("✓ Correct! Digital literacy workshops address the");
        console.log("  root cause - lack of skills - rather than just");
        console.log("  providing more access or support.");
        score++;
      } else {
        console.log("✗ The best answer is C. The primary barrier isn't");
        console.log("  cost or device ownership, but skill development.");
        console.log("  Workshops provide hands-on learning opportunities.");
      }
    
      // Add more scenarios as needed...
    
      // Final score
      console.log("\n===============================================");
      console.log(`FINAL SCORE: ${score}/${totalQuestions}`);
      console.log("===============================================");
    
      if (score === totalQuestions) {
        console.log("🏆 Perfect! You're a digital inclusion expert!");
      } else if (score >= totalQuestions * 0.7) {
        console.log("🥈 Good job! You have strong understanding of digital divide issues.");
      } else if (score >= totalQuestions * 0.5) {
        console.log("👍 Decent effort, but review some of the concepts again.");
      } else {
        console.log("📚 You need more study on digital divide solutions.");
      }
    }
    
    // Run the game with: bridgeTheDivideGame();
    
      Cell In[3], line 1
        function bridgeTheDivideGame() {
                 ^
    SyntaxError: invalid syntax
    

    FRQ

    • Describe three dimensions of the digital divide and explain how each affects access to educational resources. Provide specific examples.
      • Access to Technology:

        • Impact: Lack of devices limits students’ ability to access online resources and participate in digital learning.
        • Example: Low-income families may not afford laptops, hindering their educational progress.
      • Internet Connectivity:

        • Impact: Slow or unreliable internet disrupts online learning.
        • Example: Rural areas often have poor internet speeds, making virtual classrooms difficult.
      • Digital Literacy:

        • Impact: Without proper skills, students can’t effectively use digital tools or online platforms.
        • Example: A student may struggle to navigate e-learning software or online research.
    • Compare and contrast the digital divide challenges faced in urban versus rural communities. What solutions might be effective in each context?
      • Urban:

        • Challenges: Higher costs, digital literacy gaps.
        • Solutions: Focus on affordability and literacy programs.
      • Rural:

        • Challenges: Poor internet, limited access to devices.
        • Solutions: Invest in satellite internet and affordable tech solutions.
    • Analyze how the COVID-19 pandemic exposed and potentially exacerbated existing digital divides. Include at least three specific examples.

      • School Closures: Exposed gaps in tech access, preventing students from attending online classes.
      • Remote Work: Workers in rural or low-income areas lacked necessary internet or devices for remote work.
      • Health Information: Limited access to online health resources worsened health disparities.

    Extra Credit

    yemen

    • Implications for Yemen:
      • Limited access to digital resources: A low internet penetration rate means that many people in Yemen lack the ability to access critical digital services such as e-learning, online healthcare, and government services. This limits economic opportunities and social development.
      • Barriers due to conflict and infrastructure destruction: The ongoing conflict in Yemen has damaged infrastructure, making it harder for people to connect to the internet and access digital tools. This could prevent citizens from participating in the digital economy or accessing educational resources.
      • Electricity shortages: Limited access to reliable electricity compounds the problem, as even when there is internet availability, power issues may prevent consistent use of digital resources.

    Pakistan

    • Implications for Pakistan:
      • Higher internet penetration compared to Yemen: While Pakistan has slightly higher internet access, it still faces significant barriers in terms of literacy and affordability. Citizens may struggle to fully utilize the internet for education, e-commerce, or job opportunities.
      • Gender disparity: The gender gap in digital access, where women may have less access to technology or be less likely to use it, can further limit educational and economic opportunities, particularly for women in rural areas.
      • Infrastructure gaps: Inadequate infrastructure and power access still pose challenges for full digital inclusion in Pakistan, meaning that many people may not experience the benefits of digital technologies.
    • Solutions
      • Expand Low-Cost Internet Infrastructure:

        • Satellite internet: Partner with telecom companies and international organizations to provide affordable satellite-based internet solutions to underserved regions.
        • Solar-powered internet hubs: Deploy solar-powered hubs that can provide both electricity and internet access in remote areas, addressing two major barriers at once.
      • Digital Literacy and Skills Training:

        • Mobile-based digital literacy programs: Develop affordable, scalable mobile-based learning platforms targeting both urban and rural populations.
        • Gender-sensitive initiatives: Focus on providing digital literacy programs that include women and other marginalized groups to reduce the digital divide.
        • Public-private partnerships: Collaborate with local schools, NGOs, and tech companies to provide free or low-cost online education and digital skills workshops for the population.

    Computing Bias

    Popcorn Hack 1

    • Facial Recognition Misidentification
      • Bias Type: Technical Bias
      • Facial recognition systems have been shown to have higher error rates for people with darker skin tones due to imbalanced training data that over represents lighter-skinned individuals.
      • Impact: This leads to misidentifications, wrongful arrests, and discrimination in law enforcement and security applications.
      • Solution: Improve training datasets by including diverse skin tones and use bias-detection audits to evaluate model performance across different demographic groups.
      • Read More

    Popcorn Hack 2

    • Use Counterfactual Data Augmentation – Create synthetic loan applications where only the gender variable is changed while keeping all other financial factors the same. This helps the AI learn to make decisions based on merit rather than gender.

    • Adopt Explainable AI (XAI) Techniques – Implement transparency tools that reveal how the AI makes decisions, allowing human auditors to detect and correct gender-based disparities in loan approvals.

    Homework Hack

    “I use a voice assistant that sometimes struggles to understand my accent. The system is biased because it was mainly trained on certain dialects, making it harder for people with diverse accents to use. This is an example of Pre-existing Social Bias. To fix this, I would add a feature that lets users train the assistant to recognize their speech better over time.”

    Extra Credit

    • Bias: Pre-existing Social Bias
      • Example: AI recognizes faces better for lighter skin
      • Explanation: Many facial recognition systems perform better on lighter skin tones due to training data being predominantly composed of images of lighter-skinned individuals. This can lead to misidentification or exclusion of people with darker skin tones, affecting their access to services and security systems.
      • Solution: Improve AI training datasets by ensuring diversity in skin tones. Conduct regular audits to assess accuracy across different demographic groups and fine-tune the model accordingly.
    • Bias: Pre-existing Social Bias
      • Example: Google Translate stereotypes
      • Explanation: Google Translate has been known to reinforce gender stereotypes, such as translating gender-neutral pronouns into male-dominated professions (e.g., “he is a doctor” and “she is a nurse”). This reflects societal biases rather than neutral translation.
      • Solution: Implement bias-mitigation techniques in translation algorithms, such as balancing datasets with diverse examples and flagging gendered translations for review.
    • Bias: Technical Bias
      • Example: Bias in facial recognition technologies
      • Explanation: Facial recognition technologies often have higher error rates for people of color due to biased training data. This can lead to false identifications, discrimination, and even wrongful arrests.
      • Solution: AI developers should train models on diverse and representative datasets. Independent audits and transparency in AI development can also help mitigate these biases.
    • Bias: Pre-existing Social Bias
      • Example: Machine learning algorithms reinforce stereotypes
      • Explanation: Machine learning models trained on biased data can reinforce and amplify existing social biases, such as associating certain jobs, behaviors, or characteristics with specific races or genders. This can perpetuate discrimination in hiring, policing, and recommendations.
      • Solution: Regularly audit datasets and models for bias, and incorporate fairness-aware algorithms that actively detect and mitigate discriminatory patterns.
    • Bias: Emergent Social Bias
      • Example: Tay chatbot learns hate
      • Explanation: Microsoft’s Tay chatbot was designed to learn from user interactions, but it quickly adopted offensive and racist language due to exposure to toxic online behavior. This demonstrates how AI systems can be manipulated by user interactions.
      • Solution: Implement stricter content moderation, filtering, and real-time monitoring of AI learning processes. AI should have ethical guidelines and safeguards against adopting harmful language.
    • Bias: Pre-existing Social Bias & Technical Bias
      • Example: Amazon AI favors men
      • Explanation: Amazon’s AI hiring system was found to favor male candidates by penalizing resumes that included words associated with women (e.g., “women’s chess club”). This occurred because the model was trained on past hiring data that reflected gender disparities.
      • Solution: Ensure hiring algorithms are trained on unbiased data, remove gendered indicators, and regularly test AI for discriminatory patterns. Human oversight should be integrated into AI-driven decision-making.

    Crowdsourcing

    Popcorn Hack

    captcha

    • Public Dataset: Google Trends
      • Purpose: Tracks search interest over time for keywords, helping businesses, researchers, and marketers analyze trends.

      • Pros:
        ✅ Real-time insights into public interests
        ✅ Useful for market research & forecasting

      • Cons:
        ⚠️ Skewed towards internet users, ignoring offline populations
        ⚠️ Can be manipulated by viral trends or bot activity

    Homework Hacks

    Question 1:

    • Concept of Crowdsourcing: Crowdsourcing is a method of obtaining input, services, or ideas by soliciting contributions from a large group of people, typically from an online community. This approach leverages the collective knowledge, creativity, or effort of a large number of participants, often offering them small incentives or recognition in return. Crowdsourcing can be used to solve problems, generate ideas, or complete tasks that would otherwise be difficult or time-consuming for a single organization or individual to accomplish.
    • Citizen Science (Astronomy) – Projects like Galaxy Zoo allow volunteers to help classify galaxies using telescope images.
    • Traffic Data (Navigation Apps) – Apps like Waze crowdsource real-time traffic updates from drivers to improve navigation accuracy.

    Question 2: A successful example of crowdsourcing is Wikipedia.

    • Project: A free, collaborative online encyclopedia.
    • Goals: To create and maintain a vast collection of accurate, publicly accessible information.
    • Outcomes: Millions of articles written by volunteers worldwide, making knowledge more accessible and reducing reliance on traditional encyclopedias.

    Question 3:

    • Quality Control Issues – Crowdsourced work may lack accuracy or consistency (e.g., false or biased information on Wikipedia).
    • Exploitation of Labor – Platforms like Amazon Mechanical Turk pay workers very little for tasks, leading to criticism of unfair compensation.
    • Security Risks – Open platforms may be vulnerable to misinformation or data breaches.
    • Example: In 2016, Google’s “Quick, Draw!” (a crowdsourced AI doodling game) raised concerns about privacy since users’ drawings were used to train AI without explicit compensation.

    Question 4:

    • Dataset: CDC’s National Diabetes Statistics Report
    • Source: Centers for Disease Control and Prevention (CDC)
    • Purpose: Provides nationwide statistics on diabetes prevalence, demographics, and health outcomes.

    Legal / Ethical Concerns

    Popcorn Hack #1

    • My IP: hire someone to create a logo, design, or software specifically for myself, here’s an agreement that I own the rights to the work upon completion. I can make copies, resell, or modify the work because I own the rights to it.
    • Not My IP: buy a movie on DVD or a book…

    Popcorn Hack #2

    • As a computer science student, I’d probably go with CC BY-SA for my repository or site. It allows people to modify and share my work, but they have to keep it under the same license. This way, I can make sure the project stays open-source and others can contribute, while also ensuring that any derivative work is shared in the same way. It’s a good balance between openness and maintaining control over the project’s future development.

    Safe Computing

    Popcorn Hack #1

    • Think about a website/company/app that has access to your PII. Describe the service and the kind of data they might store on you. Then, answer the question: How would it affect you if this information was stolen, and what might hackers be able to do with it? (Think about fraud, connections to other websites)
      • Example: Google stores my emails, passwords, location, search history, and payment details.
        • If hacked:
          • Identity Theft – Access to emails, bank accounts, and personal data.
          • Full Digital Takeover – Hackers reset passwords on other linked accounts.
          • Blackmail & Phishing – Exploiting private emails and search history.
        • To protect myself:
          • Enable 2FA
          • Use unique, strong passwords
          • Monitor account activity regularly

    Popcorn Hack #2

    • You receive an email warning that your bank account is locked and that you need to click a link to reset your password. What steps should you take before taking action?
      • If I receive an email claiming my bank account is locked, I will be cautious before acting. I’ll check the sender’s email, avoid clicking links, and review my account history by logging in through the official website. I’ll watch for urgent language, typos, or suspicious URLs. Instead of using the provided link, I’ll contact my bank directly. Lastly, I’ll ensure two-factor authentication (2FA) is enabled for extra security.

    Popcorn Hack #3

    • How might public Wi-Fi networks be exploited by hackers, and what precautions should users take when connecting to them?
      • Hackers can exploit public Wi-Fi by intercepting data, setting up fake hotspots, or spying on unencrypted information. To stay safe, I won’t access sensitive accounts, and I’ll use a VPN to protect my connection. I’ll also check for HTTPS, turn off auto-connect, and use mobile data or a personal hotspot when possible, I can also use a vpn

    Quiz

    Binary Search

    Homework Hack #1

    def search_rotated_array(arr, target):
        left, right = 0, len(arr) - 1
    
        while left <= right:
            mid = (left + right) // 2
    
            # Check if mid is the target
            if arr[mid] == target:
                return mid
    
            # Left half is sorted
            if arr[left] <= arr[mid]:
                if arr[left] <= target < arr[mid]:
                    right = mid - 1  # target in left half
                else:
                    left = mid + 1   # target in right half
            # Right half is sorted
            else:
                if arr[mid] < target <= arr[right]:
                    left = mid + 1   # target in right half
                else:
                    right = mid - 1  # target in left half
    
        return -1  # Target not found
    

    Homework Hack #2

        def find_first_and_last(arr, target):
            def find_first():
                left, right = 0, len(arr) - 1
                first = -1
                while left <= right:
                    mid = (left + right) // 2
                    if arr[mid] == target:
                        first = mid
                        right = mid - 1 
                    elif arr[mid] < target:
                        left = mid + 1
                    else:
                        right = mid - 1
                return first
    
            def find_last():
                left, right = 0, len(arr) - 1
                last = -1
                while left <= right:
                    mid = (left + right) // 2
                    if arr[mid] == target:
                        last = mid
                        left = mid + 1 
                    elif arr[mid] < target:
                        left = mid + 1
                    else:
                        right = mid - 1
                return last
    
            first = find_first()
            last = find_last()
    
            if first == -1:
                return -1
            return (first, last)
    

    Homework Hack #3

        def smallest_greater_or_equal(arr, target):
            left, right = 0, len(arr) - 1
            result = -1  # default if no element is found
    
            while left <= right:
                mid = (left + right) // 2
    
                if arr[mid] >= target:
                    result = arr[mid]      # possible candidate
                    right = mid - 1        # try to find a smaller valid one on the left
                else:
                    left = mid + 1         # look on the right
    
            return result
    

    List Filter

    Popcorn Hacks

    1.  def find_students_in_range(df, min_score, max_score):
       return df[(df['Score'] >= min_score) & (df['Score'] <= max_score)]
      
    2.  def add_letter_grades(df):
       def get_letter(score):
           if score >= 90:
               return 'A'
           elif score >= 80:
               return 'B'
           elif score >= 70:
               return 'C'
           elif score >= 60:
               return 'D'
           else:
               return 'F'
      
       df['Letter'] = df['Score'].apply(get_letter)
       return df
      
    3.  def find_mode(series):
       return series.mode().iloc[0]
      

    Homework Hacks

    • Here is the new design of filtered dataset for my pilot city project – glucose monitor
        import pandas as pd
        import matplotlib.pyplot as plt
        import seaborn as sns
    
        file_path = "/home/your_path/dexcom_simulator_glucose.csv"
        df = pd.read_csv(file_path)
    
        df.rename(columns={
            'Timestamp': 'timestamp',
            'GlucoseValue': 'glucose',
            'Trend': 'trend' 
        }, inplace=True)
    
        df['timestamp'] = pd.to_datetime(df['timestamp'])
        df = df.dropna(subset=['glucose'])
        df = df[df['glucose'] > 0]
        df = df.sort_values(by='timestamp')
    
        def classify_glucose(value):
            if value < 70:
                return 'Hypo'
            elif value > 180:
                return 'Hyper'
            else:
                return 'Normal'
    
        df['glucose_level'] = df['glucose'].apply(classify_glucose)
    
        plt.figure(figsize=(14, 6))
        sns.lineplot(x='timestamp', y='glucose', data=df, color='blue', label='Glucose Level')
        plt.axhline(70, color='red', linestyle='--', label='Hypoglycemia Threshold')
        plt.axhline(180, color='orange', linestyle='--', label='Hyperglycemia Threshold')
        plt.title("Glucose Levels Over Time (Dexcom Simulator)")
        plt.xlabel("Time")
        plt.ylabel("Glucose (mg/dL)")
        plt.legend()
        plt.grid(True)
        plt.tight_layout()
        plt.show()
    
        df['date'] = df['timestamp'].dt.date
        daily_summary = df.groupby('date')['glucose'].agg(['mean', 'max', 'min', 'std']).reset_index()
        daily_summary.columns = ['Date', 'Avg Glucose', 'Max Glucose', 'Min Glucose', 'Std Dev']
        print("📋 Daily Summary:")
        print(daily_summary.head())
    
        event_counts = df['glucose_level'].value_counts()
        plt.figure(figsize=(6, 4))
        sns.barplot(x=event_counts.index, y=event_counts.values, palette='coolwarm')
        plt.title("Glucose Event Count")
        plt.ylabel("Number of Readings")
        plt.xlabel("Glucose Category")
        plt.show()
    
        df.to_csv("cleaned_glucose_readings.csv", index=False)
    

    Big O and Algorithmic Complexity

    Homework Hacks

    1. O(1) - Constant Time

    def get_first_element(arr):
        """Returns the first element of an array. O(1) time."""
        return arr[0] if arr else None
    
    # Example usage:
    arr = [5, 2, 9, 1, 5]
    print(get_first_element(arr))  # Output: 5
    

    Explanation:

    • Accessing an array element by index is always O(1) because it uses direct memory addressing.
    • The operation takes the same time regardless of array size.

    2. O(log n) - Logarithmic Time

    def binary_search(arr, target):
        """Binary search implementation. O(log n) time."""
        low, high = 0, len(arr) - 1
        while low <= high:
            mid = (low + high) // 2
            if arr[mid] == target:
                return mid
            elif arr[mid] < target:
                low = mid + 1
            else:
                high = mid - 1
        return -1
    
    # Example usage:
    sorted_arr = [1, 3, 5, 7, 9, 11]
    print(binary_search(sorted_arr, 7))  # Output: 3 (index of 7)
    

    Explanation:

    • With each iteration, the search space is halved.
    • This logarithmic reduction leads to O(log n) time complexity.

    3. O(n) - Linear Time

    def linear_search(arr, target):
        """Linear search through array. O(n) time."""
        for i, num in enumerate(arr):
            if num == target:
                return i
        return -1
    
    # Example usage:
    arr = [4, 2, 7, 1, 9]
    print(linear_search(arr, 1))  # Output: 3 (index of 1)
    

    Explanation:

    • In the worst case, we may need to check every element once.
    • Time grows linearly with input size n.

    4. O(n²) - Quadratic Time

    def find_duplicates(arr):
        """Finds duplicate elements using nested loops. O(n²) time."""
        duplicates = []
        for i in range(len(arr)):
            for j in range(i + 1, len(arr)):
                if arr[i] == arr[j] and arr[i] not in duplicates:
                    duplicates.append(arr[i])
        return duplicates
    
    # Example usage:
    arr = [1, 2, 3, 2, 4, 3, 5]
    print(find_duplicates(arr))  # Output: [2, 3]
    

    Explanation:

    • For each element (n), we compare it to every subsequent element (~n comparisons).
    • This results in n × n = n² operations in the worst case.

    Key Observations:

    1. O(1): Fastest, independent of input size
    2. O(log n): Very efficient for large datasets
    3. O(n): Proportional to input size
    4. O(n²): Becomes slow quickly as n grows

    Undecidable Problems, Graphs, Heuristics

    Homework Hacks

    1. Undecidable Problem: The Infinite Tiling Problem

    Imagine you have an infinite grid and a finite set of colored tiles, each with colored edges. The question is: can you tile the entire infinite grid using these tiles so that all touching edges match in color?

    This is known as the Infinite Tiling Problem, and it is undecidable. More specifically, given a finite set of Wang tiles (square tiles with colored edges), there is no general algorithm that can determine whether those tiles can tile the infinite plane without mismatches.

    2. Nearest Neighbor Algorithm for the Traveling Salesman Problem (TSP)

    import math
    
    # Define cities with (x, y) coordinates
    cities = {
        "Pineville": (0, 0),
        "Lakeside": (1, 4),
        "Riverbend": (5, 2),
        "Hilltop": (6, 6),
        "Stonefield": (9, 3)
    }
    
    def distance(a, b):
        x1, y1 = cities[a]
        x2, y2 = cities[b]
        return math.hypot(x2 - x1, y2 - y1)
    
    def nearest_neighbor(start):
        unvisited = set(cities.keys())
        tour = [start]
        unvisited.remove(start)
        current = start
    
        while unvisited:
            next_city = min(unvisited, key=lambda city: distance(current, city))
            print(f"Traveling from {current} to {next_city}, Distance: {distance(current, next_city):.2f}")
            tour.append(next_city)
            unvisited.remove(next_city)
            current = next_city
    
        tour.append(start)  # Complete the loop
        print(f"Returning to {start}, Distance: {distance(current, start):.2f}")
        return tour
    
    path = nearest_neighbor("Pineville")
    print("\nTSP path (Nearest Neighbor):", " → ".join(path))
    

    3. Heuristics in Action: Warehouse Robotics Pathfinding

    In modern automated warehouses (think Amazon fulfillment centers), fleets of robots navigate tightly packed storage zones to retrieve items. Computing the exact optimal path for every robot in real-time would be a logistical nightmare—especially considering thousands of simultaneous movements, changing priorities, and live updates to inventory.

    Instead, warehouses use heuristic-based pathfinding—like A* search with dynamic weight adjustments—to calculate efficient, but not always perfect, paths. This keeps the robots moving smoothly and avoids computational bottlenecks. Here, perfection takes a back seat to speed and adaptability, proving that “good enough, fast” beats “perfect, late.”

    MC

    Binary Base 2 Math

    Homework Hacks

    Binary Calculator

    from flask import Flask, request, jsonify
    
    app = Flask(__name__)
    
    @app.route('/calculate', methods=['POST'])
    def calculate():
        data = request.get_json()
        bin1 = data.get('bin1')
        bin2 = data.get('bin2')
        operation = data.get('operation')  # add, subtract, multiply, divide
    
        try:
            num1 = int(bin1, 2)
            num2 = int(bin2, 2)
        except (ValueError, TypeError):
            return jsonify({'error': 'Invalid binary input'}), 400
    
        result = None
    
        if operation == 'add':
            result = num1 + num2
        elif operation == 'subtract':
            result = num1 - num2
        elif operation == 'multiply':
            result = num1 * num2
        elif operation == 'divide':
            if num2 == 0:
                return jsonify({'error': 'Division by zero is not allowed'}), 400
            result = num1 // num2  # Integer division
        else:
            return jsonify({'error': 'Invalid operation'}), 400
    
        # Convert the result back to binary
        binary_result = bin(result)[2:] if result >= 0 else '-' + bin(abs(result))[2:]
    
        return jsonify({
            'bin1': bin1,
            'bin2': bin2,
            'operation': operation,
            'result': binary_result
        })
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    Color Code

    Homework

    Exercise 1

    1) #1E90FF

    • RGB: (30, 144, 255)
    • RGBA (A=1): rgba(30, 144, 255, 1)

    2) #32CD32

    • RGB: (50, 205, 50)
    • RGBA (A=1): rgba(50, 205, 50, 1)

    3) #FFD700

    • RGB: (255, 215, 0)
    • RGBA (A=1): rgba(255, 215, 0, 1)

    4)50% Transparent Teal (RGB: (0, 128, 128)):

    • RGBA: rgba(0, 128, 128, 0.5)

    Exercise 2

    1) Pick 4 Colors (One for Each Pixel):

    • 🔴 Red: #FF0000
    • 🟢 Green: #00FF00
    • 🔵 Blue: #0000FF
    • 🟡 Yellow: #FFFF00

    2) Calculate Storage at 24-bit Color Depth

    • 24-bit color depth = 24 bits per pixel
    • 2×2 image = 4 pixels
    • Total bits = 24 bits/pixel × 4 pixels = 96 bits

    To convert to bytes:
    96 bits á 8 = 12 bytes

    Total storage = 96 bits = 12 bytes

    Exercise 3

    1. Base64 Encode the String "Cat"

    • Plaintext: "Cat"
    • Base64 encoded:
      Q2F0
      

      2. Create a 1×1 Red PNG and Convert to Base64

    Red Pixel