In Python, matrices can be created using nested lists. For example, [[1, 2], [3, 4]]. Below I have written a function that prompts the user for the dimensions of a square matrix and then prompts the user for the values in the for loop. I have a tempArray variable that temporarily stores one row of values, and then is deleted after it is appended to the matrix array. For some reason, when I print the matrix at the end, this is what I get: [ [ ], [ ] ]. What is going wrong?
def proj11_1_a():
n = eval(input("Enter the size of the square matrix: "))
matrix = []
tempArray = []
for i in range(1, (n**2) + 1):
val = eval(input("Enter a value to go into the matrix: "))
if i % n == 0:
tempArray.append(val)
matrix.append(tempArray)
del tempArray[:]
else:
tempArray.append(val)
print(matrix)
proj11_1_a()
You simply delete the array elements del tempArray[:] and as lists are mutable it also clears part of matrix
def proj11_1_a():
n = eval(input("Enter the size of the square matrix: "))
matrix = []
tempArray = []
for i in range(1, (n**2) + 1):
val = eval(input("Enter a value to go into the matrix: "))
if i % n == 0:
tempArray.append(val)
matrix.append(tempArray)
tempArray = [] #del tempArray[:]
else:
tempArray.append(val)
print(matrix)
proj11_1_a()
Which could be further simplified/cleared to
def proj11_1_a():
# Using eval in such place does not seem a good idea
# unless you want to accept things like "2*4-2"
# You might also consider putting try: here to check for correctness
n = int(input("Enter the size of the square matrix: "))
matrix = []
for _ in range(n):
row = []
for _ in range(n):
# same situation as with n
value = float(input("Enter a value to go into the matrix: "))
row.append(value)
matrix.append(row)
return matrix
Another solution is to change the following line:
matrix.append(tempArray)
to:
matrix.append(tempArray.copy())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With