I tried to make a python code that would answer the Joseph problem. I really had a hard time with this and the try blocks was the only thing I could come up with. Can anyone tell me if the way I did it is valid or I have to rewrite the code because its too bad?
The problem is:
People are standing in a circle waiting to be executed. Counting begins at a specified point in the circle and proceeds around the circle in a specified direction. After a specified number of people are skipped, the next person is executed. The procedure is repeated with the remaining people, starting with the next person, going in the same direction and skipping the same number of people, until only one person remains, and is freed.
The problem — given the number of people, starting point, direction, and number to be skipped — is to choose the position in the initial circle to avoid execution.
My solution:
class Game:
def __init__(self, n):
self.n = n
self.ppl = []
self.has_gun = 1
def creating_list(self):
for i in range(1, self.n+1):
self.ppl.append(i)
def kill(self):
number = self.ppl.index(self.has_gun)
try:
print("{} shoots {}".format(self.has_gun, self.ppl[number + 1]))
del self.ppl[number + 1]
except IndexError:
print("{} shoots {}".format(self.has_gun, self.ppl[0]))
del self.ppl[0]
try:
print("{} gives his gun to {}".format(self.has_gun, self.ppl[number+1]))
self.has_gun = self.ppl[number + 1]
except IndexError:
if len(self.ppl) > 1:
print("{} gives his gun to {}".format(self.has_gun, self.ppl[0]))
else:
print("{} is the only one remaining person in the circle".format(self.ppl[0]))
self.has_gun = self.ppl[0]
print("*" * 40)
def run(self):
self.creating_list()
while True:
self.kill()
if len(self.ppl) == 1:
print("{} survives".format(self.ppl[0]))
break
while True:
try:
question = int(input("How many people in the circle do you want to be?\n"))
break
except:
print("Type a number\n")
cos = Game(question)
cos.run()