Repository navigation
Expand file tree
/
Copy pathdo-matrix.py
More file actions
executable file
·118 lines (81 loc) · 2.61 KB
/
Copy pathdo-matrix.py
File metadata and controls
executable file
·118 lines (81 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Example to show how a multi dimensional array works in Python.
The "array" is implemented using lists of lists.
Press 's' to save the state to the file and press 'l' to load the
state from the file.
"""
# pylint: disable=consider-using-enumerate
filename = 'matrix.txt'
def createMatrix(y, x, filler):
"""
Create a two-dimensional array and return it.
"""
return [[filler for _ in range(x)] for _ in range(y)]
def printMatrix(matrix):
"""
Print the content of the matrix.
"""
for row in matrix:
print("".join(row))
def saveMatrix(matrix):
"""
Save the content of the matrix to a file. Do this by joining all items in the
list and create a string-representing the row and write that string to the file.
Add a newline to each row.
"""
with open(filename, 'w') as f:
for row in matrix:
f.write("".join(row) + '\n')
print("Saved the state to the file {}".format(filename))
def loadMatrix(matrix):
"""
Load the content of the matrix from a file. Do this by reading the lines from the file
and splitting them into a list by characters.
Ignore the newline at each row.
"""
with open(filename, 'r') as f:
# with \n
#content = f.readlines()
# without \n
content = f.read().splitlines()
# Update each row of the matrix and fill it by using the file content
# (may need som care when file and matrix size does not match)
for y in range(0, len(matrix)):
matrix[y] = list(content[y])
print("Loaded the state from the file {}".format(filename))
def main():
"""
Main function to carry out the work.
"""
print("Enter the size of the matrix.")
y = int(input("y: "))
x = int(input("x: "))
matrix = createMatrix(y, x, "-")
counter = 0
while 1:
printMatrix(matrix)
# Swap between X and O
if counter % 2:
char = "X"
else:
char = "O"
counter += 1
# Get a position to place the character
posY = input("Enter a row: ")
posX = input("Enter a column (or q for quit): ")
if posY == "q" or posX == "q":
break
elif posY == "s" or posX == "s":
saveMatrix(matrix)
continue
elif posY == "l" or posX == "l":
loadMatrix(matrix)
continue
#Place the character
matrix[int(posY)][int(posX)] = char
if __name__ == "__main__":
print(__doc__)
input("Press enter to continue.")
main()