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

暴力法求解背包问题绘图时遇维度不匹配ValueError报错求助

背包问题暴力解法绘图报错:ValueError: x and y must have same first dimension, but have shapes (5,) and (1,)

报错原因

你的代码中绘图逻辑被错误缩进在for循环内部。第一次循环执行时,running_times仅收集到1条运行时间数据(长度为1),但input_sizes的长度是5,此时调用plt.plot(input_sizes, running_times)会因x、y数组维度不匹配触发报错。

解决方法

将所有绘图相关代码(从plt.plot()到plt.show())移至for循环外部,确保等running_times收集完所有5组输入规模对应的运行时间后,再执行绘图操作。

修正后的完整代码

import time
import random
import matplotlib.pyplot as plt

def brute_force(values, weights, capacity):
    num_items = len(values)
    max_value = 0
    subset = []
    
    for i in range(2**num_items):
        current_value = 0
        current_weight = 0
        current_subset = []
        
        for j in range(num_items):
            if(i & (1 << j)) != 0:
                current_value += values[j]
                current_weight += weights[j]
                current_subset.append(j)
                
        if current_weight <= capacity and current_value > max_value:
            max_value = current_value
            subset = current_subset
            
    return max_value, subset

input_sizes = [10, 20, 30, 40, 50]
running_times = []
for size in input_sizes:
    values = [random.randint(1,100) for _ in range(size)]
    weights = [random.randint(1, 100) for _ in range(size)]
    capacity = sum(weights) // 2

    start_time = time.time()
    max_value, subset = brute_force(values, weights, capacity)
    end_time = time.time()
    running_time = end_time - start_time
    running_times.append(running_time)

    print(f"Input size: {size}")
    print(f"Chosen subset: {subset}")
    print(f"Chosen weight: {sum(weights[i] for i in subset)}")
    print(f"Running time: {running_time: .6f} seconds")

# 绘图代码移至循环外部
plt.plot(input_sizes, running_times, marker = 'o')
plt.xlabel('Input size')
plt.ylabel('Running time (s)')
plt.title('Brute force Knapsack')
plt.show()  

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 14:27:36