I have to print a 2d matrix so that it looks nice and neat, but I keep getting a weird output. I am not allowed to import anything like pretty print to help me. My code is this:
def pretty_print(M):
for rows in M:
print('{:<4}'.format(each) for each in rows)
but when I put in a 3x3 matrix, this is my result:(for some reason it won't show up but it says generator object genexpr at _____ with less than and greater than signs on either side of generator object and genexpr)
It also appears that it says the generator object thing the amount of times as there are rows in the matrix.
generator object genexpr at 0x03368530
generator object genexpr at 0x03368530
generator object genexpr at 0x03368530
Any help is appreciated. Thanks.
print
prints each argument passed to it separately. You provided it one generator argument, and thus it will print <generator object genexpr at 0x03368530>
; to print each argument from an iterator, use the *
apply operator (notice that I also changed the code to do a list comprehension instead of a generator as it would be slightly more efficient in this case)
def pretty_print(M):
for rows in M:
print(*['{:<4}'.format(each) for each in rows])
Example output:
46 20 18 55
99 14 76 12
81 7 48 79
58 36 74 7