Home > front end >  Trying to add a progress bar as my python program runs
Trying to add a progress bar as my python program runs

Time:11-23

I am a beginner writing a Python code, where the computer generates a random number between 1 and 10, 1 and 100, 1 and 1000, 1 and 10000, 1 and 100000 and so on. The computer itself will guess the random number a number of times (a user input number), and every time there is a count of how many times the computer took to guess the random number. A mean of the count over the number of times will be calculated and put in an array, where matplotlib will generate a graph of x=log10(the upper bounds of the random number range, i.e. 10, 100, 1000,...)

At the moment, I print the log10 of each bound as it is processed, and that has been acting as my progress tracker. But I am thinking of adding my progress bar, and I don't know where to put it so that I can see how much of the overall program has run.

I have added tqdm.tqdm in all sorts of different places to no avail. I am expecting a progress bar increasing as the program runs.

My program is as shown.

# Importing the modules needed
import random
import time
import timeit
import numpy as np
import matplotlib.pyplot as plt
import tqdm

# Function for making the computer guess the number it itself has generated and seeing how many times it takes for it to guess the number
def computer_guess(x):
    # Telling program that value "low" exists and it's 0
    low = 0
    # Telling program that value "high" exists and it's the arbitrary parameter x
    high = x
    # Storing random number with lower limit "low" and upper limit "high" as "ranno" for the while-loop later
    ranno = random.randint(low, high)
    # Setting initial value of "guess" for iteration
    guess = -1
    # Setting initial value of "count" for iteration
    count = 1
    # While-loop for all guessing conditions
    while guess != ranno:
        # Condition: As long as values of "low" and "high" aren't the same, keep guessing until the values are the same, in which case "guess" is same as "low" (or "high" becuase they are the same anyway)
        if low != high:
            guess = random.randint(low, high)
        else:
            guess = low
        # Condition: If the guess if bigger than the random number, lower the "high" value to one less than 1, and add 1 to the guess count
        if guess > ranno:
            high = guess - 1
            count  = 1
        # Condition: If the guess if smaller than the random number, increase the "low" value to one more than 1, and add 1 to the guess count
        elif guess < ranno:
            low = guess   1
            count  = 1
        # Condition: If it's not either of the above, i.e. the computer has guessed the number, return the guess count for this function
        else:
            return count


# Setting up a global array "upper_bounds" of the range of range of random numbers as a log array from 10^1 to 10^50
upper_bounds = np.logspace(1, 50, 50, 10)


def guess_avg(no_of_guesses):
    # Empty array for all averages
    list_of_averages = []

    # For every value in the "upper_bounds" array,
    for bound in upper_bounds:
        # choose random number, "ranx", between 0 and the bound in the array
        ranx = random.randint(0, bound)
        # make an empty Numpy array, "guess_array", to insert the guesses into
        guess_array = np.array([])
        # For every value in whatever the no_of_guesses is when function called,
        for i in np.arange(no_of_guesses):
            # assign value, "guess", as calling function with value "ranx"
            guess = computer_guess(ranx)
            # stuff each resultant guess into the "guess_array" array
            guess_array = np.append(guess_array, guess)
        # Print log10 of each value in "upper_bound"
        print(int(np.log10(bound)))

        # Finding the mean of each value of the array of all guesses for the order of magnitude

        average_of_guesses = np.mean(guess_array)
        # Stuff the averages of guesses into the array the empty array made before
        list_of_averages.append(average_of_guesses)

    # Save the average of all averages in the list of averages into a single variable
    average_of_averages = np.mean(list_of_averages)
    # Print the list of averages
    print(f"Your list of averages: {list_of_averages}")
    # Print the average of averages
    print(f"Average of averages: {average_of_averages}")
    return list_of_averages


# Repeat the "guess_avg" function as long as the program is running
while True:
    # Ask user to input a number for how many guesses they want the computer to make for each order of magnitude, and use that number for calling the function "guess_avg()"
    resultant_average_numbers = guess_avg(
        int(input("Input the number of guesses you want the computer to make: ")))
    # Plot a graph with log10 of the order of magnitudes on the horizontal and the returned number of average of guesses
    plt.plot(np.log10(upper_bounds), resultant_average_numbers)
    # Show plot
    plt.show()

I apologise if this is badly explained, it's my first time using Stackoverflow.

CodePudding user response:

You can define the following progress_bar function, which you will call from wherever you want to monitor the advancement in you code:

import colorama
def progress_bar(progress, total, color=colorama.Fore.YELLOW):
    percent = 100 * (progress / float(total))
    bar = '█' * int(percent)   '-' * (100 - int(percent))
    print(color   f'\r|{bar}| {percent:.2f}%', end='\r')
    if progress == total:
        print(colorama.Fore.GREEN   f'\r|{bar}| {percent:.2f}%', end='\r')

Hope this helps

CodePudding user response:

You can also call tqdm by hand and then update it manually.

progress_bar = tqdm.tqdm(total=100)
progress_bar.update()

When you are finished, you can call progress_bar.clear() to start again.

  • Related