Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

Jupyter notebook Josephus Problem Code - Elgan Roberts.ipynb

22 views
Kernel: Python 2 (SageMath)
def Josephus(n): ''' Function that returns the position of the last remaining person in the circle. n is the number of people in the circle (people in the circle are numbered from 1 to n), every second person gets killed. ''' circle = [i + 1 for i in range(n)] #Creating a circle of n people numbered from 1 to n. i = 0 while len(circle) != 1: i = (i + 1) % len(circle) # .pop automatically skips one for us so we need to skip one less. # we use % so that the position in the cicle doesn't goes above the number of people in the circle. circle.pop(i) return circle[0] for n in range(1,21): print(n, Josephus(n))
(1, 1) (2, 1) (3, 3) (4, 1) (5, 3) (6, 5) (7, 7) (8, 1) (9, 3) (10, 5) (11, 7) (12, 9) (13, 11) (14, 13) (15, 15) (16, 1) (17, 3) (18, 5) (19, 7) (20, 9)
def orderJosephus(n): ''' Function that returns the order of killing and position of the last remaining person in the circle. n is the number of people in the circle (people in the circle are numbered from 1 to n), every second person gets killed. ''' circle = [i + 1 for i in range(n)] order_of_killing = [] # empty list to add the removed positions from the list circle. i = 0 while len(circle) != 1: i = (i + 1) % len(circle) order_of_killing.append(circle.pop(i)) return order_of_killing, circle[0] orderJosephus(8)
([2, 4, 6, 8, 3, 7, 5], 1)
import math def j(n): ''' A function that obtains the position of the last survivor using a formula. ''' return 1 + 2 * n - 2 ** (1 + math.floor(math.log(n, 2))) checks = [j(n) == Josephus(n) for n in range(1,2000)] all(checks)
True
def Josephusk(n, k): ''' Function that returns the killing order and position of the last remaining person in the circle. There are n people in the circle (people in the circle are numbered from 1 to n), every kth person is killed until there is only oneperson left. ''' circle = [i + 1 for i in range(n)] order_of_killing = [] i = 0 while len(circle) != 1: i = (i + k - 1) % len(circle) # .pop automatically skips one for us so we need to skip one less. #we use % so that the position never goes above the number of people in the circle order_of_killing.append(circle.pop(i)) #create a list of objects removed from circle return circle[0]
def phus(n, k): ''' A function that returns the position of survivor using recursion. ''' if n == 1: return 1 return ((phus(n - 1, k) + k - 1) % n) + 1
check = [phus(n, k) == Josephusk(n, k) for n in range(1,200) for k in range(1,200)] all(check)
True