实现用户的历史记录功能

实现用户的历史记录功能

案例:
很多应用程序都有浏览用户的历史记录的功能
例如:
浏览器查看最近访问的网页
视频播放器查看最近播放过的视频文件
shell查看用户输入的命令
......

现制作一个简单的猜数字游戏,添加历史记录功能,显示最近猜过的数字

解决思路:
使用容量为n的队列存储历史记录
使用标准库collections中的deque函数,它是一个双端循环队列

from random import randint
from collections import deque


N = randint(0,100)
history = deque([],6)

def GuessNum(k):
if k == N:
print ("your guess right.")
return True
if k < N:
print ("your guess number less-than N")
else:
print ("your guess number gteater-than N")
return False

while True:
line = input("please input a number:").strip()
if line.isdigit():
k = int(line)
history.append(k)
if GuessNum(k):
break
elif line == "history" or line == "h?":
print ("history:",history)

please input a number:50
your guess number gteater-than N
please input a number:20
your guess number less-than N
please input a number:25
your guess number less-than N
please input a number:h?
history: deque([50, 20, 25], maxlen=6)
please input a number:2
your guess number less-than N
please input a number:32
your guess number gteater-than N
please input a number:28
your guess number gteater-than N
please input a number:h?
history: deque([50, 20, 25, 2, 32, 28], maxlen=6)
please input a number:25
your guess number less-than N
please input a number:26
your guess right.

  

 

posted @ 2017-07-19 23:26  xie仗剑天涯  阅读(1092)  评论(0编辑  收藏  举报