Thursday, 31 December 2020

Lucky alive person in a circle sword puzzle - Python Datastructures Algorithm

Hi,The program I provided is an implementation of the famous Josephus problem, which is a theoretical problem named after the Jewish historian Josephus Flavius. The problem involves a circle of people numbered from 1 to n, and a count to skip, k. Starting from person 1, every k-th person is eliminated, and the process continues until only one person is left, who is declared the winner.

The program I provided implements a solution to this problem in Python. It uses a list to represent the circle of people, and iteratively removes people from the list until only one person is left. The program uses the modulo operator to ensure that the index of the person to remove wraps around to the beginning of the list if it goes past the end.

The program prompts the user to input the number of people in the circle and the count to skip, and then outputs the number of the lucky alive person who wins the game. This program can be used to play the Josephus game for any number of people and count to skip



def lucky_alive_person(n, k): people = list(range(1, n+1)) index = 0 while len(people) > 1: index = (index + k - 1) % len(people) people.pop(index) return people[0] n = int(input("Enter the number of people in the circle: ")) k = int(input("Enter the count to skip: ")) lucky_person = lucky_alive_person(n, k) print("The lucky alive person is:", lucky_person)




The lucky_alive_person function takes two arguments, n and k, which represent the number of people in the circle and the count to skip, respectively. The function initializes a list of people numbered from 1 to n, and sets the initial index to 0. Then, it enters a loop that continues until there is only one person left in the list. In each iteration, the function calculates the index of the person to remove using the formula (index + k - 1) % len(people), which ensures that the index wraps around to the beginning of the list if it goes past the end. The function then removes the person at that index from the list. Once the loop completes, the function returns the remaining person as the lucky alive person.

Above program prompts the user to enter the number of people in the circle and the count to skip, and then calls the lucky_alive_person function to find the lucky person. The program then prints the lucky person's number.thanks.

Labels:

0 Comments:

Post a Comment

Note: only a member of this blog may post a comment.

<< Home