Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

python - Runtime error in CSES problem set Missing Number

The problem:

You are given all numbers between 1,2,…,n except one. Your task is to find the missing number. The first input line contains an integer n. The second line contains n?1 numbers. Each number is distinct and between 1 and n (inclusive). Print the missing number. Constraints 2≤n≤2?105 Example Input: 5 2 3 1 5 Output: 4

This is the code that I've tried:

n=int(input())
arr = list(map(int,input().strip().split()))[:n-1]
arr.sort(reverse=True)
for i in range(n-1):
  if(arr[i]-arr[i+1]>1):
    print(arr[i]-1)
    break

I've also tried this:

n=int(input())
arr = list(map(int,input().strip().split()))[:n-1]
arr.sort(reverse=True)
for i in range(n-1):
  if n-1==1 and arr[0]==1:
    print(2)
    break
  elif n-1==1 and arr[0]==2:
    print(1)
    break
  elif i==n-1:
    print(arr[i]-1)
    break
  elif arr[i]-arr[i+1]>1:
    print(arr[i]-1)
    break

I'm getting a Runtime error in a few test cases:

Error:
Traceback (most recent call last):
  File "input/code.py", line 14, in <module>
    elif arr[i]-arr[i+1]>1:
IndexError: list index out of range

How can I fix this?

question from:https://stackoverflow.com/questions/65898068/runtime-error-in-cses-problem-set-missing-number

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You might want to try:

n=int(input())
arr = list(map(int,input().strip().split()))[:n-1]
arr.sort(reverse=True)
for i in range(n-1):
  if n-1==1 and arr[0]==1:
    print(2)
    break
  elif n-1==1 and arr[0]==2:
    print(1)
    break
  elif i==n-2:
    print(arr[0]+1)
    break
  elif arr[i]-arr[i+1]>1:
    print(arr[i]-1)
    break

This will remove your error list index out of range. Also, a faster way to approach this problem can be:

n = int(input())
print(n * (n + 1) // 2 - sum(map(int, input().split())))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...