Python约瑟夫环经典问题
30 个人在一条船上,超载,需要 15 人下船。
于是人们排成一队,排队的位置即为他们的编号。
报数,从 1 开始,数到 9 的人下船。
如此循环,直到船上仅剩 15 人为止,问都有哪些编号的人下船了呢?
方法一:
不下船的人依次排到最后,直到队伍剩下15个人为止
def JosephDeathGame1(nums,step,stay):
people = list(range(1,nums+1))
while len(people)>stay:
i = 1
while i<step:
people.append(people.pop(0))
#print(people)
i += 1
print('{:2d}号下船了'.format(people.pop(0)))
people.sort()
print('最后留下的人的号码:{}'.format(people))
JosephDeathGame1(30,9,15)
方法二:
每九个人下船一个,前八个排到队伍最后,第9个人下船,直到队伍剩下15个人为止
def JosephDeathGame2(nums,step,stay):
people = list(range(1,nums+1))
while len(people)>stay:
print('{:2d}号下船了'.format(people.pop(step-1)))
#print(people)
people += people[0:step-1]
del people[0:step-1]
print('最后留下的人的号码:{}'.format(sorted(people)))
JosephDeathGame2(30,9,15)