You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python猜数统计程序添加tqdm进度条求助

我是一名Python初学者,编写了如下程序:电脑生成1-10、1-100、1-1000等不同范围的随机数,自行猜测该数(猜测次数由用户输入指定),每次统计猜测次数,计算多次猜测的平均值存入数组,最后用matplotlib绘制以log10(随机数范围上限)为X轴的图表。目前我通过打印每个上限的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()
解决方法

你的程序核心耗时在两个循环:遍历不同范围上限的外层循环,以及每个上限下重复猜测的内层循环,进度条需要分别加在这两个循环上,才能清晰展示整体和当前任务的进度。

具体修改点:

  1. 外层循环(遍历upper_bounds):
    用tqdm包装原循环,同时移除原有的print(int(np.log10(bound))),进度条会自动展示进度:

    for bound in tqdm.tqdm(upper_bounds, desc="处理各范围上限"):
    

    desc参数用来标注进度条的任务名称,明确当前执行阶段。

  2. 内层循环(重复猜测):
    同样用tqdm包装,添加leave=False参数,让内层进度条完成后自动消失,避免终端被多条进度条刷屏:

    for i in tqdm.tqdm(np.arange(no_of_guesses), desc=f"上限{int(bound)}的猜测", leave=False):
    

额外性能优化:

原代码用np.append反复扩展数组效率极低,建议先用普通列表存储猜测次数,最后再转为numpy数组,能大幅提升运行速度:

# 替换原有的guess_array = np.array([])
guess_list = []
# 内层循环中用列表append替代np.append
guess_list.append(computer_guess(ranx))
# 最后转numpy数组计算均值
guess_array = np.array(guess_list)

修改后的完整代码:

# Importing the modules needed
import random
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):
    low = 0
    high = x
    ranno = random.randint(low, high)
    guess = -1
    count = 1
    while guess != ranno:
        if low != high:
            guess = random.randint(low, high)
        else:
            guess = low
        if guess > ranno:
            high = guess - 1
            count += 1
        elif guess < ranno:
            low = guess + 1
            count += 1
        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 bound in tqdm.tqdm(upper_bounds, desc="处理各范围上限"):
        ranx = random.randint(0, bound)
        # 用列表代替numpy数组提升效率
        guess_list = []
        # 内层循环添加进度条,leave=False避免残留
        for i in tqdm.tqdm(np.arange(no_of_guesses), desc=f"上限{int(bound)}的猜测", leave=False):
            guess = computer_guess(ranx)
            guess_list.append(guess)
        # 转numpy数组计算均值
        guess_array = np.array(guess_list)

        average_of_guesses = np.mean(guess_array)
        list_of_averages.append(average_of_guesses)

    average_of_averages = np.mean(list_of_averages)
    print(f"Your list of averages: {list_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:
    resultant_average_numbers = guess_avg(
        int(input("Input the number of guesses you want the computer to make: ")))
    plt.plot(np.log10(upper_bounds), resultant_average_numbers)
    plt.show()

内容的提问来源于stack exchange,提问作者aurumlct

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 11:15:34