ZeroDivisionError: integer division or modulo by zero error question

Asked 2 years ago, Updated 2 years ago, 59 views

I'm solving Josephus problem on Baekjun site (https://www.acmicpc.net/problem/1158), the code below is correct algorithm except for output format.

N, k = map(int, input().split())

A = [x for x in range (1,N+1)]
answer = []
idx = 0

for i in range(N):
    idx = (idx + k - 1) % len(A)
    answer.append(A[idx])
    del A[idx]

print(answer)

However, if I change the repetition statement fori in range(N): to whilelen(answer) <=N:, I get a ZeroDivisionError: integrer division or modulo by zero error. I think it's an error that doesn't have anything to do with the form of the repeat statement, but does anyone know why this error occurs?

python python3

2022-09-20 14:42

1 Answers

An error occurs when (idx+k-1)%len(A) becomes 0 when len(A).

I'll give you an additional answer. I thought you would fully understand with the above answer.

The while door will spin even after A is completely empty. So Len(A) becomes 0, and then when we meet the phrase above, the problem arises because we're going to do the division by 0, and to avoid this, we can add a condition to the when statement.


2022-09-20 14:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.