UNB/ CS/ David Bremner/ teaching/ cs2613/ labs/ Lab 17

Before the Lab

Read


Getting started


Questions

Time
10 minutes
Activity
Q&A

Modules

Time
20 minutes
Activity
Refactor existing code to to reuse a function.
def test_prices():
    portfolio = read_portfolio('Data/portfolio.csv')

    prices = {  s['name']: s['price'] for s in portfolio }
    assert prices['AA'] == pytest.approx(32.2,abs=0.001)
    assert prices['GE'] == pytest.approx(40.37,abs=0.001)

Methods

Time
20 minutes
Activity
Write accessor and mutator methods.

def test_cost2():
    s = Stock('GOOG', 100, 490.10)
    assert s.cost() == pytest.approx(49010.0,0.001)

def test_sell():
    s = Stock('GOOG', 100, 490.10)
    s.sell(25)
    assert s.shares == 75
    assert s.cost() == pytest.approx(36757.5, 0.001)

Special Methods

Time
25 minutes
Activity
Code to test, learn about "dunder" methods.
def test_repr():
    goog = Stock('GOOG', 100, 490.1)
    assert repr(goog) == "Stock('GOOG', 100, 490.1)"

Tables

Time
25 minutes
Activity
Code to test, learn about "dunder" methods.

Write a Python class Table whose constructor takes a list of strings selecting columns, and a list of dictionaries corresponding to rows. You should support the str function by implementing the appropriate "dunder" method. Your method should return a string of the formatted table with the given columns selected.

  def make_abm():
      return [{'name': 'Alice', 'hobby': 'Kendo', 'age': 21},
              {'name': 'Bob', 'hobby': 'Skiing', 'age': 23},
              {'name': 'Mallory', 'hobby': 'Cryptanalysis', 'age': 30}]

  def test_strings():
      rows=make_abm()
      table = Table(['name', 'hobby'], rows)
      assert str(table) == \
          'name      hobby     \n' + \
          'Alice     Kendo     \n'+ \
          'Bob       Skiing    \n' + \
          'Mallory   Cryptanalysis'

  def test_strings_numbers():
      rows=make_abm()
      table = Table(['name', 'age'], rows)
      assert str(table) == \
          'name      age       \n' + \
          'Alice     21        \n'+ \
          'Bob       23        \n'+ \
          'Mallory   30        '

Before next lab

Study for the Python Quiz