0

I have designed this code below which basically takes as an input, the number of rows, columns,highest value and lowest value from the user.

import random
import math


nrows=int(input("enter the number of rows: "))
ncols=int(input("enter the number of columns: "))
lowval=float(input("enter the lowest value: "))
highval=float(input("enter the highest value: "))

def list(nrows, ncols, lowval, highval):
    values=[[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0]]

    for r in range(nrows):
        for c in range(ncols):
            values[r][c] = random.uniform(lowval,highval+1)

    print(values)


list(nrows, ncols, lowval, highval)

Now the area which I'm struggling with is attempting to take the list and convert it into something more organized akin to a chart so that the output basically mirrors this for example:

Number of rows: 4
Number of columns: 3
Low value: -100
High value: 100

             0         1         2
   0     7.715     6.522    23.359
   1    79.955    -4.858   -71.112
   2    49.249   -17.001    22.338
   3    98.593   -28.473   -92.926

Any suggestions/ideas as to how I can have my output look like the one desired above?

YoungSon
  • 7
  • 3

1 Answers1

0

I have no idea how that very obfuscated code I linked in the comments (here) works, so I'm going to try writing it more clearly.

import string

In the example you gave, there's a varying amount of space between the columns. It seems like you could either make each column a the same fixed width or make them the width of the longest string in that column plus some constant for spacing. Three or four for that constant looks nice:

def formatchart(data,spacing=3):

I'll use zip() and the splat operator to transpose the data so I can work with columns, because that's what the spacing is based on. I can transpose it back later to print it.

    t = zip(*data)

I'll iterate over the rows to figure out how wide each should be. I'm using range(len(t)) because I'm going to be padding them in this loop, so I need the index to modify t.

    for i in range(len(t)):

I'm using a list comprehension to iterate over the items in the row, finding the max, and adding the extra spacing.

        width = max([len(j) for j in t[i]])+spacing

Now, I'll pad each string in the row with spaces. I'm using rjust(), but you can easily left-justify if you want, or even have some rows left-justify and some right-justify.

        t[i] = [string.rjust(j,width) for j in t[i]]

Now, I just have to transpose it again and print it:

    formatted = zip(*t)
    for i in formatted:
        for j in i:
            print(j,end="")

I assume you're using Python 3 based on the parentheses you use with your print statement, so I'm taking advantage of that in the last line, but I usually use Python 2, so let me know if I messed anything up.

Community
  • 1
  • 1
KSFT
  • 1,774
  • 11
  • 17