I'm stuck on a function in my program that formats multiple lines of numbers seperated by spaces. The following code so far takes the unformatted list of lists and makes it into a table seperated by spaces without brackets:
def printMatrix(matrix):
return ('\n'.join(' '.join(map(str, row)) for row in matrix))
I would like all of the numbers to line up nicely though in the output. I can't figure out how to stick the format operator into the list comprehension to make this happen. The input is always a square matrix (2x2 3x3 etc) Here's the rest of the program to clarify
# Magic Squares
def main():
file = "matrix.txt"
matrix = readMatrix(file)
print(printMatrix(matrix))
result1 = colSum(matrix)
result2 = rowSum(matrix)
result3 = list(diagonalSums(matrix))
sumList = result1 + result2 + result3
check = checkSums(sumList)
if check == True:
print("This matrix is a magic square.")
else:
print("This matrix is NOT a magic square.")
def readMatrix(file):
contents = open(file).read()
with open(file) as contents:
return [[int(item) for item in line.split()] for line in contents]
def colSum(matrix):
answer = []
for column in range(len(matrix[0])):
t = 0
for row in matrix:
t += row[column]
answer.append(t)
return answer
def rowSum(matrix):
return [sum(column) for column in matrix]
def diagonalSums(matrix):
l = len(matrix[0])
diag1 = [matrix[i][i] for i in range(l)]
diag2 = [matrix[l-1-i][i] for i in range(l-1,-1,-1)]
return sum(diag1), sum(diag2)
def checkSums(sumList):
return all(x == sumList[0] for x in sumList)
def printMatrix(matrix):
return ('\n'.join(' '.join(map(str, row)) for row in matrix))
main()