Home > database >  Adding text in loop python only once (adding a string to a column in a loop)
Adding text in loop python only once (adding a string to a column in a loop)

Time:12-15

I would like to add a red ABCD on the left as it is on the top ... I have a big problem with it because everything is done in a loop

as I have now

as I have now photo

as I want to have

as I want to have photo

import sys
INF = sys.maxsize
def floydWarshall(graph):
    n = len(graph)
    dist = [[] for i in range(n)]
    for i in range(n):
        for j in range(n):
            dist[i].append(graph[i][j])
    for k in range(n):
        for i in range(n):
            for j in range(n):
                dist[i][j] = min(dist[i][j], dist[i][k]   dist[k][j])
    print('Najkrotszy dystans pomiedzy kazda para')
    print("\033[91m      A       B       C       D\033[0m")
    for i in range(n):
        for j in range(n):
            if dist[i][j] == INF:
                print("%7s" % ("INF"), end=' ')
            else:
                print("%7s" % (dist[i][j]), end=' ')
        print()
graph = [[0, 5, INF, 10] , [INF, 0, 3, INF], [2, INF, 0, 1], [5, 3, 4, 0]]
floydWarshall(graph)

CodePudding user response:

You could for example introduce a row_names list with the row names:

row_names = ["A", "B", "C", "D"]

Then right after the first for loop after the header print, use the index i to get the correct row_name:

# ...
    for i in range(n):
        print("\033[91m{0}\033[0m".format(row_names[i]), end= ' ')
        for j in range(n):
# ...

If you are using Python >= 3.6 you could replace the format function with F-Strings:

print(f"\033[91m{row_names[i]}\033[0m", end= ' ')

EDIT: or as @kosciej16 suggested, use chr(ord("A") i) instead of row_names:

  • ord() returns the ASCII code of the letter "A" (65)
  • adds the index i to it
  • and chr() then converts the ASCII number back to a character

(e.g. "B" would be ord("A") 1 = 66 -> chr(66) -> "B")

Output:

Najkrotszy dystans pomiedzy kazda para
A       0       5       8       9 
B       5       0       3       4 
C       2       4       0       1 
D       5       3       4       0 

CodePudding user response:

You can simplify things a great deal by doing something like this:

for i in range(n):
  row_header = chr(ord("A")   i)
  preformatted_values = ("INF" if v == INF else v for v in dist[i])
  formatted_values = [f"\033[91m{v}\033[0m" for v in preformatted_values]
  row = "/t".join(formatted_values)
  print(f"{row_header} {row}")

This doesn't handle all the formatting you're doing in the row string, but you can also use something like format() instead of print() in order to do that formatting on each element and then use the above-shown join() rather than iterating manually through your row.

Another alternative is to use one of the veteran libraries like tabulate.

  • Related