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.

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 test cases for your book_cost function:

import pytest

def test_book_cost():
# YOUR TEST CASES HERE
pass

Part C

Design 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

Convert the given Pyret function into Python. (string-length is len in Python.)

fun longer(s1 :: String, s2 :: String) -> String:
doc: "the longer of the two strings; if they are the same length, the first"
if string-length(s1) >= string-length(s2):
s1
else:
s2
end
end

Your code:

def longer(s1: str, s2: str) -> str:
"""the longer of the two strings; if they are the same length, the first"""
# YOUR CODE HERE
pass

Part B

Write test cases for your longer function.

def test_longer():
# YOUR TEST CASES HERE
pass

Part C

Design a Python function clamp(n, lo, hi) that returns n, except it must not go below lo or above hi. So clamp(3, 0, 10) is 3, clamp(-2, 0, 10) is 0, and clamp(15, 0, 10) is 10.

You may assume lo is less than or equal to hi.