Python算法压力测试脚本异常求助:变量始终输出0
问题分析与修复方案
Hey there! I see exactly what's tripping up your stress test script—let's walk through the issues and fix them together:
核心问题
Your script has two critical issues keeping fast and result stuck at 0:
- You never call your functions! You defined
max_pairwise_productandmax_pairwise_product_fast, but nowhere in your loop do you run them with your random arraya. So the global variablesresultandfastnever get updated from their initial 0 values. - Misplaced code blocks: Putting
if __name__ == '__main__':inside thewhileloop, and defining functions inside that block, is inefficient (you redefine functions every loop) and causes scoping confusion.
额外优化点
- Using global variables for
resultandfastis unnecessary—you can capture function return values directly, making code cleaner and easier to debug. - You should reset comparison variables each loop iteration, or better yet, use function returns directly in your check.
修正后的代码
Here's the fixed script with key changes explained:
import random # Move function definitions to global scope (define them once only!) def max_pairwise_product(n, a): product = 0 for i in range(n): for j in range(i + 1, n): current_product = a[i] * a[j] if current_product > product: product = current_product return product def max_pairwise_product_fast(n, a): max_index1 = -1 for i in range(n): if max_index1 == -1 or a[i] > a[max_index1]: max_index1 = i max_index2 = -1 for i in range(n): if i != max_index1 and (max_index2 == -1 or a[i] > a[max_index2]): max_index2 = i return a[max_index1] * a[max_index2] if __name__ == '__main__': while True: # Generate random test case n = random.randint(2, 11) a = [random.randint(0, 99999) for _ in range(n)] assert len(a) == n # Call both functions and capture results result = max_pairwise_product(n, a) fast = max_pairwise_product_fast(n, a) # Check and output results if result == fast: print(fast, result, "OK") else: print(f"Wrong Answer! Input array: {a}") print(f"Brute force result: {result}, Fast result: {fast}") break # Halt testing when a mismatch is found
关键修改说明:
- Functions moved outside the loop: Functions are defined once at the start, not recreated every iteration.
- Global variables removed: Each function calculates and returns its result directly, which we assign to
resultandfastin the loop. - Added function calls: We now run both algorithms with the random array
aevery loop iteration. - Restructured main block: The
whileloop lives insideif __name__ == '__main__':(the correct place for entry-point code). - Improved error reporting: When a mismatch occurs, we print the problematic array and both results to simplify debugging.
Now when you run this script, it will generate random test cases, run both your algorithms, and only stop if it finds a case where they produce different results—exactly what a stress test should do!
内容的提问来源于stack exchange,提问作者thenoob
相关产品推荐
相关产品推荐

