码迷,mamicode.com
首页 > 其他好文 > 详细

问题7:如何实现用户的历史记录功能(最多n条)

时间:2018-04-06 20:21:18      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:对象   导入   style   print   容量   from   nbsp   n+1   运行   

实例:制作猜字游戏,添加历史记录功能,显示用户最近猜过的数字

 

解决方案:使用容量为n的队列存储历史记录

  1. 使用标准库colections中的deque,一个双端循环队列
  2. 程序退出前,可以使用pickle将队列对象存入文件,再次运行程序时将导入其中

deque(序列, n):生成一个容量为n的序列,当序列中存储第n+1个数据时,则从左/右将溢出一个数;

pickle.dump(python对象, 文件名, 文件权限):创建一个文件,并将一个python对象存储其中;

from collections import deque
from random import randint
import pickle

history = deque([], 5)
a = randint(0, 20)

def guss(b)
    if b == a:
        print(right)
        return True
    if b < a:
        print(%s is less-than a%b)
    else:
        print(%s is greater-than a%b)

while True:
    b0 = input(please input a number:)
    if b0.isdigit() and b0 =! history:
        b = b0
        history.append(b)
        if guss(b):
            break
pickle.dump(history, open(histoy, w))
#将历史记录存储值文件history;
q = pickle.load(open(history))
#读取history文件内的历史记录;

 

问题7:如何实现用户的历史记录功能(最多n条)

标签:对象   导入   style   print   容量   from   nbsp   n+1   运行   

原文地址:https://www.cnblogs.com/volcao/p/8728612.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!