python实现约瑟夫环问题
#!/usr/bin/python# -*- coding:utf-8 -*-def initList(n):list = []for i in range(n):list.append(i+1)return listdef run_josephus(list, m):n = len(list)i = 0j = 0while n > 1:n = len(list)# .
·
#!/usr/bin/python
# -*- coding:utf-8 -*-
def initList(n):
list = []
for i in range(n):
list.append(i+1)
return list
def run_josephus(list, m):
n = len(list)
i = 0
j = 0
while n > 1:
n = len(list)
# print("i=",i,",j=",j)
# print("list=",list)
if i == m-1:
print(list[j])
list.remove(list[j])
i = 0
n = len(list)
if j == n:
j = 0
continue
else:
i = i+1
if j == n-1:
j = 0
else:
j = j+1
print(list[0])
m = 3
for n in range(11):
list = initList(n+1)
print(list)
run_josephus(list, m)
'''
n = 3
list = initList(n)
print(list)
run_josephus(list, m)
'''
结果:
[1]
1
[1, 2]
1
2
[1, 2, 3]
3
1
2
[1, 2, 3, 4]
3
2
4
1
[1, 2, 3, 4, 5]
3
1
5
2
4
[1, 2, 3, 4, 5, 6]
3
6
4
2
5
1
[1, 2, 3, 4, 5, 6, 7]
3
6
2
7
5
1
4
[1, 2, 3, 4, 5, 6, 7, 8]
3
6
1
5
2
8
4
7
[1, 2, 3, 4, 5, 6, 7, 8, 9]
3
6
9
4
8
5
2
7
1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
3
6
9
2
7
1
8
5
10
4
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
3
6
9
1
5
10
4
11
8
2
7
更多推荐
已为社区贡献2条内容
所有评论(0)