Skip to main content

Lab 9 -- From Pyret to Python

Skills: 8

The goal of this lab will be to familiarize yourself with basic Python functions. (NOTE: is this lab too long?)

Problem 1

Part A

Convert the given Pyret function into Python.

fun book-cost(num-books :: Number, hardcover :: Boolean) -> Number:
doc: "each paperback costs $12, while hardcover costs $25"
if hardcover:
num-books * 25
else:
num-books * 12
end
end

Your code:

def book_cost(num_books: int, hardcover: bool) -> float:
"""each paperback costs $12, while hardcover costs $25"""
# YOUR CODE HERE
pass

Part B

Write pytest test cases for your book_cost function:

import pytest

def test_book_cost():
# YOUR TEST CASES HERE
pass

Part C

Write a Python function letter_grade that assigns letter grades based on numeric scores:

  • 90-100: "A"
  • 80-89: "B"
  • 70-79: "C"
  • 60-69: "D"
  • Below 60: "F"

Problem 2

Part A

Design a function c_to_f that transforms a list of temperatures from Celsius to Fahrenheit, using the formula F = C * 9/5 + 32. (Hint: a list abstraction may be helpful here!)

Part B

Design a function long_words_upper that, given a list of words (Strings), finds all words longer than 4 characters and convert them to uppercase. (Hint: map and filter may be helpful here!)

Problem 3

You may NOT use list abstractions for the following problems.

Part A

Write a function sum_positives that sums only the positive numbers in a list.

Part B

Design a function longest_word_info that finds the longest string in a list and return both the string and its length.