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 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

A common built in data structure used in Python for lists of a fixed size are called tuples, which are created by wrapping multiple values, separated by commas, in parentheses, e.g.:

TUPLE_EXAMPLE = ("hello", 2000)

They can have arbitrary size, but are not mutable. One common use for them is to allow functions to return multiple values -- you can do this by returning a tuple with values, e.g.,:

return (one_val, another_val, a_third_val)

This pattern is so common, that you can leave out the paretheses in this case (and several others), as Python can infer that you mean to create a tuple. As in:

return one_val, another_val, a_third_val

When you call a function that returns a tuple, you can "unpack" the result by either writing the tuple syntax with variables:

(a,b,c) = my_function()

(assuming my_function returned a tuple with three values, this would add a, b, and c to the program directory with the three corresponding values).

This, too, can be done with the paretheses inferred, as:

a,b,c = my_function()

With all of that said -- please design a function longest_word_info that finds the longest string in a list and return both the string and its length.