We have a round table of
nis some positive integer. These have failed to satisfy the expectations of the mad king and are sentenced to death. However as an act of mercy he goes around the table killing every other knight (starting with the second) until only one knight remains.
The question is: which seat do you need to pick to survive?
I wrote the primitive code below to tackle this problem:
while True: temp_num = input("Enter the number of knights: ") try: temp_num = int(temp_num) if temp_num <= 0: # if not a positive int print message and ask for input again print("Sorry, the number of knights must be a positive integer, try again") else: knights_num = temp_num break except ValueError: print("That's not an integer!") # else all is good, val is >= 0 and an integer # Create a table of knights and a temp table knights_table = [i for i in range(1,knights_num+1)] knights_temp_table = list(knights_table) i = 1 while len(knights_temp_table)>1: # print("Knights =",knights_temp_table , "(",knights_temp_table[i],")") knights_temp_table.pop(i) i = (i+1)%len(knights_temp_table) print( "The knight who survived was no.",knights_temp_table )
The code runs fine and outputs the expected values
n=60> 57 and
n=16 > 1
However from the code it is not clear why it works. So i had some questions below
- Could the table of knights be made using a generator?
- Is a code using
knights_temp_table[i+2]and then iterating over the list for the exceptions clearer?
- Could one implement a linked list to make the code clearer instead of modulo?
I know the code is very simple and the problem I solved almost trivial. However any suggestions is much appreaciated since I am a semi-begginer / novice at python. * Are there any other general suggestions to improve the code, or running speed?