1

How to print each recursion of function (quicksort as a example) like this:

            [0]   1   [5, 3, 99, 22, 24, 11, 303, 3821]
            [3]   5   [99, 22, 24, 11, 303, 3821]
   [22, 24, 11]   99  [303, 3821]    
           [11]   22  [24]           
             []   303 [3821]     

instead of this:

[0]     1     [5, 3, 99, 22, 24, 11, 303, 3821]
[3]     5     [99, 22, 24, 11, 303, 3821]
[22, 24, 11]     99     [303, 3821]
[11]     22     [24]
[]     303     [3821]

Should it be done with f-strings are maybe in another way?

def quicksort(values):
    if len(values) <= 1:
        return values

    pivot = values[0]
    less_than_pivot = []
    greater_than_pivot = []

    for value in values[1:]:
        if value <= pivot:
            less_than_pivot.append(value)
        else:
            greater_than_pivot.append(value)

    print(f"{less_than_pivot}     {pivot}     {greater_than_pivot}")

    return quicksort(less_than_pivot) + [pivot] + quicksort(greater_than_pivot)


numbers = [1, 5, 0, 3, 99, 22, 24, 11, 303, 3821]
sorted_numbers = quicksort(numbers)
mozway
  • 194,879
  • 13
  • 39
  • 75
Miłosz
  • 69
  • 4
  • Does this answer your question? [Format output string, right alignment](https://stackoverflow.com/questions/8234445/format-output-string-right-alignment) – mkrieger1 Nov 29 '21 at 11:38
  • For what you want, you wouldn't know how much to indent the earlier prints until the entire algorithm runs since you don't know what the depth of recursion will be. Thus -- rather than `print` from the function you would need to store what you are currently printing in something like a dictionary and then as a completely different problem decide on how you want to pretty-print it. – John Coleman Nov 29 '21 at 11:39
  • Use string formatting (https://docs.python.org/3/tutorial/inputoutput.html) look for the right alignment. – Florin C. Nov 29 '21 at 11:42

1 Answers1

2

You could use:

print(f"{str(less_than_pivot): >25} {str(pivot): >4}   {greater_than_pivot}")

Note that it might be hard to predict the maximum length of the string, so the simplest might be to use a reasonable value. For this you can take into account the expected maximum length of the intermediate list, and the length of the contained elements.

output:

                      [0]    1   [5, 3, 99, 22, 24, 11, 303, 3821]
                      [3]    5   [99, 22, 24, 11, 303, 3821]
             [22, 24, 11]   99   [303, 3821]
                     [11]   22   [24]
                       []  303   [3821]
mozway
  • 194,879
  • 13
  • 39
  • 75