Due at 11:59:59 pm on Thursday, 11/12/2019.

Starter Files

Download lab08.zip. Inside the archive, you will find starter files for the questions in this lab, along with a copy of the OK autograder.

Submission

By the end of this lab, you should have submitted the lab with python3 ok --submit. You may submit more than once before the deadline; only the final submission will be graded. Check that you have successfully submitted your code on okpy.org. See this article for more instructions on okpy and submitting assignments.

  • Submit the lab08.py file to ok.

OOP terminology

Object-oriented programming (OOP) is a style of programming that allows you to think of code in terms of "objects." Here's an example of a Car class:

class Car(object):
    num_wheels = 4
    gas = 30
    headlights = 2
    size = 'Tiny'

    def __init__(self, make, model):
        self.make = make
        self.model = model
        self.color = 'No color yet. You need to paint me.'
        self.wheels = Car.num_wheels
        self.gas = Car.gas

    def paint(self, color):
        self.color = color
        return self.make + ' ' + self.model + ' is now ' + color

    def drive(self):
        if self.wheels < Car.num_wheels or self.gas <= 0:
            return 'Cannot drive!'
        self.gas -= 10
        return self.make + ' ' + self.model + ' goes vroom!'

    def pop_tire(self):
        if self.wheels > 0:
            self.wheels -= 1

    def fill_gas(self):
        self.gas += 20
        return 'Gas level: ' + str(self.gas)

Here's some terminology:

  • class: a blueprint for how to build a certain type of object. The Car class (shown above) describes the behavior and data that all Car objects have.
  • instance: a particular occurrence of a class. In Python, we create instances of a class like this:

    >>> my_car = Car('Tesla', 'Model S')

    my_car is an instance of the Car class.

  • attribute or field: a variable that belongs to the class. Think of an attribute as a quality of the object: cars have wheels and size, so we have given our Car class self.wheels and self.size attributes. We can access attributes using dot notation:

    >>> my_car.size
    'Tiny'
    >>> my_car.wheels
    4
  • method: Methods are just like normal functions, except that they are tied to an instance or a class. Think of a method as a "verb" of the class: cars can drive and also pop their tires, so we have given our Car class the methods drive and pop_tire. We call methods using dot notation:

    >>> my_car = Car('Tesla', 'Model S')
    >>> my_car.drive()
    'Tesla Model S goes vroom!'
  • constructor: As with data abstraction, constructors describe how to build an instance of the class. Most classes have a constructor. In Python, the constructor of the class defined as __init__. For example, here is the Car class's constructor:

    def __init__(self, make, model):
            self.make = make
            self.model = model
            self.color = 'No color yet. You need to paint me.'
            self.wheels = Car.num_wheels
            self.gas = Car.gas

    The constructor takes in two arguments, make and model. As you can see, the constructor also creates the self.color, self.wheels and self.gas attributes.

  • self: in Python, self is the first parameter for many methods (in this class, we will only use methods whose first parameter is self). When a method is called, self is bound to an instance of the class. For example:

    >>> my_car = Car('Tesla', 'Model S')
    >>> my_car.drive()

    Notice that the drive method takes in self as an argument, but it looks like we didn't pass one in! This is because the dot notation implicitly passes in car as self for us.

Use OK to test your knowledge with the following What would Python print questions:

python3 ok -q car -u

Keyboard

Question 1: Keyboard

We'd like to create a Keyboard class that takes in an arbitrary number of Buttons and stores these Buttons in a dictionary. The keys in the dictionary will be ints that represent the position on the Keyboard, and the values will be the respective Button. Fill out the methods in the Keyboard class according to each description, using the doctests as a reference for the behavior of a Keyboard.

class Keyboard:
    """A Keyboard takes in an arbitrary amount of buttons, and has a
    dictionary of positions as keys, and Buttons as values.

    >>> b1 = Button(0, "H")
    >>> b2 = Button(1, "I")
    >>> k = Keyboard(b1, b2)
    >>> k.buttons[0].key
    'H'
    >>> k.press(1)
    'I'
    >>> k.typing([0, 1])
    'HI'
    >>> k.typing([1, 0])
    'IH'
    >>> b1.pressed
    2
    >>> b2.pressed
    3
    """

    def __init__(self, *args):
"*** YOUR CODE HERE ***"
self.buttons = {} for button in args: self.buttons[button.pos] = button
def press(self, info): """Takes in a position of the button pressed, and returns that button's output"""
"*** YOUR CODE HERE ***"
if info in self.buttons.keys(): b = self.buttons[info] b.pressed += 1 return b.key return ''
def typing(self, typing_input): """Takes in a list of positions of buttons pressed, and returns the total output"""
"*** YOUR CODE HERE ***"
accumulate = '' for pos in typing_input: accumulate+=self.press(pos) return accumulate
class Button: def __init__(self, pos, key): self.pos = pos self.key = key self.pressed = 0

Use OK to test your code:

python3 ok -q Keyboard

Table

In this lab, you will implement a version of the Table object from Data 8, that we are calling T88ble, appropriately pronounced T-88-bel. We aren't going to make you implement every single function, but we have table.select()ed the functions table.where(difficulty, are.below(insane)) and table.where(concepts, are.equal_to(relevant)).

Notice that we are representing tables here as a list of rows.

Question 2: Basic

Complete the num_rows, num_cols, and labels functions according to the docstrings.

    def num_rows(self):
        """
        Compute the number of rows in a table.

        >>> simple_table = T88ble(simple_table_rows, simple_table_labels)
        >>> simple_table.num_rows()
        2
        >>> longer_table = T88ble(longer_table_rows, longer_table_labels)
        >>> longer_table.num_rows()
        3
        """
"*** YOUR CODE HERE ***"
return len(self.rows)
def num_cols(self): """ Compute the number of cols in a table. >>> simple_table = T88ble(simple_table_rows, simple_table_labels) >>> simple_table.num_cols() 2 >>> longer_table = T88ble(longer_table_rows, longer_table_labels) >>> longer_table.num_cols() 5 """
"*** YOUR CODE HERE ***"
return len(self.rows[0])
def labels(self): """ Lists the column labels in a table. >>> simple_table = T88ble(simple_table_rows, simple_table_labels) >>> simple_table.labels() ['Flavor', 'Price'] >>> longer_table = T88ble(longer_table_rows, longer_table_labels) >>> longer_table.labels() ['Year', 'Bread price', 'Eggs price', 'Average tank of gas', 'Rent per day'] """
"*** YOUR CODE HERE ***"
return self.column_labels

Use OK to test your code:

python3 ok -q T88ble.num_rows

Use OK to test your code:

python3 ok -q T88ble.num_cols

Use OK to test your code:

python3 ok -q T88ble.labels

Question 3: Column Methods

Complete the column, select, and with_column functions according to the docstrings.

You might find the list.index(value) function to be particularly useful for this problem. Check out the python docs here

    def column(self, label):
        """
        Returns the values of the column represented by label.

        >>> simple_table = T88ble(simple_table_rows, simple_table_labels)
        >>> simple_table.column("Flavor")
        ['chocolate', 'vanilla']
        >>> longer_table = T88ble(longer_table_rows, longer_table_labels)
        >>> longer_table.column("Eggs price")
        [1.5, 2.5, 4]
        >>> longer_table
        ['Year', 'Bread price', 'Eggs price', 'Average tank of gas', 'Rent per day']
        [1990, 1, 1.5, 12, 7]
        [2000, 2, 2.5, 25, 10]
        [2010, 5, 4, 70, 36]
        """
"*** YOUR CODE HERE ***"
label_index = self.labels().index(label) return [row[label_index] for row in self.rows]
def with_column(self, label, values): """ Returns a new table with an additional or replaced column. label is a string for the name of a column, values is an list >>> longer_table = T88ble(longer_table_rows, longer_table_labels) >>> longer_table.with_column('Inflation rate', [i for i in range(longer_table.num_rows())]) ['Year', 'Bread price', 'Eggs price', 'Average tank of gas', 'Rent per day', 'Inflation rate'] [1990, 1, 1.5, 12, 7, 0] [2000, 2, 2.5, 25, 10, 1] [2010, 5, 4, 70, 36, 2] >>> longer_table ['Year', 'Bread price', 'Eggs price', 'Average tank of gas', 'Rent per day'] [1990, 1, 1.5, 12, 7] [2000, 2, 2.5, 25, 10] [2010, 5, 4, 70, 36] """
"*** YOUR CODE HERE ***"
new_rows = [self.rows[i][:] + [values[i]] for i in range(self.num_rows())] new_labels = self.labels()[:] + [label] return T88ble(new_rows, new_labels)
def select(self, labels): """ Create a copy of a table with only some of the columns, reffered to by the list of labels. >>> simple_table = T88ble(simple_table_rows, simple_table_labels) >>> simple_table.select(["Flavor"]) ['Flavor'] ['chocolate'] ['vanilla'] >>> simple_table ['Flavor', 'Price'] ['chocolate', 2] ['vanilla', 1] >>> longer_table = T88ble(longer_table_rows, longer_table_labels) >>> longer_table.select(['Year', 'Average tank of gas']) ['Year', 'Average tank of gas'] [1990, 12] [2000, 25] [2010, 70] >>> longer_table ['Year', 'Bread price', 'Eggs price', 'Average tank of gas', 'Rent per day'] [1990, 1, 1.5, 12, 7] [2000, 2, 2.5, 25, 10] [2010, 5, 4, 70, 36] """
"*** YOUR CODE HERE ***"
label_indices = [self.labels().index(label) for label in labels] new_rows = [[row[i] for i in label_indices] for row in self.rows] return T88ble(new_rows, labels)

Use OK to test your code:

python3 ok -q T88ble.column

Use OK to test your code:

python3 ok -q T88ble.with_column

Use OK to test your code:

python3 ok -q T88ble.select

Question 4: Sort

Complete the sort function according to the docstring.

You might find the sorted method to be very useful for this question. sorted can take in a key = lambda... just like the min function from the project. Check out the python docs here

    def sort(self, label, descending=True):
        """
        Create a copy of a table sorted by the values in a column.
        Defaults to ascending order unless descending = True is included.

        >>> longer_table = T88ble(longer_table_rows, longer_table_labels)
        >>> longer_table.sort("Year")
        ['Year', 'Bread price', 'Eggs price', 'Average tank of gas', 'Rent per day']
        [2010, 5, 4, 70, 36]
        [2000, 2, 2.5, 25, 10]
        [1990, 1, 1.5, 12, 7]
        >>> longer_table
        ['Year', 'Bread price', 'Eggs price', 'Average tank of gas', 'Rent per day']
        [1990, 1, 1.5, 12, 7]
        [2000, 2, 2.5, 25, 10]
        [2010, 5, 4, 70, 36]

        >>> simple_table = T88ble(simple_table_rows, simple_table_labels)
        >>> simple_table.sort("Price", descending=False)
        ['Flavor', 'Price']
        ['vanilla', 1]
        ['chocolate', 2]
        >>> simple_table
        ['Flavor', 'Price']
        ['chocolate', 2]
        ['vanilla', 1]

        """
"*** YOUR CODE HERE ***"
label_index = self.labels().index(label) new_rows = sorted(self.rows[:], key=lambda x: x[label_index], reverse = descending) return T88ble(new_rows, self.labels())

Use OK to test your code:

python3 ok -q T88ble.sort

Question 5: Where

Complete the where function according to the docstring.

    def where(self, label, filter_fn):
        """
        Create a copy of a table with only the rows that match a filter function.

        >>> def above(x):
        ...     return lambda y: y > x
        ...
        >>> longer_table = T88ble(longer_table_rows, longer_table_labels)
        >>> longer_table.where('Eggs price', above(2))
        ['Year', 'Bread price', 'Eggs price', 'Average tank of gas', 'Rent per day']
        [2000, 2, 2.5, 25, 10]
        [2010, 5, 4, 70, 36]
        >>> longer_table
        ['Year', 'Bread price', 'Eggs price', 'Average tank of gas', 'Rent per day']
        [1990, 1, 1.5, 12, 7]
        [2000, 2, 2.5, 25, 10]
        [2010, 5, 4, 70, 36]
        """
"*** YOUR CODE HERE ***"
label_index = self.labels().index(label) new_rows = [row[:] for row in self.rows if filter_fn(row[label_index])] return T88ble(new_rows, self.labels())

Use OK to test your code:

python3 ok -q T88ble.where