Search code examples
pythondictionarystring-formatting

Problem with formatting a python print output that includes dictionary items


I am trying to benchmark the performance of three different sorting algorithms. I want to print the result on my terminal.

Here's the code I am using:

### library imports ###
import random
from time import time
from SortingAlgorithms import selection_sort, merge_sort, quicksort


### function definitions ###
def create_array(size, max):
    return [random.randint(0, max) for _ in range(0, size)]


### main ###
n = [10, 100, 1000]
times = {'selection':[], 'merge':[], 'quick':[]}
samples = 5

for size in n:
    tot_time = 0.0
    for _ in range(samples):
        myArray = create_array(size, size)
        t0 = time()
        selection_sort(myArray)
        t1 = time()
        tot_time += t1 - t0
    times['selection'].append(tot_time / float(samples))

for size in n:
    tot_time = 0.0
    for _ in range(samples):
        myArray = create_array(size, size)
        t0 = time()
        merge_sort(myArray)
        t1 = time()
        tot_time += t1 - t0
    times['merge'].append(tot_time / float(samples))

for size in n:
    tot_time = 0.0
    for _ in range(samples):
        myArray = create_array(size, size)
        t0 = time()
        myArraySorted = quicksort(myArray)
        t1 = time()
        tot_time += t1 - t0
    times['quick'].append(tot_time / float(samples))

print("\n \t Selectionsort \t Mergesort \t Quicksort")
print(50* "_")
for i,size in enumerate(n):
    "{0:6d} \t {1:2.5f} \t {2:2.5f} \t {3:2.5f}".format(
        size,
        times['selection'][i],
        times['merge'][i],
        times['quick'][i]
    )

However, only the first line (Selectionsort, Mergesort, Quicksort) is printed on the terminal. The performance does not get printed. I have always been so confused by python's way of formatting strings, so I am pretty sure I do sth terribly wrong here. Still, can anyone help?


Solution

  • As said in the comments, you only formatted the string, but you did not print it. You don't expect a string to be output without calling the print function.