Lists HW
Lists
Popcorn Hack 1: Indexing
# Lists Popcorn 1 - predict, run, fix the crash
# Predictions:
# print(items_needed[0]) -> blankets
# print(items_needed[-1]) -> meals
# print(len(items_needed)) -> 4
# print(items_needed[3]) -> meals
items_needed = ["blankets", "socks", "water", "meals"]
print(items_needed[0])
print(items_needed[-1])
print(len(items_needed))
print(items_needed[3])
blankets
meals
4
meals
Popcorn Hack 2: Sum and Average
# Lists Popcorn 2
volunteer_hours = [7, 6, 8, 5, 7, 9]
if len(volunteer_hours) == 0:
print("No data yet")
else:
total = 0
for hours in volunteer_hours:
total += hours
average = total / len(volunteer_hours)
print(total)
print(average)
42
7.0
Popcorn Hack 3: Count and Filter
# Lists Popcorn 3 - count then filter
items_requested = ["blankets", "socks", "meals", "socks", "water", "socks", "meals"]
frequency = {}
for item in items_requested:
if item in frequency:
frequency[item] += 1
else:
frequency[item] = 1
popular = []
for item in frequency:
if frequency[item] >= 2:
popular.append(item)
print(frequency)
print(popular)
{'blankets': 1, 'socks': 3, 'meals': 2, 'water': 1}
['socks', 'meals']
Homework Hack: Combined Dataset
# Lists Homework - indexing, accumulator, count and filter on one dataset
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
print(len(donations_by_item))
print(donations_by_item[-1])
# LESSON 2 - sum and average
total = 0
for cost in costs:
total += cost
average = total / len(costs)
print(f"Total: {int(total)}")
print(f"Average: {int(average)}")
# LESSON 3 - count and filter
frequency = {}
for item in donations_by_item:
if item in frequency:
frequency[item] += 1
else:
frequency[item] = 1
print(frequency)
popular = []
for item in frequency:
if frequency[item] >= 3:
popular.append(item)
print(popular)
12
socks
Total: 31
Average: 2
{'blankets': 5, 'socks': 4, 'water': 2, 'meals': 1}
['blankets', 'socks']