1

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

2 Answers2

1
def printMatrix(matrix):
    return "\n".join((("{:<10}"*len(row)).format(*row))for row in matrix)


In [19]: arr=[[1,332,3,44,5],[6,7,8,9,100]]

In [20]: print(printMatrix(arr))
1         332       3         44        5         
6         7         8         9         100  

"{:<10}"*len(row)) creates a {} for each number left aligned 10 <:10 then we use str.format format(*row) to unpack each row.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
0

Something like this shoud do the trick:

def print_matrix(matrix, pad_string=' ', padding_ammount=1,
                 number_delimiter=' ', number_width=3):
    '''
    Converts a list of lists holding integers to a string table.
    '''

    format_expr = '{{:{}>{}d}}'.format(number_delimiter, number_width)
    padding = pad_string * padding_ammount
    result = ''
    for row in matrix:
        for col in row:
            result = '{}{}{}'.format(
                result,
                padding,
                format_expr
            ).format(col)
        result = '{}\n'.format(result)
    return result

a = [
    [1, 2, 3, 22, 450],
    [333, 21, 13, 5, 7]
]

print(print_matrix(a))
#    1   2   3  22 450
#  333  21  13   5   7

print(print_matrix(a, number_delimiter=0)
# 001 002 003 022 450
# 333 021 013 005 007