I'm trying to print out the following triangle using columns instead of rows:
def r(x):
return '\x1b[6;31;50m{}\x1b[0m'.format(x)
def g(x):
return '\x1b[1;32;50m{}\x1b[0m'.format(x)
def rb(x):
return '\x1b[5;31;51m{}\x1b[0m'.format(x)
print(f'1 10 {rb(208)} {r(1234)}')
print(5*' ', f'{g("1")} {g("1")}{r("0")} {g(208)}')
print(12*' ', f'1 {r("1")}0')
print(20*' ', f'{r(1)} ')
If I want to add a column as the code is now, I have to add spaces and one element to the end of each print statement. That's not a big deal for this example, but I'm not looking forward to column 50 or 100. I thought I'd just write each column as a separate list instead and then combine them into a list of lists and loop through it, but I got stuck.
Printing one list as a column while keeping the alignment was pretty straight forward, but I don't know how to handle the lists being of different lengths (the spacing is fine, but the fact that all lists will have different lengths got me).
col = ['32Σ21', '1234', '208', '10', '1']
col5color = ["33" r("Σ2") g("1"), g("12") r("34"), r("2") g("08"), rb("10"), r("1")]
maxlen = len(col[0])
for i in range(len(col)):
print((maxlen - len(col[i]))*' ' col5color[i])
The lists for the first four columns:
col4color = [r("1234"), g("208"), r("1") "0", r("1")]
col3color = [rb("208"), g("1") r("0"), "1"]
col2color = ["10", g("1")]
col1color = ["1"]
To clarify: I can't change the layout (flip rows/columns), I can't use imports and I have to hardcode it. That's why I would like to tidy it up and minimize the risk of errors. If I could just deal with the different lengths I would only have to add one element at the first index of "col", copy and paste "col", change the name to "colncolor" and then change the colors. I don't know much about the next column beforehand, but I know that the new element will have at least as many characters as the element in the previous column, so I never have to change "maxlen".
CodePudding user response:
I solved it. It's not the best solution or a generic one, but at least it's a solution =)
def trimatrix_print(color_matrix, matrix, spacing=4):
num_col = len(matrix)
maxlen = len(matrix[0][0]) spacing
newmat = []
for i in range(num_col):
for j in range(num_col):
if len(matrix[i]) < num_col:
color_matrix[i].append(" ")
matrix[i].append(" ")
if len(matrix[i][j]) < maxlen and i != num_col - 1:
color_matrix[i][j] = (maxlen - len(matrix[i][j]))*" " color_matrix[i][j]
for i in range(num_col):
tempmat = []
for j in range(1, num_col 1):
tempmat.append(color_matrix[-j][i])
newmat.append(tempmat)
for line in newmat:
print(''.join(line))
return
num = [
['32Σ21', '1234', '208', '10', '1'],
['1234', '208', '10', '1'],
['208', '10', '1'],
['10', '1'],
['1']]
colornum = [
["33" r("Σ2") g("1"), g("12") r("34"), r("2") g("08"), rb("10"), r("1")],
[r("1234"), g("208"), r("1") "0", r("1")],
[rb("208"), g("1") r("0"), "1"],
["10", g("1")],
["1"]]
trimatrix_print(colormat, mat)