30 个人在一条船上,超载,需要 15 人下船。
于是人们排成一队,排队的位置即为他们的编号。
报数,从 1 开始,数到 9 的人下船。
如此循环,直到船上仅剩 15 人为止,问都有哪些编号的人下船了呢?
这是一个链表的循环遍历问题。
虽然递归并不是解决这个问题的最佳实践,但是也能很好的练手。
# -*- coding:UTF-8 -*-
'''
30 个人在一条船上,超载,需要 15 人下船。
于是人们排成一队,排队的位置即为他们的编号。
报数,从 1 开始,数到 9 的人下船。
如此循环,直到船上仅剩 15 人为止,问都有哪些编号的人下船了呢?
calculate people who get down boat
'''
rangeCnt = 9
totle = 15
getDownList = []
def check(people, start, tempCnt):
print('tempCnt', tempCnt, 'start', start)
if (tempCnt > 0):
tempCnt += 1
for i in range(start, len(people)):
if (people[i] == 1):
tempCnt += 1
if (tempCnt == rangeCnt):
people[i] = 0
if (len(people) - len(getDownList) <&