How to Solve Josephus Problem using Linked List in Python

In this tutorial, we will learn how to program "How to Solve the Josephus Problem Using a Linked List in Python." The objective is to solve the Josephus problem. This tutorial will guide you step by step through the process of solving the Josephus problem using a linked list. By the end of this tutorial, you will have a solid understanding of how to implement this task effectively in Python, helping you strengthen your problem-solving abilities and improve your coding skills.

This topic is straightforward and easy to understand. Simply follow the instructions provided, and you will complete it with ease. The program will guide you step by step through the process of solving the Josephus problem. So, let's dive into the coding process!

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. class Node:
  2.     def __init__(self, data):
  3.         self.data = data
  4.         self.next = None
  5.  
  6.  
  7. class CircularLinkedList:
  8.     def __init__(self):
  9.         self.head = None
  10.  
  11.     def append(self, data):
  12.         node = Node(data)
  13.         if self.head is None:
  14.             self.head = node
  15.             node.next = node
  16.         else:
  17.             temp = self.head
  18.             while temp.next != self.head:
  19.                 temp = temp.next
  20.             temp.next = node
  21.             node.next = self.head
  22.  
  23.     def remove(self, node):
  24.         if self.head.next == self.head:
  25.             self.head = None
  26.             return
  27.  
  28.         prev = self.head
  29.         while prev.next != node:
  30.             prev = prev.next
  31.  
  32.         prev.next = node.next
  33.         if node == self.head:
  34.             self.head = node.next
  35.  
  36.     def display(self):
  37.         if not self.head:
  38.             return
  39.         temp = self.head
  40.         while True:
  41.             print(temp.data, end=" ")
  42.             temp = temp.next
  43.             if temp == self.head:
  44.                 break
  45.         print()
  46.  
  47.  
  48. def josephus(cllist, k):
  49.     execution_order = []
  50.     current = cllist.head
  51.  
  52.     while cllist.head and cllist.head.next != cllist.head:
  53.         for _ in range(k - 1):
  54.             current = current.next
  55.  
  56.         execution_order.append(current.data)
  57.         print(f"Executed: {current.data}")
  58.  
  59.         next_node = current.next
  60.         cllist.remove(current)
  61.         current = next_node
  62.  
  63.         print("Remaining:", end=" ")
  64.         cllist.display()
  65.  
  66.     return execution_order, cllist.head.data
  67.  
  68.  
  69. while True:
  70.     print("\n============= Solve Josephus Problem using Linked List =============\n")
  71.  
  72.     n = int(input("Enter number of people: "))
  73.     k = int(input("Enter k (step count): "))
  74.  
  75.     index_type = input("Use 0-based indexing? (yes/no): ").strip().lower()
  76.     if index_type == "yes":
  77.         start = 0
  78.     else:
  79.         start = 1
  80.  
  81.     cllist = CircularLinkedList()
  82.     for i in range(start, start + n):
  83.         cllist.append(i)
  84.  
  85.     print("\nInitial circle:")
  86.     cllist.display()
  87.  
  88.     order, survivor = josephus(cllist, k)
  89.  
  90.     print("\nExecution Order:", order)
  91.     print("Survivor:", survivor)
  92.  
  93.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  94.     if opt == "no":
  95.         print("Exiting program...")
  96.         break
  97.     elif opt != "yes":
  98.         print("Invalid choice. Exiting program...")
  99.         break

This program solves the Josephus problem using a circular linked list. The user inputs the number of people (`n`) and the step count (`k`), and the program creates a circular linked list representing the people standing in a circle. It then iteratively removes every `k`‑th person, displaying each executed person and the remaining circle after every step. The program continues this process until only one person remains, ultimately displaying the full execution order of removed people and the survivor. Users can choose whether to use 0-based or 1-based numbering, and the simulation can be repeated multiple times.

Output:

There you have it we successfully created How to Solve Josephus Problem using Linked List in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials