🐍 MESSY PYTHON SCRIPTS COLLECTION
Green Coding Exercise - Energy-Inefficient Code for Students
Instructions for Students: Your teacher will assign you ONE of these scripts. Copy it exactly as written (yes,
even though it's inefficient!). Then submit it to the Alien CTO for review.
📗 BEGINNER LEVEL
Script 1: Temperature Converter
python
# Convert Celsius to Fahrenheit for a list of temperatures
celsius_temps = [0, 10, 20, 30, 40]
fahrenheit_temps = []
temp1 = celsius_temps[0]
fahr1 = (temp1 * 9/5) + 32
fahrenheit_temps.append(fahr1)
temp2 = celsius_temps[1]
fahr2 = (temp2 * 9/5) + 32
fahrenheit_temps.append(fahr2)
temp3 = celsius_temps[2]
fahr3 = (temp3 * 9/5) + 32
fahrenheit_temps.append(fahr3)
temp4 = celsius_temps[3]
fahr4 = (temp4 * 9/5) + 32
fahrenheit_temps.append(fahr4)
temp5 = celsius_temps[4]
fahr5 = (temp5 * 9/5) + 32
fahrenheit_temps.append(fahr5)
print(fahrenheit_temps)
Script 2: Grade Calculator
python
# Calculate letter grade from percentage
scores = [85, 92, 78, 65, 95]
grades = []
for i in range(len(scores)):
score = scores[i]
if score >= 90:
grade = "A"
[Link](grade)
if score >= 80 and score < 90:
grade = "B"
[Link](grade)
if score >= 70 and score < 80:
grade = "C"
[Link](grade)
if score >= 60 and score < 70:
grade = "D"
[Link](grade)
if score < 60:
grade = "F"
[Link](grade)
print(grades)
Script 3: Word Counter
python
# Count how many times each word appears
sentence = "the cat and the dog and the bird"
words = [Link]()
word_counts = []
for word in words:
count = 0
for w in words:
if w == word:
count = count + 1
word_counts.append(f"{word}: {count}")
print(word_counts)
📘 INTERMEDIATE LEVEL
Script 4: Remove Duplicates
python
# Remove duplicates from a list
numbers = [1, 2, 2, 3, 4, 4, 5, 1, 6, 7, 7]
unique_numbers = []
for num in numbers:
is_duplicate = False
for unique_num in unique_numbers:
if num == unique_num:
is_duplicate = True
if is_duplicate == False:
unique_numbers.append(num)
print(unique_numbers)
Script 5: Find Common Elements
python
# Find common elements between two lists
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list2 = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
common = []
for item1 in list1:
for item2 in list2:
if item1 == item2:
[Link](item1)
print(common)
Script 6: Sum of Products
python
# Calculate sum of products of paired numbers
prices = [10, 20, 30, 40, 50]
quantities = [2, 3, 1, 4, 2]
total = 0
product1 = prices[0] * quantities[0]
total = total + product1
product2 = prices[1] * quantities[1]
total = total + product2
product3 = prices[2] * quantities[2]
total = total + product3
product4 = prices[3] * quantities[3]
total = total + product4
product5 = prices[4] * quantities[4]
total = total + product5
print(f"Total cost: ${total}")
📙 INTERMEDIATE-ADVANCED LEVEL
Script 7: Text Analysis
python
# Count lines, words, and characters in text
text = """Hello world
This is a test
Python is great"""
# Count lines
lines = [Link]('\n')
line_count = 0
for line in lines:
line_count = line_count + 1
# Count words
all_words = []
for line in lines:
words = [Link]()
for word in words:
all_words.append(word)
word_count = 0
for word in all_words:
word_count = word_count + 1
# Count characters
char_count = 0
for line in lines:
for char in line:
char_count = char_count + 1
print(f"Lines: {line_count}")
print(f"Words: {word_count}")
print(f"Characters: {char_count}")
Script 8: Email Validator
python
# Check if emails are valid
emails = ["test@[Link]", "[Link]", "user@[Link]", "badformat"]
valid_emails = []
invalid_emails = []
for email in emails:
has_at = False
has_dot = False
for char in email:
if char == "@":
has_at = True
if char == ".":
has_dot = True
if has_at == True and has_dot == True:
valid_emails.append(email)
else:
invalid_emails.append(email)
print("Valid:", valid_emails)
print("Invalid:", invalid_emails)
Script 9: Data Cleaning
python
# Clean and format names
names = [" JOHN doe ", "jane SMITH", " bob JONES "]
cleaned_names = []
for name in names:
# Remove leading spaces
while name[0] == " ":
name = name[1:]
# Remove trailing spaces
while name[-1] == " ":
name = name[:-1]
# Convert to title case
words = [Link]()
title_case_words = []
for word in words:
first_letter = word[0].upper()
rest_of_word = word[1:].lower()
title_word = first_letter + rest_of_word
title_case_words.append(title_word)
cleaned_name = " ".join(title_case_words)
cleaned_names.append(cleaned_name)
print(cleaned_names)
📕 ADVANCED LEVEL
Script 10: Fibonacci Sequence (Inefficient Recursion)
python
# Generate first 20 Fibonacci numbers
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
fib_numbers = []
for i in range(20):
fib_numbers.append(fibonacci(i))
print(fib_numbers)
Script 11: Student Grade Analysis
python
# Analyze student performance
students = {
"Alice": [85, 90, 78, 92],
"Bob": [76, 81, 72, 85],
"Carol": [95, 88, 91, 94]
}
# Calculate averages
averages = []
for student in students:
scores = students[student]
total = 0
count = 0
for score in scores:
total = total + score
count = count + 1
average = total / count
[Link]({student: average})
# Find highest average
highest_avg = 0
top_student = ""
for avg_dict in averages:
for student in avg_dict:
if avg_dict[student] > highest_avg:
highest_avg = avg_dict[student]
top_student = student
# Find lowest average
lowest_avg = 100
lowest_student = ""
for avg_dict in averages:
for student in avg_dict:
if avg_dict[student] < lowest_avg:
lowest_avg = avg_dict[student]
lowest_student = student
print(f"Top student: {top_student} ({highest_avg})")
print(f"Lowest student: {lowest_student} ({lowest_avg})")
Script 12: CSV Data Processing (Simulated)
python
# Process sales data
sales_data = "Product,Price,Quantity\nApple,1.5,100\nBanana,0.8,150\nOrange,1.2,80"
# Parse CSV manually
lines = sales_data.split('\n')
header = lines[0]
data_lines = []
for i in range(1, len(lines)):
data_lines.append(lines[i])
# Calculate total revenue
total_revenue = 0
for line in data_lines:
parts = [Link](',')
product = parts[0]
price = float(parts[1])
quantity = int(parts[2])
revenue = price * quantity
total_revenue = total_revenue + revenue
# Find most profitable product
max_revenue = 0
top_product = ""
for line in data_lines:
parts = [Link](',')
product = parts[0]
price = float(parts[1])
quantity = int(parts[2])
revenue = price * quantity
if revenue > max_revenue:
max_revenue = revenue
top_product = product
print(f"Total revenue: ${total_revenue}")
print(f"Top product: {top_product} (${max_revenue})")
📊 QUICK REFERENCE: What's Wrong With Each Script?
Script # Main Problem Expected Green Fix
1 Repetitive code, no loop Use for loop or list comprehension
2 Multiple if statements (no elif) Use elif chain, reduce comparisons
Script # Main Problem Expected Green Fix
3 Nested loops O(n²) Use dictionary or Counter from collections
4 Nested loops for duplicate checking Use set() - O(n) instead of O(n²)
5 Nested loops for comparison Use set intersection
6 Manual repetition, no loop Use zip() and sum()
7 Multiple separate loops Use len(), reduce iterations
8 Character-by-character loop Use 'in' operator for strings
9 Manual string manipulation Use .strip() and .title() methods
10 Exponential time recursion Add memoization or use iteration
11 Repetitive code, multiple passes Use functions, max(), min() built-ins
12 Repeated parsing of same data Parse once, use list comprehensions
🎯 DISTRIBUTION SUGGESTIONS
Option A: Skill-Based Assignment
Beginners (learning basics): Scripts 1-3
Intermediate (comfortable with loops): Scripts 4-6
Advanced (know functions/data structures): Scripts 7-9
Challenge seekers: Scripts 10-12
Option B: Random Assignment
Put script numbers in a hat
Students draw randomly
Creates variety in class discussion
Option C: Choice-Based
Let students pick based on topic interest
Temperature? Grades? Fibonacci? Student choice!
Teacher Note: All scripts are intentionally inefficient for educational purposes. The goal is for students to
identify improvements through AI assistance and learn green coding principles.