Answer to Question #278255 in Python for Chiarra

Question #278255

The Josephus' problem is notoriously known. For those who are not familiar with the original problem: from among n people, numbered 1, 2, ..., n, standing in circle every mth is going to be executed and only the life of the last remaining person will be saved. Joseph was smart enough to choose the position of the last remaining person, thus saving his life to give us the message about the incident. For example when n = 6 and m = 5 then the people will be executed in the order 5, 4, 6, 2, 3 and 1 will be saved.INPUTEach line contains of 3 integers nand p.  n is the number of people to be executed.  m is the interval on how the people are to be executed.  p is the starting position of the execution.OUTPUTPrint the number of the person who will be saved from the execution

1
Expert's answer
2021-12-11T01:58:33-0500
# Python code for Josephus Problem

def Josh(person, k, index):


   

  # Base case , when only one person is left


  if len(person) == 1:


    print(person[0])


    return


   

  # find the index of first person which will die


  index = ((index+k)%len(person))


   

   # remove the first person which is going to be killed


  person.pop(index)


   

  # recursive call for n-1 persons


  Josh(person,k,index)

 
# Driver Program to test above function

n = 14 # specific n and k  values for original josephus problem


k = 2


k-=1   # (k-1)th person will be killed

 

index = 0

 
# fill the person vector

person=[]


for i in range(1,n+1):


  person.append(i)

 
Josh(person,k,index)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS