實現使用者的歷史記錄功能

xie仗劍天涯發表於2017-07-19

實現使用者的歷史記錄功能

案例:
很多應用程式都有瀏覽使用者的歷史記錄的功能
例如:
瀏覽器檢視最近訪問的網頁
視訊播放器檢視最近播放過的視訊檔案
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.

  

 

相關文章