Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Filename: josephus_problem.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- Description:
- - This script simulates the Josephus problem, where a group of people
- stand in a circle and are sequentially eliminated based on a fixed counting
- rule until only one person remains.
- Requirements:
- - Python 3.x
- Functions:
- - find_last_person(n):
- Simulates the elimination process in the Josephus problem and returns
- the index of the last remaining person.
- Usage:
- - Run the script and input the number of people when prompted. The script
- will then find and print the index of the last remaining person. To exit,
- type '0' when prompted for input.
- Additional Notes:
- - The Josephus problem has a mathematical solution, but this script
- simulates the elimination process for demonstration purposes.
- """
- def find_last_person(n):
- """
- Simulates the elimination process in the Josephus problem and returns
- the index of the last remaining person.
- Args:
- n (int): The number of people in the circle.
- Returns:
- int: The index of the last remaining person.
- """
- circle = list(range(1, n + 1)) # Represent the circle of people with indices starting from 1
- p = 0 # Pointer to the current person
- # Simulating the elimination process
- while len(circle) > 1:
- # Each person counts twice per round
- p = (p + 2) % len(circle)
- # Eliminate the person at the current index
- circle.pop(p - 1 if p > 0 else len(circle) - 1)
- # Adjust pointer if needed
- p = p - 1 if p > 0 else len(circle)
- # Return the index of the last remaining person
- return circle[0]
- def main():
- """
- Main function to interact with the user and find the last remaining person.
- """
- while True:
- print("""
- _ _
- | | | |
- | | ___ ___ ___ _ __ | |__ _ _ ___
- _ | | / _ \ / __| / _ \| '_ \ | '_ \ | | | |/ __|
- | |__| || (_) |\__ \| __/| |_) || | | || |_| |\__ \\
- \____/ \___/ |___/ \___|| .__/ |_| |_| \__,_||___/
- | |
- |_|
- """)
- # Input the number of people
- n = input("\nEnter the number of people (or type '0' to exit): ")
- if n == '0':
- print("\nExiting Program... GoodBye!\n")
- break
- n = int(n)
- # Find and print the index of the last remaining person
- print("\nThe index of the last remaining person is:", find_last_person(n))
- # Prompt the user to hit enter to continue
- input("\nPress Enter to continue...")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement