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
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.
591 GDB gets version error when attempting to debug with the Presense SDK (IDE)
863 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
564 Who developed the "avformat-59.dll" that comes with FFmpeg?
564 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
© 2024 OneMinuteCode. All rights reserved.