0% found this document useful (0 votes)
280 views4 pages

FIT1045 Algorithms and Programming Fundamentals in Python - Workshop 5

This document provides instructions for Workshop 5 on algorithms and programming fundamentals in Python. It covers objectives of reading, writing, and creating files; representing graphs; and reasoning about selection sort. It includes 4 tasks: 1) reading and writing files, 2) using graphs, 3) generating grid graphs and mazes, and 4) sorting tables. The tasks involve writing functions to perform tasks like getting the first word from a file, representing file data as a nested list, finding the degree of a vertex, checking if a path exists in a graph, generating grid graphs, and sorting a table based on a given column.

Uploaded by

Alireza Kafaei
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
280 views4 pages

FIT1045 Algorithms and Programming Fundamentals in Python - Workshop 5

This document provides instructions for Workshop 5 on algorithms and programming fundamentals in Python. It covers objectives of reading, writing, and creating files; representing graphs; and reasoning about selection sort. It includes 4 tasks: 1) reading and writing files, 2) using graphs, 3) generating grid graphs and mazes, and 4) sorting tables. The tasks involve writing functions to perform tasks like getting the first word from a file, representing file data as a nested list, finding the degree of a vertex, checking if a path exists in a graph, generating grid graphs, and sorting a table based on a given column.

Uploaded by

Alireza Kafaei
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

FIT1045 Algorithms and Programming Fundamentals in Python –

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.

Task 0: Setup file and tester


Download the Workshop 5 folder. In it you will find:
ˆ a Python file workshop05.py
ˆ a Python file workshop05 test.py
ˆ a folder containing a variety of .txt files
The file workshop05.py is the file you need to modify. You may open and look in the test file, but ensure that
you do not modify it.

Working with files


In this workshop we will practice working with files. The general pattern we follow for reading files is:1
1. open file: open(file name, mode)
2. read file, either all at once, or line-by-line: read() or readline()
3. close file: close()
The open() function takes the argument mode, which can be either the default read, or write (‘w’), or append
(‘a’), among other options.
Let’s step through an example:
>>> f = open(‘files/warm_up.txt’) #opens the file to read
>>> contents = f.read() #file contents saved to variable
>>> f.close()
>>> print(contents)
Hopefully you printed Hello, world! in the shell. Now let’s try adding to the warm up file:
>>> f = open(‘files/warm_up.txt’, ‘a’) #opens the file to append
>>> f.write(‘I can use files!’) #adds another line to the file
>>> f.close()
If this process worked correctly, you should have printed an integer in the shell. This is the number of characters
written to the file. If you step through the first block of code again, you will see another line has been written
to your file. You also could open the warm up.txt file in a text editor to see that you have changed it.
1 There is an alternative way you can read a file, using the with keyword. Read about it here: https://docs.python.org/3/

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.

Hint: the string methods split and strip will be useful.

Example: calling word from file(‘files/task1A.txt’) returns ‘Once’.

Part B - Read a table


Implement a function nested int list from file(file) that takes a file containing lines of integers that are
separated by commas as input and returns the file contents formatted as a nested list in Python. Note that the
numbers should be converted into integers.

Example: calling nested int list from file(‘files/task1B.txt’ returns [[2,1,3], [3,1,3], [2,9]].

Task 2: Using Graphs


Part A - Degree of a Vertex
Implement a function degree(graph, vertex) that calculates the degree of a given vertex. The function must:
ˆ take two arguments: a table graph that is an adjacency matrix representation of a graph, and an integer
indicating a vertex in the graph, where vertex < len(graph)
ˆ return the degree of the given vertex in the given graph

Part B - Existence of a Path


Implement a function is path(graph, path) that returns whether the path exists in the given graph. The
function must:
ˆ take two arguments: a table graph that is an adjacency matrix representation of a graph, and a list of
integers path that represents a proposed path in the graph
ˆ return a boolean: True if the path exists, otherwise False

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

Figure 1: A 2 by 3 grid graph

Task 3: Grid Graphs and Mazes


Part A - Generating Grid Graphs
In the lecture we said that we can use Prim’s algorithm to create mazes by starting from a regular “grid graph”
and then finding a spanning tree. Implement a function grid graph(m, n) that takes as input two positive
integers, and returns the adjacency matrix of a m by n grid graph, i.e., a graph with m*n vertices that, when
drawn on a regular m by n grid, has edges exactly between vertices that lie and neighbouring points on the
grid. See Figure. 1 for an illustration.

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)
*---*---*---*---*---*---*---*---*---*
| | | | | | | | | |
*---*---*---*---*---*---*---*---*---*
| | | | | | | | | |
*---*---*---*---*---*---*---*---*---*
| | | | | | | | | |
*---*---*---*---*---*---*---*---*---*
| | | | | | | | | |
*---*---*---*---*---*---*---*---*---*

Part B - Generating Mazes (not assessed)


Use your grid graph generator in conjunction with Prim’s algorithm to generate a maze. You can print your
maze again with the print as grid function to investigate your result. You might recognise that your maze
looks rather boring. For instance, with the implementation from the lecture, using a 5-by-10 grid, your result
would look as follows:
>>> g = grid_graph(5, 10)
>>> t = spanning_tree()
>>> print_as_grid(t,10)
*---*---*---*---*---*---*---*---*---*
| | | | | | | | | |
* * * * * * * * * *
| | | | | | | | | |
* * * * * * * * * *
| | | | | | | | | |
* * * * * * * * * *
| | | | | | | | | |
* * * * * * * * * *
To make your maze more compelling, think about how you can include random choices into Prim’s algo-
rithm (see the documentation of the random module https://docs.python.org/3.8/library/random.html;
in particular have a look at the function shuffle) to write a function random spanning tree(graph) that
returns the adjacency matrix of a random spanning tree of graph. Test this function on grid graphs to see
whether you can generate now more compelling mazes.

3
Continuing the example from above, your maze might look as follows:
>>> t = random_spanning_tree(g)
>>> print_as_grid(t, 10)
*---* *---*---*---* *---* *---*
| | | | | |
*---*---* * *---* *---* *---*
| | | |
*---* *---*---*---*---*---*---*---*
| |
* *---*---* * * *---* *---*
| | | | | |
*---*---*---*---*---*---*---*---* *

Task 4: Sorting Tables


In the lectures you were given the following code for insertion sort:
def insert (k , lst ):
j = k
while j > 0 and lst [j -1] > lst [ j ]:
lst [j -1] , lst [ j ] = lst [ j ] , lst [j -1]
j = j - 1

def insertion_sort ( lst ):


for i in range (1 , len ( lst )):
insert (i , lst )
Implement a function sort table(table, col) that takes as input an n × m table and a column index.
The function sorts the rows of the table in non-decreasing order according to the values in the given column.
The function does not have a return statement. You should model your function on the insertion sort code.

Example: say that we have the following table:


jedi = [[‘Luke’, ‘Tatooine’, ‘green’],
[‘Qui-Gon’, ‘Coruscant’, ‘blue’],
[‘Obi-Wan’, ‘Coruscant’, ‘blue’],
[‘Rey’, ‘Jakku’, ‘yellow’]]

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.

You might also like