python版约瑟夫环
#! /usr/bin/env python3#coding = utf-8
import itertools
def josef(list0, start, interval):# start为开始删除的元素下标,interval为间隔
removed_list = []# 建立用于保存被删除元素的列表
round_cycle = itertools.cycle(list0)# 建立循环遍历list0的生成器
for i in range(start):
current_element = next(round_cycle)# 定位当前元素
removed_list.append(current_element)# 将start位置的元素放入删除列表
while len(removed_list) < len(list0):
count = 0# 计数放在for循环外,每剔除一个元素后归零
for i in range(interval):# 循环开始
while count < interval:# 计数开始
current_element = next(round_cycle)
if current_element not in removed_list:
count += 1
removed_list.append(current_element)
print('removed_list={}'.format(removed_list))
return removed_list[-1]
def main():
test_list =
print('test_list={}'.format(test_list))
print('last_one={}'.format(josef(list0=test_list, start=2, interval=3)))
if __name__ == '__main__':
main()
# 结果输出
'''
test_list=
removed_list=
last_one=9
'''
页:
[1]