Python中如何输入n-1个值并通过总和法查找缺失序列值
Hey Dave, great approach using the sum difference to find the missing number—this is actually one of the most efficient solutions for this problem! Let's fix that input handling issue and refine your idea a bit.
Core Concept Recap
Your logic is solid:
- Calculate the total sum of numbers from 1 to n using the formula
n*(n+1)//2(this is way more efficient than looping to add each number one by one) - Subtract the sum of your input values from this total—the result is your missing number.
Handling Inputs
The tricky part is reading those n-1 values, and it depends on how your input is formatted. Here are two common scenarios with code examples (using Python, since it's widely used for practice problems):
Scenario 1: Input is a single line of space-separated numbers
If all n-1 values are given in one line (like 3 1 4 when n=5), use this code:
# Get the value of n first n = int(input()) # Read the single line, split into strings, convert to integers input_numbers = list(map(int, input().split())) # Calculate full sum of 1..n full_sum = n * (n + 1) // 2 # Calculate sum of input values input_sum = sum(input_numbers) # Find the missing number missing_number = full_sum - input_sum print(missing_number)
Scenario 2: Input is one number per line (n-1 total lines)
If each value is on its own line, use a loop to collect each number:
n = int(input()) input_sum = 0 # Loop n-1 times to read each number for _ in range(n - 1): num = int(input()) input_sum += num full_sum = n * (n + 1) // 2 missing_number = full_sum - input_sum print(missing_number)
Why This Works
- The formula
n*(n+1)//2is a mathematical shortcut for the sum of the first n natural numbers—no need to write a loop for this, which saves you from potential off-by-one errors. - By subtracting the sum of your given values from this full sum, you're left with exactly the number that's missing from the sequence.
内容的提问来源于stack exchange,提问作者Dave
相关产品推荐
相关产品推荐

