Pnerd6

Josephus Problem

Mar 16th, 2022
715
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.85 KB | None | 0 0
  1. # Josephus Problem
  2.  
  3. def josephus(n, k):
  4.     # create a list of integers: [1, 2, ... , n]
  5.     lst = list(range(1, n+1))
  6.  
  7.     # initialize index to -1 as counting goes from index 0 to k the first time
  8.     ind = -1
  9.    
  10.     # the loop continues until all but one element has been removed
  11.     while len(lst) != 1:
  12.         # compute the index of the next element to be removed and remove that element
  13.         ind = (ind + k) % len(lst)
  14.         lst.remove(lst[ind])
  15.        
  16.         # Every time an element is removed, the rest of the elements to the
  17.         # right of it gets shifted one step to the left. So, the next count
  18.         # starts from the index to the left of the last one
  19.         ind -= 1
  20.  
  21.     # when only one element is left in the list, return that element
  22.     return lst[0]  
  23.  
  24. N, K = map(int, input().split())
  25. print(josephus(N, K))
  26.  
Advertisement
Add Comment
Please, Sign In to add comment