# Initialize Otter
import otter
grader = otter.Notebook("03_lab_decision_structures.ipynb")
Decision Structures Lab - CreatorSpace Analytics¶
Scenario: You're building analytics tools for CreatorSpace, a platform where content creators track metrics, ad revenue, and sponsor opportunities.
Reference: See lecture notebook 03_decision_structures_boolean_logic.ipynb for syntax help.
Important: Run cells in order. Each question uses unique variable names.
# Validation: Check Python version and file location
import math
import os
import sys
# Supported Python versions for this course
SUPPORTED_VERSIONS = ["3.12", "3.13"]
current_version = f"{sys.version_info.major}.{sys.version_info.minor}"
if current_version not in SUPPORTED_VERSIONS:
raise EnvironmentError(
f"Python version mismatch!\n"
f"Supported: {', '.join(SUPPORTED_VERSIONS)}\n"
f"Found: {current_version}\n"
f"Please use Python 3.12 or 3.13 for this course."
)
print(f"Python version: {current_version}")
# Expected filename for this assignment
EXPECTED_FILE = "03_lab_decision_structures.ipynb"
# Check file is in the correct directory
current_path = os.path.abspath("")
required_path_segment = os.path.join("Documents", "CSC115", "lab_notebooks")
allowed_envs = ["submission", "dist", "live", "source"]
in_allowed_env = any(env in current_path for env in allowed_envs)
if required_path_segment not in current_path and not in_allowed_env:
raise EnvironmentError(
f"File location error!\n"
f"This notebook should be in: ~/Documents/CSC115/lab_notebooks/\n"
f"Current location: {current_path}\n"
f"Please move this file to the correct directory."
)
# Verify directory name and filename (skip in grading/development environments)
if not in_allowed_env:
if not os.path.exists(EXPECTED_FILE):
notebooks = [f for f in os.listdir(".") if f.endswith(".ipynb")]
raise EnvironmentError(
f"Filename mismatch!\n"
f"Expected: {EXPECTED_FILE}\n"
f"Found notebooks: {notebooks}\n"
f"Please rename your notebook to '{EXPECTED_FILE}'."
)
print(f"File location: {os.path.join(current_path, EXPECTED_FILE)}")
Question 1: Payment Processing (1 point)¶
CreatorSpace pays creators in $100 increments. Given pending_earnings = 847:
complete_payments- How many $100 payments can be maderemaining_balance- How much stays in pending
# Given value (do not change)
pending_earnings = 847
payment_amount = 100
# ✏️ YOUR CODE HERE
complete_payments = ...
remaining_balance = ...
print(f"Pending earnings: ${pending_earnings}")
print(f"Complete $100 payments: {complete_payments}")
print(f"Remaining balance: ${remaining_balance}")
grader.check("q1_payment_processing")
Question 2: Monetization Eligibility (1 point)¶
CreatorSpace allows creators to earn money from ads, but only after meeting platform requirements. The channel must have built up a minimum audience size (at least one thousand subscribers) AND demonstrated consistent content (at least four thousand watch hours).
Note: The platform tracks subscribers and watch hours separately. A channel might have lots of subscribers but not enough watch hours (or vice versa) if they're new or post infrequently.
Create three boolean variables:
has_enough_subs- Does the channel meet the subscriber minimum?has_enough_hours- Does the channel meet the watch hours minimum?can_monetize- Can monetization be enabled? (requires meeting both thresholds)
# Given values (do not change)
channel_subscribers = 1000
channel_watch_hours = 3500
# ✏️ YOUR CODE HERE
has_enough_subs = ...
has_enough_hours = ...
can_monetize = ...
print(f"Subscribers: {channel_subscribers} (need 1,000)")
print(f"Watch hours: {channel_watch_hours} (need 4,000)")
print(f"Has enough subscribers: {has_enough_subs}")
print(f"Has enough watch hours: {has_enough_hours}")
print(f"Can monetize: {can_monetize}")
grader.check("q2_monetization_check")
Question 3: Engagement Rate Calculation (1 point)¶
The engagement rate measures audience interaction. Calculate it by adding all interactions (likes and comments) and dividing by total views. Round to 4 decimal places.
A video "meets the industry benchmark" if its engagement rate is within 1% of the target. Since floating-point numbers can have tiny rounding differences, use math.isclose() with rel_tol=0.01 to check if two values are close enough.
Create:
engagement_rate- The calculated rate, rounded to 4 decimal placesmeets_benchmark- True if the rate is within 1% of the industry target
# Given values (do not change)
video_likes = 1850
video_comments = 427
video_views = 45000
industry_benchmark = 0.0504
# ✏️ YOUR CODE HERE
engagement_rate = ...
meets_benchmark = ...
print(f"Likes: {video_likes}, Comments: {video_comments}, Views: {video_views}")
print(f"Engagement rate: {engagement_rate}")
print(f"Industry benchmark: {industry_benchmark}")
print(f"Meets benchmark: {meets_benchmark}")
grader.check("q3_engagement_rate")
Question 4: Ad Revenue Tiers (1 point)¶
CreatorSpace calculates ad revenue using CPM (cost per mille), which is the dollar amount paid per thousand views. Larger channels with more subscribers earn higher CPM rates because advertisers pay a premium to reach bigger audiences.
Tier thresholds:
- Channels with one million or more subscribers are "Premium" ($8 per thousand views)
- Channels with at least one hundred thousand subscribers are "Established" ($5 per thousand views)
- Channels with at least ten thousand subscribers are "Growing" ($3 per thousand views)
- Smaller channels are "Starter" ($1.50 per thousand views)
To calculate revenue: divide total monthly views by one thousand, then multiply by the CPM rate.
Create: tier_name, cpm_rate, estimated_revenue
# Given values (do not change)
creator_subscribers = 75000
monthly_views = 500000
# ✏️ YOUR CODE HERE
# Write an if-elif-else chain to set tier_name and cpm_rate based on subscriber count
# Premium: 1M+ subs ($8), Established: 100K+ ($5), Growing: 10K+ ($3), Starter: under 10K ($1.50)
...
...
...
...
estimated_revenue = ...
print(f"Subscribers: {creator_subscribers:,}")
print(f"Monthly views: {monthly_views:,}")
print(f"Tier: {tier_name}")
print(f"CPM rate: ${cpm_rate}")
print(f"Estimated revenue: ${estimated_revenue:,.2f}")
grader.check("q4_revenue_tiers")
Question 5: Video Performance Category (1 point)¶
The "view ratio" measures how many of a channel's subscribers actually watched a specific video. Calculate it by dividing video views by total channel subscribers, then multiply by 100 to get a percentage.
CreatorSpace uses this metric to categorize video performance. Videos that get views from more than half the subscriber base are viral hits. Those reaching between one-fifth and half are performing strongly. Videos reaching at least one-tenth are average. Anything below that threshold needs improvement.
The platform also tracks average watch time and completion rate, but those aren't used for this categorization.
Categories: Viral: 50%+, Strong: 20-49%, Average: 10-19%, Needs Work: under 10%
Create: view_ratio, performance_category
# Given values (do not change)
video_views_q5 = 8500
channel_subs_q5 = 25000
# ✏️ YOUR CODE HERE
view_ratio = ...
# Write an if-elif-else chain to set performance_category
# Viral: 50%+, Strong: 20-49%, Average: 10-19%, Needs Work: under 10%
...
...
...
...
print(f"Video views: {video_views_q5:,}")
print(f"Channel subscribers: {channel_subs_q5:,}")
print(f"View ratio: {view_ratio:.1f}%")
print(f"Performance: {performance_category}")
grader.check("q5_video_performance")
Question 6: Sponsor Deal Qualification (1 point)¶
A sponsor wants to partner with CreatorSpace creators who meet certain criteria. They're looking for creators who satisfy either of two different profiles:
Quality creators: Have built a dedicated audience (at least ten thousand subscribers) AND maintain high engagement (five percent or higher engagement rate). These creators may have smaller audiences but their followers are highly active.
Large creators: Have a substantial reach (at least fifty thousand subscribers) regardless of engagement rate. The sheer audience size makes them valuable even with lower engagement.
The sponsor will consider working with any creator who fits at least one of these profiles.
Create: meets_quality_threshold, meets_size_threshold, qualifies_for_sponsor
# Given values (do not change)
sponsor_subs = 35000
sponsor_engagement = 0.042 # 4.2%
# ✏️ YOUR CODE HERE
meets_quality_threshold = ...
meets_size_threshold = ...
qualifies_for_sponsor = ...
print(f"Subscribers: {sponsor_subs:,}")
print(f"Engagement rate: {sponsor_engagement * 100:.1f}%")
print(f"Meets quality threshold (10K+ subs AND 5%+ engagement): {meets_quality_threshold}")
print(f"Meets size threshold (50K+ subs): {meets_size_threshold}")
print(f"Qualifies for sponsor: {qualifies_for_sponsor}")
grader.check("q6_sponsor_qualification")
Question 7: Content Warning Flags (1 point)¶
Flag content for review if any of these are true:
- Misclassification:
is_matureAND views < 1,000 - Bot activity: engagement < 1% (0.01) AND views > 10,000
- Disabled comments:
not comments_enabledAND video > 60 seconds
Create: flag_misclassification, flag_bot_activity, flag_disabled_comments, needs_review
# Given values (do not change)
is_mature = False
comments_enabled = True
vid_views = 15000
vid_engagement = 0.008 # 0.8%
vid_length_seconds = 450 # 7.5 minutes
# ✏️ YOUR CODE HERE
flag_misclassification = ...
flag_bot_activity = ...
flag_disabled_comments = ...
needs_review = ...
print(f"Is mature content: {is_mature}")
print(f"Comments enabled: {comments_enabled}")
print(f"Views: {vid_views:,}")
print(f"Engagement: {vid_engagement * 100:.1f}%")
print(f"Video length: {vid_length_seconds} seconds")
print()
print(f"Flag - Misclassification: {flag_misclassification}")
print(f"Flag - Bot activity: {flag_bot_activity}")
print(f"Flag - Disabled comments: {flag_disabled_comments}")
print(f"Needs review: {needs_review}")
grader.check("q7_content_warnings")
Question 8: Creator Dashboard Summary (2 points)¶
Build a complete creator status report with multiple calculations. The dashboard displays key metrics and eligibility status.
Monthly payout: CreatorSpace pays in fifty-dollar increments. Calculate how much will be paid this month by flooring earnings to the nearest $50 (floor division by 50, then multiply back).
Channel tier: Same tier categories as Question 4 based on subscriber count.
Partner eligibility: Same requirements as Question 2 (subscriber and watch hour minimums).
Growth status: Calculate the percentage change in subscribers from last month. Compare current subscribers to last month's count to find the growth rate. Channels growing at ten percent or more are "Accelerating", those with positive but smaller growth are "Stable", and channels losing subscribers are "Declining".
Featured eligibility: The platform features creators on the homepage who meet ALL of these criteria: they must be partner eligible, belong to a top tier (the two highest tiers), and not be in decline.
Create: monthly_payout, channel_tier, partner_eligible, growth_status, featured_eligible
# Given values (do not change)
dash_earnings = 1847.50
dash_subs = 125000
dash_watch_hours = 52000
subs_last_month = 118000
# ✏️ YOUR CODE HERE
# 1. Monthly payout (floor to nearest $50)
monthly_payout = ...
# 2. Channel tier (same as Q4)
# Premium: 1M+, Established: 100K+, Growing: 10K+, Starter: under 10K
...
...
...
...
# 3. Partner eligible (1K subs AND 4K watch hours)
partner_eligible = ...
# 4. Growth status
growth_pct = ...
...
...
...
# 5. Featured eligible (partner AND (Premium OR Established) AND not declining)
is_top_tier = ...
is_not_declining = ...
featured_eligible = ...
print("=== Creator Dashboard ===")
print(f"Earnings: ${dash_earnings:,.2f} -> Payout: ${monthly_payout:,.2f}")
print(f"Subscribers: {dash_subs:,} ({channel_tier} tier)")
print(f"Watch hours: {dash_watch_hours:,}")
print(f"Growth: {growth_pct:.1f}% ({growth_status})")
print(f"Partner eligible: {partner_eligible}")
print(f"Featured eligible: {featured_eligible}")
grader.check("q8_dashboard")
Quick Reference¶
| Operator | Use Case |
|---|---|
// |
Whole number division |
% |
Remainder |
>=, < |
Threshold checks |
math.isclose() |
Float comparisons |
and |
Both conditions required |
or |
Either condition sufficient |
not |
Flip boolean |
Lab Complete!
To double-check your work, the cell below will rerun all of the autograder tests.
grader.check_all()