Skip to content

Commit ff0c1a2

Browse files
committed
添加约瑟夫环
1 parent 362a545 commit ff0c1a2

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

josephus.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
' Circular sorting module '
5+
6+
__author__ = 'Chongsen Zhao'
7+
8+
9+
def cycle_sort(target, begin, step):
10+
""" 对原列表重新排序生成新列表
11+
12+
在原列表中从指定位置开始,按照步进每次取出一个元素放入新列表
13+
并把该元素从原列表中弹出,不参与下次排序
14+
15+
Args:
16+
target: 原列表
17+
begin: 起始位置
18+
step: 步进
19+
20+
Returns:
21+
排序后的新列表
22+
23+
Raises:
24+
TypeError: An error occurred accessing wrong data type.
25+
IndexError: An error occurred accessing invalid index.
26+
"""
27+
pos = begin - 1
28+
result = []
29+
30+
for i in range(len(target)):
31+
pos = (pos + step - 1) % len(target)
32+
result.append(target[pos])
33+
target.pop(pos)
34+
35+
return result
36+
37+
38+
if __name__ == "__main__":
39+
original = ['a', 'b', 'c', 'd']
40+
final = cycle_sort(original, 2, 2)
41+
print(final)
42+
43+
# *=====End File=====* #

0 commit comments

Comments
 (0)