FIT1045 Algorithms and Programming Fundamentals in Python - Workshop 5
FIT1045 Algorithms and Programming Fundamentals in Python - Workshop 5
Workshop 5.
Objectives
After this workshop, you should be able to:
Read, write, and create files using Python.
Represent graphs in Python.
Reason about the selection sort algorithm.
MARKS: Marks for this workshop will be determined by the tester.
tutorial/inputoutput.html#reading-and-writing-files
1
Task 1: Reading files
Part A - Read a word
Implement a function word from file(file) that takes a file as input and returns the first word in the file.
Example: calling nested int list from file(‘files/task1B.txt’ returns [[2,1,3], [3,1,3], [2,9]].
Note: The given path may contain vertices that are not in the graph. In such a case the function call should
return False, but be wary as certain implementations will throw errors under this case.
0 1 2
3 4 5
2
For example:
>>> grid_graph(2, 3)
[[0, 1, 0, 1, 0, 0],
[1, 0, 1, 0, 1, 0],
[0, 0, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0],
[0, 1, 0, 0, 0, 1],
[0, 0, 1, 0, 1, 0]]
Hints: Think about appropriate ways to decompose the problem. How can you translate between the id of a
vertex i the adjacency matrix and the two grid coordinates? How can you decide whether vertices with indices
i and j are neighbours in the grid? The module template provides a function print as grid(graph, n) that
you can use to visually. For example:
>>> grid_graph(2, 3)
>>> print_as_grid(grid_graph(2, 3), 3)
*---*---*
| | |
*---*---*
>>> print_as_grid(grid_graph(3,2), 2)
*---*
| |
*---*
| |
*---*
>>> print_as_grid(grid_graph(5, 10), 10)
*---*---*---*---*---*---*---*---*---*
| | | | | | | | | |
*---*---*---*---*---*---*---*---*---*
| | | | | | | | | |
*---*---*---*---*---*---*---*---*---*
| | | | | | | | | |
*---*---*---*---*---*---*---*---*---*
| | | | | | | | | |
*---*---*---*---*---*---*---*---*---*
3
Continuing the example from above, your maze might look as follows:
>>> t = random_spanning_tree(g)
>>> print_as_grid(t, 10)
*---* *---*---*---* *---* *---*
| | | | | |
*---*---* * *---* *---* *---*
| | | |
*---* *---*---*---*---*---*---*---*
| |
* *---*---* * * *---* *---*
| | | | | |
*---*---*---*---*---*---*---*---* *
After calling sort table(jedi, 0), then jedi == [[‘Luke’, ‘Tatooine’, ‘green’], [‘Obi-Wan’, ‘Coruscant’,
‘blue’], [‘Qui-Gon’, ‘Coruscant’, ‘blue’], [‘Rey’, ‘Jakku’, ‘yellow’]]. If we then call sort table(jedi,
2), then jedi == [[‘Obi-Wan’, ‘Coruscant’, ‘blue’], [‘Qui-Gon’, ‘Coruscant’, ‘blue’], [‘Luke’,
‘Tatooine’, ‘green’], [‘Rey’, ‘Jakku’, ‘yellow’]]. Note that the relative ordering is maintained.