0

I have a question on creating an r*c matrix with given number of rows and columns. I wrote this which takes r number of rows and c number of columns but the problem is in the output formatting, i require a exact output format and can't seem to get it even after trying for so long, if anyone could help me.

def matprint(r, c):
max = r*c
l=[]
for i in range(1,max+1):
    l.append(i)
subList = [l[n:n+c] for n in range(0, len(l),c)]
for q in subList:
    list1 = q
    print( ( '{} ' * len(list1) ).format( *list1 ) )

enter image description here

see the difference is that mine prints "\n" after spaces and also on the last line. it is not a logical problem, just need help with the formatting. Thank You

Souvikavi
  • 108
  • 1
  • 10

2 Answers2

1

You should use str.join to join a list of strings.

This code produces a string of items from list1, separeted by ' ', but also adds a white space at the end:

print( ( '{} ' * len(list1) ).format( *list1 ) )

Instead of that, do this:

list_of_strings = [str(x) for x in list1]
print(' '.join(list_of_strings))

Or, more compact:

print(' '.join(str(x) for x in list1))

You have the same problem with the newlines. print adds them after each line. You don't want them after the last line, so you should join the lines as well and then print them without a newline:

lines = [' '.join(str(x) for x in list1) for list1 in subList]
sys.stdout.write('\n'.join(lines))
zvone
  • 18,045
  • 3
  • 49
  • 77
1

You can invert the problem:

  • print a sublist if it is the first one - without newline after it
  • if it is not the first one, print a newline followed by the next sublist

that way your last line does not have to \n at its end:

def matprint(r, c):
    data = list(range(1,r*c+1))               
    l= [data[i*c:i*c+c] for i in range(r)]

    formatter = ('{} ' * c).strip()     # create the format string once - strip spaces at end

    for i,sublist in enumerate(l):
        if i: # 0 is False, all others are True
            print("")
        print( formatter.format( *sublist ), end="" ) # do not print \n at end


matprint(3, 5)

I optimized the code a bit as well - you should not use things like max,min,list,dict,... as variable names - they hide the build in functions of the same name.

Your list construction can be streamlined by a list comprehension that chunks your numbers list - see How do you split a list into evenly sized chunks? .

You do not need to recompute the length of your sublist - it is c long.

You need the index from enumerate() to decide if the list is "first" - and you need the end="" option of print to avoid autoprinting newlines.


A simpler version without enumerate could be done using list slicing:

def matprint(r, c):
    data = list(range(1,r*c+1))
    l= [data[i*c:i*c+c] for i in range(r)]
    formatter = ('{} ' * c).strip()     # create the format string once - strip spaces at end

    print(formatter.format(*l[0]), end="")  # print the 1st element w/o newline
    for sublist in l[1:]: 
        # print all others including a \n in front
        print( "\n"+formatter.format( *sublist ), end="" ) # do not print \n at end
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69