励志成为优产的母猪--------猜数游戏 ,历史记录,pickle保存,队列deque

# pickle 可以处理复杂的序列化语法。(例如自定义的类的方法,游戏的存档等),存档以文件的形式保存   参见 https://www.cnblogs.com/abobo/p/8080447.html
# collections是Python内建的一个集合模块,提供了许多有用的集合类。参见 https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001411031239400f7181f65f33a4623bc42276a605debf6000
 1 # coding: utf-8
 2 import random
 3 import pickle
 4 from collections import deque
 5 
 6 n = random.randint(0, 100)  # 随机找出0-100之中的数
 7 history_list = deque([], maxlen=5)  # 限制最大长度
 8 try_num = 0
 9 print(n)
10 
11 
12 def pk(m):
13     if m != n:
14         if m > n:
15             print("大了")
16         else:
17             print("小了")
18         return False
19     return True
20 
21 
22 def h_print():# pickle取
23     ret = pickle.load(open('history', 'rb'))
24     return ret
25 
26 
27 def history(history_list): # pickle存
28     history_list = list(history_list)
29     pickle.dump(history_list, open('history', 'wb'))
30 
31 
32 while True:
33     try_num += 1
34     if try_num > 10:
35         print("尝试次数过多,您已经笨死了!!!")
36         break
37     m = input("输入您的答案:")
38     try:                               # 异常处理 防止用户输入字母
39         # m = input("输入您的答案:")
40         if len(m) == 0:
41             print("not null")
42         m = int(m)
43         history_list.append(m)
44         history(history_list)
45         if pk(m) == True:
46             print("以您的智商,居然TM答对了")
47             break
48     except ValueError:
49         if m == "h":
50             print("您猜数的历史记录:")
51             print(h_print())
52         else:
53             print("格式有误,请输入整数字")

 



# 注解:使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢了,因为list是线性存储,数据量大的时候,插入和删除效率很低。
#
# deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈
posted @ 2019-05-01 23:13  jum_blog  阅读(256)  评论(0编辑  收藏  举报

载入天数...载入时分秒...