Live coding exercises

Basic operations, control structure, operations (10/2-2021)

1.1 Print numbers 1 to 10.

1.2 Print the sum of a list of values.

1.3 Print the maximum in a list of values.

1.4 Count the number of occurrences of a character in a string, e.g. 'c' occours 4 times in 'abccbbacbabc'.

1.5 Find the largest number of consecutive identical characters in a string, e.g. for 'abbacccbaa' the answer is 3 because of 'ccc'.

1.6 Find the largest number of concecutive chars in a string that occure alphabetically, e.g. for 'abcxauefghvxuvw' the answer is 4 because of the substring 'efgh'.

1.7 Find the position of an element in a sorted list, e.g. that 7 is at position 3 in [-2, 1, 3, 7, 10, 12].

Lists, ranges, tuples, for, list-comprehensions, enumerate, zip (17/2-2021)

2.1 Given a list of even length, create a list where each consecutive pair of elements has been swapped, e.g. [1, 2, 3, 4, 5, 6] becomes [2, 1, 4, 3, 6, 5].

2.2 Convert a list of strings to a single nice string, e.g. ['A', 'B', 'C', 'D'] becomes 'A, B, C and D'.

2.3 Remove all odd numbers from a list, e.g. [2, 3, 7, 4, 3, 2, 6, 1, 8] becomes [2, 4, 2, 6, 8].

2.4 Given three lists of integers X, Y, Z, generate list of all tuples (x, y, z) where x is in X, y in Y, z in Z, and z = x + y.

2.5 Given two lists X and Y, find all pairs (i, j) where X[i] = Y[j].

Dictionaries and functions (24/2-2021)

3.1 Make a function print_words(words) that given a list of words words, prints each word on a separate line (in an arbitrary order).

3.2 Create a function print_words(words, indent=4) that given a list of words words, prints each word on a separate line (in an arbitrary order) with indent leading spaces. Indent should be an optional keyword argument.

3.3 Create a function longest(words) that giving a list of words returns a longest word, say the first if several words have the maximum length.

3.4 Create function longest(word1, word2, ...) to return the longest word of one or more arguments provided.

3.5 Create a function eliminate(text, words) that given a space separated text of words text, and a list of words words, returns the text with all occurences of words in words replaced by a corresponding number of *. E.g.

eliminate('Python Java and C are popular languages but Java and C ' 'are statically typed whereas Python is dynamically typed', ['java', 'c', 'statically'])

should return the string

'Python **** and * are popular languages but **** and * are ********** typed whereas Python is dynamically typed'

3.6 Modify the definition of eliminate so that it can be called as eliminate(text, word1, word2, ...)

3.7 Create a function rewrite(text, initial=[word,...], hide=[word,...], upper=[word,...]) where initial, hide, and upper are optional keyword arguments each containing a list of words where words in initial should be replace by only the first letter followed by *, words in hide all letters should be replaced by *, and words in upper should be converted to all upper case. E.g.

rewrite('Python rocks but Java sucks', initial=['sucks'], hide=['Java'], upper=['Python'])

should return

'PYTHON rocks but **** s****'

3.8 Write a method substitute(text, replace) where replace should contain a dictionary of (key, value) items, where keys are words that should be replaced by the corresponing value.

3.9 Implement rewrite(text, initial=[word,...], hide=[word,...], upper=[word,...]) using substitute(text, replace).

Recursion (3/3 - 2021)

4.1 Given two non-negative integers a and b, compute power(a, b) == a ** b using recursion, without using **, i.e. only using multiplication, division, addision and subtraction.

4.2 Convert a recursive tuple to a nicely indented string. E.g. dump(((1, 3), (5, (4, 6)))) could become

(
   (
      1,
      3
   ),
   (
      5,
      (
         4,
         6
      )
   )
)

similar to what you achieve for lists using

import json print(json.dumps([[1,3],[5,[4,6]]], indent=3))

4.3 Create a recursive function subsets(L, k) that given a list L and an integer k, returns a list of all subsets of L of size k. It is assumed all elements are distinct. E.g. subsets([1,2,3,4,5], 3) should return

[[3, 4, 5], [2, 4, 5], [2, 3, 5], [2, 3, 4], [1, 4, 5], [1, 3, 5], [1, 3, 4], [1, 2, 5], [1, 2, 4], [1, 2, 3]]

4.4 Create subsets(L, k) without using recursion.

Lambda, Classes and Objects (10/3 - 2021)

5.1 Given a list L of intergers, create a new list where all integers are incremented by one. E.g. for L = [3, 4, 5] you should create the list [4, 5, 6].

5.2 Sort a list of strings by the number of distinct characters (strings with the same number of distinct symbols can appear in any order).

5.3 Sort a list of strings by number of vovals.

5.4 Create a class Beverage to store information about a beverage. Create a __init__ method to be able to create a beverage object using:

CocaCola = Beverage(
  name = "Coca Cola",
  volume = 0.33,
  container = "Can",
  alcohol_percent = 0
)

or

HarboeBottle = Beverage('Harboe Pilsner', 0.33, 'Glass', 4.4)

Create methods __str__ to be able to print a Beverage object, and __le__ to be able to compare objects, e.g. just order them by name. Create a method total_alcohol return the total abount of alcohol in a beverage unit.

Class hierarchies, Exceptions and Files (17/3 - 2021)

6.1 Create a class Volume to represent a volume. The calls should have methods get_liter, get_imperial_oz, get_us_oz to return the volume in liters, imperial fluid ounces, and US fluid ounces.

Create a subclass Container of Volume that furthermore has an attribute material.

6.2 Create a function eval_function(f, values) that prints f(x) for all x in values. If the function raises an error for a value print "error" for this value.

6.3 Create a function create_pairs(X, Y) that given two lists X and Y returns the list of pairs [(X[0], Y[0]), (X[1], Y[1]), ...]. If the two lists have different length, raise a "ValueError" exception.

6.4 Find all occurences of "mathematic" in file cano.txt.

Documentation, Testing, Decorators (24/3 - 2021)

7.1 Create a method rank(x, L) that returns the number of elements in a sorted list of integers L that are less than or equal to x.

7.2 Create a decorator add_noise to add random noise to the output of a function returning a float.

Dynamic programming, Jupyter notebook (7/4 - 2021)

8.1 Bitonic euclidean traveling-salesman problem

Given a set of n points in the plane, we wish to find the shortest closed bitonic tour that connects all n points, that is, tours that start at the leftmost point, go strictly rightward to the rightmost point, and then go strictly leftward back to the starting point. Give a dynamic programming solution assuming no two points have the same x-coordinate.

Note this is Problem 15-3 from "Introduction to Algorithms", Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein, page 405, The MIT Press, 2009.

Numpy (14/4 - 2021)

9.1 Compare the running time of working with Python lists of integers and Numpy arrays of integers.

9.2 Use pyplot to plot a Numpy array.

9.3 Download MNIST pictures (from Tensorflow/Keras) as Numpy arrays

9.4 Represent a graph using a Numpy array.

Iterators and Generators (21/4 - 2021)

10.1 Create an iterable class arange(start, end, step) to return values start, start + step, start + 2 * step, ...

10.2 Generator expression to create powers of two.

10.3 Create generator g(n) to generate all pairs (x, y) where x and y are from range(n) and x + y is not divisble by 3.

Iterators and Generators (21/4 - 2021)

11.1 Create an iterable class arange(start, end, step) to return values start, start + step, start + 2 * step, ...

11.2 Generator epxression to create powers of two.

11.3 Create generator g(n) to generate all pairs (x, y) where x and y are from range(n) and x + y is not divisble by 3.

Text (28/4 - 2021)

12.1 Read and write a CSV file containing:

artist,song,length
ZZ Top,La Grange,3:50
Iron Butterfly,In-A-Gadda-Da-Vida,17:04
Led Zeppelin,Whole Lotta Love,5:33

12.2 Save the following to a JSON file:

[ {'id': 42, 'value': 'Something exciting'}, {'value': 'Also exciting news', 'id': 7} ]

12.3 XML - Open Street Map

Download a small map from www.openstreetmap.org as XML and plot it using matplotlib.

12.4 Read and write a CSV file containing:

artist,song,length
ZZ Top,La Grange,3:50
Iron Butterfly,In-A-Gadda-Da-Vida,17:04
Led Zeppelin,Whole Lotta Love,5:33

12.5 Save the following to a JSON file:

[ {'id': 42, 'value': 'Something exciting'}, {'value': 'Also exciting news', 'id': 7} ]

12.6 XML - Open Street Map

Download a small map from www.openstreetmap.org as XML and plot it using matplotlib.

Pandas (5/5-2021)

13.1 Load csv file with major cities from https://datahub.io/core/world-cities into a Pandas dataframe.

GUI / tkinter (12/5-2021)

14.1 Create a GUI using tkinter to interactively draw points and visualize the minimum enclosing circle (as computed in the optimization lecture using scipy.optimize.minimize).

Note: The circle found using minimize might not be smallest possible, since minimize is not guaranteed to find the find the minimum. For (more complicated) algorithms guaranteed to find a minimum enclosing circle see https://en.wikipedia.org/wiki/Smallest-circle_problem.

Final lecture (19/5-2021)

In this lecture we will go over the course evaluation and look at the exam.