尝试在python程序运行时添加进度条

k2fxgqgv  于 2022-11-27  发布在  Python
关注(0)|答案(3)|浏览(150)

我是一个写Python代码的初学者,在代码中,计算机生成一个1和10、1和100、1和1000、1和10000、1和100000等之间的随机数。(用户输入的数字),并且每次都有一个计数,计算计算机猜测随机数的次数。计算次数的平均值,并将其放入一个数组中,其中matplotlib将生成x=log10(随机数范围的上限,即10、100、1000 ...)的图形
现在,我打印了每一个绑定的log10,作为我的进度跟踪器。但是我想添加我的进度条,我不知道把它放在哪里,这样我就可以看到整个程序运行了多少。
我已经在各种不同的地方添加了tqdm.tqdm,但都无济于事。我期待着随着程序的运行,进度条会增加。
我的程序如图所示。

# 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()

我道歉,如果这是解释不好,这是我第一次使用堆栈溢出。

isr3a4wc

isr3a4wc1#

您可以定义下列progress_bar函数,您可以从任何想要监视程式码进度的地方呼叫该函数:

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')

希望这对你有帮助

q3aa0525

q3aa05252#

也可以手动调用tqdm,然后手动更新它。

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

完成后,可以调用progress_bar.clear()重新开始。

2w2cym1i

2w2cym1i3#

您可能需要在guess_avg()函数中使用两个进度条,一个用于跟踪范围,另一个用于跟踪猜测。
在这个例子中,我使用了Enlighten进度条库,但是你可以用其他支持嵌套进度条的库来实现类似的行为。Enlighten比其他库的一个优势是你可以在进度条运行时打印你想要的任何东西,这对调试很有好处。
您可以通过使用上下文管理器和自动更新计数器来简化这一过程,但我在这里没有这样做,以使发生的事情更清楚。您还可以自定义用于进度条的模板。

import enlighten

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

    # For every value in the "upper_bounds" array,

    # Create a progress bar manager manager
    manager = enlighten.get_manager(leave=False)
    # Create main progress bar for ranges
    pbar_bounds = manager.counter(total=len(upper_bounds), desc='Bound ranges', unit='ranges')
    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,
        # Create nested progress bar for guesses, leave removes progress bar on close
        pbar_guesses = manager.counter(total=no_of_guesses, desc='Guessing', unit='guesses', leave=False)
        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)
            pbar_guesses.update() # Update nested progress bar
        pbar_guesses.close()  # Close nested progress bar

        # Print log10 of each value in "upper_bound"
        print(int(np.log10(bound)))  # You can remove this now if you want
        pbar_bounds.update()  # Update main progress bar

        # 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)
    manager.stop()  # Stop the progress bar manager

    # 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

相关问题