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

使用random方法计算5选4整数的最大最小和:HackerRank测试失败求助

Fixing Your Random-Based Min/Max 4-Integer Sum Code

Hey there! Let's break down why your code is failing 8 out of 15 test cases on HackerRank, and how to fix it while sticking strictly to the requirement of using the random method.

The Core Issues in Your Original Code

  • Insufficient Loop Iterations: Your loop runs only len(arr)-1 = 4 times. When picking 4 numbers from 5, there are 5 unique combinations (each leaving out one element). Random sampling in just 4 tries might never hit the combination that gives the true minimum or maximum sum—you could end up repeating the same combination multiple times and missing the critical one.
  • Poor Initialization: You set maxi = 0, which breaks if all input integers are negative. The maximum sum would be negative, but your code would keep maxi at 0, leading to wrong results.

Fixed Code (Safety Net Approach)

This version runs enough iterations to ensure we almost certainly hit all possible combinations, and fixes the initialization problem:

import random

# Read input into a list of integers
arr = [int(x) for x in input().split()]

# Initialize min and max with an actual sum from the array (avoids negative number edge cases)
initial_sum = sum(random.sample(arr, 4))
mini = initial_sum
maxi = initial_sum

# Run 10 iterations—more than enough to cover all 5 possible combinations
for _ in range(10):
    current_sum = sum(random.sample(arr, 4))
    if current_sum < mini:
        mini = current_sum
    if current_sum > maxi:
        maxi = current_sum

print(mini, maxi)

Even More Robust Version (Guaranteed Coverage)

If you want to be 100% sure you capture all possible sums (no reliance on "enough iterations"), you can collect unique sums until you have all 5 possible values:

import random

arr = [int(x) for x in input().split()]
unique_sums = set()

# Keep sampling until we have all 5 distinct 4-element sums
while len(unique_sums) < 5:
    unique_sums.add(sum(random.sample(arr, 4)))

# Now we have every possible sum—just grab min and max
mini = min(unique_sums)
maxi = max(unique_sums)

print(mini, maxi)

Key Fixes Explained

  • Proper Initialization: By setting mini and maxi to an actual sum from the array, we avoid issues with negative numbers or extreme values that don't match your initial arbitrary values.
  • Adequate Sampling: Either running enough iterations or collecting unique sums ensures we don't miss the true min/max sum that comes from leaving out the largest or smallest element in the input list.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:26:46