Programming with Python¶

Exercises: File I/O¶

Reminder: To test your solutions, you need to create one or more text files. You can do so in Spyder, Notepad, or any other text editor.

Problem 1. Write a program that loads names of two files. Each file contains integers, one per each line. The program has to print a message describing if the sets of numbers contained in those files are equal, or the first one is a proper subset of the second one, or the second one is a proper subset of the first one, or neither.

Hint: Since the program needs to read from two files, make a function that reads a file into a set and returns that set.

Problem 2. Write a program that loads a name of a text file and reverses the order of its lines (overwriting the original file). You may assume that the file ends with an empty line (i.e., all lines end with a new line character).

Hint: Read the file, line by line, reverse it, and save it.

Problem 3. Write a program that loads an integer n and a file name, and then creates a text file with that name containing the multiplication table for all numbers between 1 and abs(n) (including both of them).

Save the table in the following format:

 *  | 1  | 2  | 3  | 4  | 5
----|----|----|----|----|----
1  | 1  | 2  | 3  | 4  | 5
2  | 2  | 4  | 6  | 8  | 10
3  | 3  | 6  | 9  | 12 | 15
4  | 4  | 8  | 12 | 16 | 20
5  | 5  | 10 | 15 | 20 | 25



So, a * in the top left cell, a horizontal dashed line after the header, and all the numbers should be centered in 2 characters more than is needed to display $n^2$.

A note on the purpose of these tables (not part of the problem): Text formatted as required by this problem can be used in GFM as tables. For example, the above text is displayed like this:

* 1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25

A bit more advanced version is to replace each "----" with ":--:":

 *  | 1  | 2  | 3  | 4  | 5
:--:|:--:|:--:|:--:|:--:|:--:
1  | 1  | 2  | 3  | 4  | 5
2  | 2  | 4  | 6  | 8  | 10
3  | 3  | 6  | 9  | 12 | 15
4  | 4  | 8  | 12 | 16 | 20
5  | 5  | 10 | 15 | 20 | 25



This achieves the centered display of the numbers when processed as GFM:

* 1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25