3.10 Lists
- Code Runner Challenge
- Code Runner Challenge
- Code Runner Challenge
- Code Runner Challenge
Code Runner Challenge
popcorn hack 1
View IPYNB Source
# CODE_RUNNER: popcorn hack 1
print("My guess is pizza, ramen, 4, ramen")
foods = ["pizza", "sushi", "tacos", "ramen"]
print(foods[0])
print(foods[len(foods) - 1])
print(len(foods))
print(foods[3])
Lines: 1
Characters: 0
Output
Click "Run" in code control panel to see output ...
Code Runner Challenge
popcorn hack 2
View IPYNB Source
# CODE_RUNNER: popcorn hack 2
numbers = [7, 6, 8, 5, 7, 9]
# 1. Calculate the sum using a for loop
total_sum = 0
for num in numbers:
total_sum += num
print("Sum:", total_sum)
# 2. Calculate the average using the sum and length of the list
average = total_sum / len(numbers)
print("Average:", average)
Lines: 1
Characters: 0
Output
Click "Run" in code control panel to see output ...
Code Runner Challenge
popcorn hack 3
View IPYNB Source
# CODE_RUNNER: popcorn hack 3
seasons = ["winter", "summer", "fall", "summer", "spring", "summer", "fall"] # use real class data
frequency = {}
for season in seasons:
if season in frequency:
frequency[season] += 1
else:
frequency[season] = 1
# 1. Build a list of seasons with 2 or more votes
popular = []
for season, count in frequency.items():
if count >= 2:
popular.append(season)
# 2. Print that list
print(popular)
Lines: 1
Characters: 0
Output
Click "Run" in code control panel to see output ...
Code Runner Challenge
homework
View IPYNB Source
# CODE_RUNNER: homework
donations_by_item = ["blankets", "socks", "blankets", "water", "socks", "blankets",
"meals", "socks", "blankets", "water", "blankets", "socks"]
costs = [2, 3, 2, 4, 3, 2, 1, 3, 2, 4, 2, 3]
# LESSON 1 - indexing
# 1. Print how many donations were made
print("Total donations made:", len(donations_by_item))
# 2. Print the last donation using indexing
print("Last donation:", donations_by_item[-1])
# LESSON 2 - sum and average
# 3. Use a loop to total costs (do NOT use sum())
total_cost = 0
for cost in costs:
total_cost += cost
# 4. Print "Total: <total>" and "Average: <average>" as integers
average_cost = total_cost / len(costs)
print("Total:", int(total_cost))
print("Average:", int(average_cost))
# LESSON 3 - count and filter
# 5. Build a frequency dictionary of donations_by_item and print it
donation_frequency = {}
for item in donations_by_item:
if item in donation_frequency:
donation_frequency[item] += 1
else:
donation_frequency[item] = 1
print("Frequency Dictionary:", donation_frequency)
# 6. Build a list of items with 3 or more donations and print it
frequent_items = []
for item, count in donation_frequency.items():
if count >= 3:
frequent_items.append(item)
print("Items with 3 or more donations:", frequent_items)
Lines: 1
Characters: 0
Output
Click "Run" in code control panel to see output ...