Print the result
- Algorithms course
- Beginner
- Lesson 36/80
- 4 min
Print the sorted price list.
Compute average
In the final step we add average_price(prices). It computes and prints the average of sorted prices.
It sorts the prices, sums them, then divides by the count. This gives the average price.
Project complete
You now have a working price sorting application: init_prices gives the array, sort_prices sorts, print_sorted prints, average_price finds the average.
Each function was built on top of the previous one. This is the cumulative approach used in real-world software development.
Practice Compute average
Write average_price(prices). Print the average of sorted prices. Call average_price(init_prices()) to print 49.
Starter code
def init_prices():
# Return price array
return [99, 45, 12, 67, 23]
def sort_prices(prices):
# Sort
n = len(prices)
for i in range(n - 1):
min_idx = i
for j in range(i + 1, n):
if prices[j] < prices[min_idx]:
min_idx = j
prices[i], prices[min_idx] = prices[min_idx], prices[i]
return prices
def print_sorted(prices):
# Sort and print
sorted_prices = sort_prices(prices)
for p in sorted_prices:
print(p)
def average_price(prices):
# Print averageSample solution
def init_prices():
# Return price array
return [99, 45, 12, 67, 23]
def sort_prices(prices):
# Sort
n = len(prices)
for i in range(n - 1):
min_idx = i
for j in range(i + 1, n):
if prices[j] < prices[min_idx]:
min_idx = j
prices[i], prices[min_idx] = prices[min_idx], prices[i]
return prices
def print_sorted(prices):
# Sort and print
sorted_prices = sort_prices(prices)
for p in sorted_prices:
print(p)
def average_price(prices):
# Print average
sp = sort_prices(prices)
total = 0
for p in sp:
total = total + p
print(total // len(sp))
average_price(init_prices())Expected output
49
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Print the result: match the terms
| Term | Meaning |
|---|---|
average_price |
Average |
sort_prices |
Sort |
total |
Sum |
print |
2 What does average_price return?
- Total price
- Average price Correct answer
- Largest price
- Smallest price
Explanation: It returns the average price.
3 Average
Ortalama = toplam / ____Average = sum /
Ortalama = toplam / len(sp)Average = sum /
Explanation: len(sp) is right.