UNB/ CS/ David Bremner/ tags/ python

This feed contains pages with tag "python".

Overview

The goal of the assignment is to develop a simple query language that lets the user select rows and columns from a CSV File, in effect treating it like database.

  • Make sure you commit and push all your work using coursegit before 16:30 on Friday November 27.

General Instructions

  • Every non-test function should have a docstring

  • Feel free to add docstrings for tests if you think they need explanation

  • Use list and dictionary comprehensions as much as reasonable.

  • Your code should pass all of the given tests, plus some of your own with different data. If you want, you can use some of the sample data from the US Government College Scorecard. I’ve selected some of the data into smaller files:

2013-1000.csv.gz

2014-1000.csv.gz

2015-1000.csv.gz

2014-100.csv.gz

2015-100.csv.gz

2013-100.csv.gz

Reading CSV Files

We will use the builtin Python CSV module to read CSV files.

def read_csv(filename):
    '''Read a CSV file, return list of rows'''
    import csv
    with open(filename,'rt',newline='') as f:
        reader = csv.reader(f, skipinitialspace=True)
        return [ row for row in reader ]

Save the following as “~/fcshome/assignments/A4/test1.csv”; we will use it several tests. You should also construct your own example CSV files and corresponding tests.

name, age, eye colour
Bob, 5, blue
Mary, 27, brown
Vij, 54, green

Here is a test to give you the idea of the returned data structure from read_csv.

def test_read_csv():
    assert read_csv('test1.csv') == [['name', 'age', 'eye colour'],
                                     ['Bob', '5', 'blue'],
                                     ['Mary', '27', 'brown'],
                                     ['Vij', '54', 'green']]

Parsing Headers

The first row most in most CSV files consists of column labels. We will use this to help the user access columns by name rather than by counting columns.

Write a function header_map that builds a dictionary from labels to column numbers.

table = read_csv('test1.csv')

def test_header_map_1():
    hmap = header_map(table[0])
    assert hmap == { 'name': 0, 'age': 1, 'eye colour': 2 }

Transforming rows into dictionaries

Sometimes it’s more convenient to work with rows of the table as dictionaries, rather than passing around the map of column labels everwhere. Write a function row2dict that takes the output from headermap, and a row, and returns a dictionary representing that row (column order is lost here, but that will be ok in our application).

def test_row2dict():
    hmap = header_map(table[0])
    assert row2dict(hmap, table[1]) == {'name': 'Bob', 'age': '5', 'eye colour': 'blue'}

Matching rows

We are going to write a simple query languge where each query is a 3-tuple (left, op, right), and op is one of =, <, and >. In the initial version, left and right are numbers or strings. Strings are interpreted as follows: if they are column labels, retrieve the value in that column; otherwise treat it as a literal string. With this in mind, write a function check_row that takes a row in dictionary form, and checks if it matches a query tuple.

def test_check_row():
    row = {'name': 'Bob', 'age': '5', 'eye colour': 'blue'}
    assert check_row(row, ('age', '=', 5))
    assert not check_row(row, ('eye colour', '=', 5))
    assert check_row(row, ('eye colour', '=', 'blue'))
    assert check_row(row, ('age', '>', 4))
    assert check_row(row, ('age', '<', 1000))

Extending the query language

Extend check_row so that it supports operations AND and OR. For these cases both left and right operands must be queries. Hint: this should only be a few more lines of code.

def test_check_row_logical():
    row = {'name': 'Bob', 'age': '5', 'eye colour': 'blue'}
    assert check_row(row, (('age', '=', 5),'OR',('eye colour', '=', 5)))
    assert not check_row(row, (('age', '=', 5),'AND',('eye colour', '=', 5)))

Filtering tables

Use you previously developed functions to impliment a function filter_table that selects certain rows of the table according to a query.

def test_filter_table1():
    assert filter_table(table,('age', '>', 0)) == [['name', 'age', 'eye colour'],
                                                   ['Bob', '5', 'blue'],
                                                   ['Mary', '27', 'brown'],
                                                   ['Vij', '54', 'green']]

    assert filter_table(table,('age', '<', 28)) == [['name', 'age', 'eye colour'],
                                                    ['Bob', '5', 'blue'],
                                                    ['Mary', '27', 'brown']]

    assert filter_table(table,('eye colour', '=', 'brown')) == [['name', 'age', 'eye colour'],
                                                                ['Mary', '27', 'brown']]

    assert filter_table(table,('name', '=', 'Vij')) == [['name', 'age', 'eye colour'],
                                                        ['Vij', '54', 'green']]


def test_filter_table2():
    assert filter_table(table,(('age', '>', 0),'AND',('age','>','26'))) == [['name', 'age', 'eye colour'],
                                                                            ['Mary', '27', 'brown'],
                                                                            ['Vij', '54', 'green']]


    assert filter_table(table,(('age', '<', 28),'AND',('age','>','26'))) == [['name', 'age', 'eye colour'],
                                                                             ['Mary', '27', 'brown']]

    assert filter_table(table,(('eye colour', '=', 'brown'),
                               'OR',
                               ('name','=','Vij'))) == [['name', 'age', 'eye colour'],
                                                        ['Mary', '27', 'brown'],
                                                        ['Vij', '54', 'green']]
Posted Tags: /tags/python
Lab 19
Posted Tags: /tags/python
Lab 18 / Python Quiz

Before the Lab

Study for the Python Quiz

Quiz

Time
50 minutes
Activity
Quiz

The first half of the lab will be a Python quiz


Getting started

Hello Go

Time
10 minutes
Activity
Demo
// Our first program will print the classic "hello world"
// message. Here's the full source code.
package main

import "fmt"

func main() {
    fmt.Println("hello world")
}

Running go code is a bit more complicated than the other languages we studied so far.

# To run the program, put the code in `hello-world.go` and
# use `go run`.
$ go run hello-world.go
hello world

# Sometimes we'll want to build our programs into
# binaries. We can do this using `go build`.
$ go build hello-world.go
$ ls
hello-world hello-world.go

# We can then execute the built binary directly.
$ ./hello-world
hello world

# Now that we can run and build basic Go programs, let's
# learn more about the language.

Loops

Time
20 minutes
Activity
Modify given example
// `for` is Go's only looping construct. Here are
// some basic types of `for` loops.

package main

import "fmt"

func main() {

    // The most basic type, with a single condition.
    i := 1
    for i <= 3 {
        fmt.Println(i)
        i = i + 1
    }

    // A classic initial/condition/after `for` loop.
    for j := 0; j < 3; j++ {
        fmt.Println(j)
    }

    // Another way of accomplishing the basic "do this
    // N times" iteration is `range` over an integer.
    for i := range 3 {
        fmt.Println("range", i)
    }

    // `for` without a condition will loop repeatedly
    // until you `break` out of the loop or `return` from
    // the enclosing function.
    for {
        fmt.Println("loop")
        break
    }

    // You can also `continue` to the next iteration of
    // the loop.
    for n := range 6 {
        if n%2 == 0 {
            continue
        }
        fmt.Println(n)
    }
}

Modify the above example so that the output of each loop is reversed. For those involving range, modify the Println statement.

% go run for.go
3
2
1
3
2
1
range 2
range 1
range 0
loop
5
3
1

Conditionals

Time
20 minutes
Activity
Synthesize program
// Branching with `if` and `else` in Go is
// straight-forward.

package main

import "fmt"

func main() {

    // Here's a basic example.
    if 7%2 == 0 {
        fmt.Println("7 is even")
    } else {
        fmt.Println("7 is odd")
    }

    // You can have an `if` statement without an else.
    if 8%4 == 0 {
        fmt.Println("8 is divisible by 4")
    }

    // Logical operators like `&&` and `||` are often
    // useful in conditions.
    if 8%2 == 0 || 7%2 == 0 {
        fmt.Println("either 8 or 7 are even")
    }

    // A statement can precede conditionals; any variables
    // declared in this statement are available in the current
    // and all subsequent branches.
    if num := 9; num < 0 {
        fmt.Println(num, "is negative")
    } else if num < 10 {
        fmt.Println(num, "has 1 digit")
    } else {
        fmt.Println(num, "has multiple digits")
    }
}

// Note that you don't need parentheses around conditions
// in Go, but that the braces are required.

Use the example above, along with a for loop, to write the "Fizzbuzz" example

% go run fizz-buzz.go
Fizzbuzz
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
Fizzbuzz
16
17
Fizz
19
Posted Tags: /tags/python
Lab 17

Before the Lab


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

Posted Tags: /tags/python
Lab 16

Before the Lab


Getting Started

List Comprehensions

Time
25 minutes
Activity
Write tests based on REPL session
import pytest
from report2 import read_portfolio
prices = {
        'GOOG' : 490.1,
        'AA' : 23.45,
        'CAT': 35.46,
        'IBM' : 91.1,
        'MSFT' : 34.23,
        'GE': 13.48,
    }

Note that the value test will need to be adjusted for a value of approximately 31167.10, since our price list is different from the one used in the book.

Higher order functions

Time
20 minutes
Activity
Assemble given pieces
def test_portfolio():
    portfolio = parse_csv('Data/portfolio.csv', types=[str, int, float])
    assert portfolio == [{'price': 32.2, 'name': 'AA', 'shares': 100},
                         {'price': 91.1, 'name': 'IBM', 'shares': 50},
                         {'price': 83.44, 'name': 'CAT', 'shares': 150},
                         {'price': 51.23, 'name': 'MSFT', 'shares': 200},
                         {'price': 40.37, 'name': 'GE', 'shares': 95},
                         {'price': 65.1, 'name': 'MSFT', 'shares': 50},
                         {'price': 70.44, 'name': 'IBM', 'shares': 100}]

def test_shares():
    shares_held = parse_csv('Data/portfolio.csv', select=['name', 'shares'], types=[str, int])
    assert shares_held == [{'name': 'AA', 'shares': 100}, {'name': 'IBM', 'shares': 50},
                           {'name': 'CAT', 'shares': 150}, {'name': 'MSFT', 'shares': 200},
                           {'name': 'GE', 'shares': 95}, {'name': 'MSFT', 'shares': 50},
                           {'name': 'IBM', 'shares': 100}]

Refactoring a function

Time
30 minutes
Activity
Refactor function to add feature
def test_tuple():
    prices = parse_csv('Data/prices.csv', types=[str,float], has_headers=False)
    assert prices == [('AA', 9.22), ('AXP', 24.85), ('BA', 44.85), ('BAC', 11.27),
                      ('C', 3.72), ('CAT', 35.46), ('CVX', 66.67), ('DD', 28.47),
                      ('DIS', 24.22), ('GE', 13.48), ('GM', 0.75), ('HD', 23.16),
                      ('HPQ', 34.35), ('IBM', 106.28), ('INTC', 15.72), ('JNJ', 55.16),
                      ('JPM', 36.9), ('KFT', 26.11), ('KO', 49.16), ('MCD', 58.99),
                      ('MMM', 57.1), ('MRK', 27.58), ('MSFT', 20.89), ('PFE', 15.19),
                      ('PG', 51.94), ('T', 24.79), ('UTX', 52.61), ('VZ', 29.26),
                      ('WMT', 49.74), ('XOM', 69.35)]

Raising exceptions

Time
20 minutes
Activity
Add error check
def test_exception():
    with pytest.raises(RuntimeError) as e_info:
        prices = parse_csv('Data/prices.csv', select=['name','price'], has_headers=False)
Posted Tags: /tags/python
Lab 15

Before the Lab


Getting Started

Dictionaries

Time
20 minutes
Activity
Individual programming, synthesis
def test_cost():
    d = parse_row(row)
    cost = compute_cost (d)
    assert cost == pytest.approx(3220.000,abs=0.00000001)

def test_d():
    d = parse_row(row)
    update_dict(d)
    assert d == {'name': 'AA', 'shares': 75, 'price':32.2, 'date': (6, 11, 2007),
                 'account': 12345}

Containers: read_portfolio

Time
20 minutes
Activity
Write function based on template
def test_read():
    portfolio = read_portfolio('Data/portfolio.csv')
    assert portfolio == \
        [('AA', 100, 32.2), ('IBM', 50, 91.1),
         ('CAT', 150, 83.44), ('MSFT', 200, 51.23),
         ('GE', 95, 40.37), ('MSFT', 50, 65.1), ('IBM', 100, 70.44)]

def test_total():
    portfolio = read_portfolio('Data/portfolio.csv')
    total = 0.0
    for name, shares, price in portfolio:
        total += shares*price
    assert total == pytest.approx(44671.15,abs=0.001)

Time
20 minutes
Activity
Modify results of previous exercise
def test_read():
    portfolio = read_portfolio('Data/portfolio.csv')
    assert portfolio == \
        [{'name': 'AA', 'shares': 100, 'price': 32.2}, {'name': 'IBM', 'shares': 50, 'price': 91.1},
         {'name': 'CAT', 'shares': 150, 'price': 83.44}, {'name': 'MSFT', 'shares': 200, 'price': 51.23},
         {'name': 'GE', 'shares': 95, 'price': 40.37}, {'name': 'MSFT', 'shares': 50, 'price': 65.1},
         {'name': 'IBM', 'shares': 100, 'price': 70.44}]

def test_total():
    portfolio = read_portfolio('Data/portfolio.csv')

    total = 0.0
    for s in portfolio:
        total += s['shares']*s['price']
    assert total == pytest.approx(44671.15,abs=0.001)

Sequences

Time
25 minutes
Activity
Convert REPL session to tests
def test_items():
    assert prices.items() == \
        [('GOOG', 490.1), ('AA', 23.45), ('IBM', 91.1), ('MSFT', 34.23)]
- Question: what is `list()` being used for in this section?
- Embed the following tests and make sure they pass
def test_zip():
    assert pricelist == \
        [(490.1, 'GOOG'), (23.45, 'AA'), (91.1, 'IBM'), (34.23, 'MSFT')]

def test_min_max():
    assert min(pricelist) == (23.45, 'AA')
    assert max(pricelist) == (490.1, 'GOOG')

Posted Tags: /tags/python
Lab 14

Before the Lab

Questions

Time
5 Minutes
Activity
Group discussion

Getting Started

- Download Work.zip and unzip in your newly created directory.

Pytest

Time
10 minutes
Activity
Demo
symbols = 'HPQ,AAPL,IBM,MSFT,YHOO,DOA,GOOG'
symlist = symbols.split(',')

def test_lookup0():
    assert symlist[0] == 'HPQ'

def test_lookup1():
    assert symlist[1] == 'AAPL'
[student@id414m22 L14]$ pytest listex.py
=================== test session starts ===================
platform linux -- Python 3.9.18, pytest-7.4.3, pluggy-1.3.0
rootdir: /home1/ugrad/student/cs2613/labs/L14
plugins: pylama-8.4.1, cov-4.1.0
collected 2 items

listex.py ..                                        [100%]

==================== 2 passed in 0.02s ====================

Lists and Pytest

Time
20 minutes
Activity
Individual programming from template

Functions and coverage

Time
20 minutes
Activity
Individual programming, modify previous solution

We have already been using python functions for pytest, without really thinking about how they work. In Part 1.7 of Practical Python, functions are explained.

def sumcount(n):
    '''
    Returns the sum of the first n integers
    '''
    total = 0
    while n > 0:
        total += n
        n -= 1
    return total

Files

Time
20 minutes
Activity
Individual programming, synthesis

Data types

Tuples

Time
20 minutes
Activity
Individual programming, synthesis

Before next lab

Read

Posted Tags: /tags/python
Indexing Debian's buildinfo

Introduction

Debian is currently collecting buildinfo but they are not very conveniently searchable. Eventually Chris Lamb's buildinfo.debian.net may solve this problem, but in the mean time, I decided to see how practical indexing the full set of buildinfo files is with sqlite.

Hack

  1. First you need a copy of the buildinfo files. This is currently about 2.6G, and unfortunately you need to be a debian developer to fetch it.

     $ rsync -avz mirror.ftp-master.debian.org:/srv/ftp-master.debian.org/buildinfo .
    
  2. Indexing takes about 15 minutes on my 5 year old machine (with an SSD). If you index all dependencies, you get a database of about 4G, probably because of my natural genius for database design. Restricting to debhelper and dh-elpa, it's about 17M.

     $ python3 index.py
    

    You need at least python3-debian installed

  3. Now you can do queries like

     $ sqlite3 depends.sqlite "select * from depends where depend='dh-elpa' and depend_version<='0106'"
    

    where 0106 is some adhoc normalization of 1.6

Conclusions

The version number hackery is pretty fragile, but good enough for my current purposes. A more serious limitation is that I don't currently have a nice (and you see how generous my definition of nice is) way of limiting to builds currently available e.g. in Debian unstable.

Posted Tags: /tags/python
Trivial example using python to hack ical

I could not find any nice examples of using the vobject class to filter an icalendar file. Here is what I got to work. I'm sure there is a nicer way. This strips all of the valarm subevents (reminders) from an icalendar file.

import vobject
import sys

cal=vobject.readOne(sys.stdin)

for ev in cal.vevent_list:
    if ev.contents.has_key(u'valarm'):
       del ev.contents[u'valarm']

print cal.serialize()
Posted Tags: /tags/python