-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloop_strategy.py
85 lines (72 loc) · 2.29 KB
/
loop_strategy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# 环策略
import random
from unicodedata import name
from tqdm import tqdm
# 初始化数据
scale = 100
max_find = 50
# 初始化环
def loop_init(scale):
# 初始化监狱人员编号
prisoner_card = [ i for i in range(1,scale+1)]
# 初始化箱子中的编号
prisoner = [ i for i in range(1,scale+1)]
random.shuffle(prisoner)
#print(prisoner)
# 建立字典(代表箱子中的编号,对应的纸条编号)
prisoner_dict = dict(zip(prisoner_card,prisoner))
# print(prisoner_dict)
return prisoner_dict
# 建立环搜索策略
def loop_generate(prisoner_dict):
flag = 1 # 假设成功
for key in prisoner_dict:
count = 1
ans = key
while prisoner_dict[key] != ans:
count += 1
if count > max_find: # 产生大于50的环时失败
flag = 0 # 标记失败
break
key = prisoner_dict[key]
if flag == 0: # 如果失败,则停止尝试
break
return flag
# 建立随机搜索策略
def random_strategy(prisoner_dict):
flag = 1 # 假设成功
for i in range(1,scale+1):
count = 1
find_path = [m for m in range(1,scale+1)] # 随机生成寻找路线
random.shuffle(find_path)
for j in find_path:
while prisoner_dict[j] != j:
count += 1
if count > max_find: # 未能找到标记失败
flag = 0
break
if flag == 0:
break
return flag
# 建立策略(尚未完成)
def loop_strategy(prisoner_card,prisoner_dict):
note = prisoner_dict[prisoner_card]
if __name__ == "__main__":
# 模拟次数
num_simulate = 10000
# 记录模拟成功次数
num_success = 0
# 环策略模拟
for i in tqdm(range(num_simulate)):
prisoner_dict = loop_init(scale)
if loop_generate(prisoner_dict) == 1:
num_success += 1
print(f"环策略成功概率:{num_success/num_simulate}")
# 成功次数初始化
num_success = 0
# 随机策略模拟
for i in tqdm(range(num_simulate)):
prisoner_dict = loop_init(scale)
if random_strategy(prisoner_dict) == 1:
num_success += 1
print(f"随机策略成功概率:{num_success/num_simulate}")