Lab

4.4.2. Lab#

  • Use this lab to practice the chapter’s coding skills in runnable Python code.

  • Sign in from the account menu before you start working on the lab.

  • Launch Live Code (the rocket) to write and run code in the coding cells.

  • Multiple submissions are allowed. The highest score is kept.

### Question 1: Default parameters
# Write format_invoice(amount, currency="USD") that returns a string like
# "120.00 USD", formatting amount to 2 decimal places.
# Call it once without currency and once passing currency="EUR".
# Print exactly these two lines:
# 120.00 USD
# 85.50 EUR
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
def format_invoice(amount, currency="USD"):
    return f"{amount:.2f} {currency}"

invoice1 = format_invoice(120)
invoice2 = format_invoice(85.5, "EUR")

print(invoice1)
print(invoice2)
120.00 USD
85.50 EUR
### Question 2: Flexible arguments with *args and **kwargs
# Write trip_summary(destination, *stops, **details) that returns a dictionary
# with keys "destination", "stops" (a tuple), and "details" (a dict).
# Call it with destination="Denver", stops "Omaha" and "Boulder",
# and keyword details days=5, budget=900. Print the returned dictionary.
# Print exactly this line:
# {'destination': 'Denver', 'stops': ('Omaha', 'Boulder'), 'details': {'days': 5, 'budget': 900}}
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
def trip_summary(destination, *stops, **details):
    return {
        "destination": destination,
        "stops": stops,
        "details": details,
    }

summary = trip_summary("Denver", "Omaha", "Boulder", days=5, budget=900)
print(summary)
{'destination': 'Denver', 'stops': ('Omaha', 'Boulder'), 'details': {'days': 5, 'budget': 900}}
### Question 3: Function composition for a BMI report
# Write three functions:
# 1. compute_bmi(weight_kg, height_m): returns weight_kg / height_m ** 2
# 2. bmi_category(bmi): returns "underweight" if bmi < 18.5,
#    "healthy" if bmi < 25, otherwise "above healthy range"
# 3. bmi_report(weight_kg, height_m): calls both and returns
#    "BMI is X.X (category)", with bmi rounded to 1 decimal place
# Call bmi_report(70, 1.75) and bmi_report(90, 1.70), printing each result.
# Print exactly these two lines:
# BMI is 22.9 (healthy)
# BMI is 31.1 (above healthy range)
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
def compute_bmi(weight_kg, height_m):
    return weight_kg / height_m ** 2

def bmi_category(bmi):
    if bmi < 18.5:
        return "underweight"
    if bmi < 25:
        return "healthy"
    return "above healthy range"

def bmi_report(weight_kg, height_m):
    bmi = compute_bmi(weight_kg, height_m)
    category = bmi_category(bmi)
    return f"BMI is {bmi:.1f} ({category})"

print(bmi_report(70, 1.75))
print(bmi_report(90, 1.70))
BMI is 22.9 (healthy)
BMI is 31.1 (above healthy range)
### Question 4: Pure function refactor
# apply_discount_in_place(prices, percent) below mutates its list argument.
# Write a pure version, apply_discount(prices, percent), that returns a NEW
# list of prices reduced by percent (each rounded to 2 decimals) without
# changing the original list.
# Call apply_discount(cart_prices, 10) and store the result in discounted.
# Print cart_prices, then discounted.
# Print exactly these two lines:
# [40.0, 15.0, 60.0]
# [36.0, 13.5, 54.0]
def apply_discount_in_place(prices, percent):
    for i in range(len(prices)):
        prices[i] = round(prices[i] * (1 - percent / 100), 2)

cart_prices = [40.0, 15.0, 60.0]
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
def apply_discount_in_place(prices, percent):
    for i in range(len(prices)):
        prices[i] = round(prices[i] * (1 - percent / 100), 2)

def apply_discount(prices, percent):
    new_prices = []
    for price in prices:
        new_prices.append(round(price * (1 - percent / 100), 2))
    return new_prices

cart_prices = [40.0, 15.0, 60.0]
discounted = apply_discount(cart_prices, 10)

print(cart_prices)
print(discounted)
[40.0, 15.0, 60.0]
[36.0, 13.5, 54.0]
### Question 5: Recursion over a list
# Write list_product(nums), which returns the product of all numbers in nums,
# using recursion. The product of an empty list is 1; otherwise multiply the
# first item by the recursive product of the rest of the list.
# Print exactly these two lines:
# 24
# 5
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
def list_product(nums):
    if not nums:
        return 1
    return nums[0] * list_product(nums[1:])

print(list_product([2, 3, 4]))
print(list_product([5]))
24
5