python(履歴)

1077 ワード

ケース
簡単な数字を当てる小さなゲームを作って、履歴機能を追加して、ユーザーが最近当てた数字を表示して、どのように実現しますか?
ぶんせき
from random import randint
from collections import deque
import pickle

N = randint(0, 100)  #     0-100   
history = deque([], 5)  #        5         (   :    ,), [1, 2, 3, 4, 5] => [2, 3, 4, 5, 6]

def guess(k):
    if k == N:
        print("right")
        return True
    if k < N:
        print("%s is less than N" % k)
    else:
        print("%s is greater than N" % k)
    return False


while True:
    line = input("Please input a number: ")
    #         ,       ,              ,                  
    if line.isdigit():  
        k = int(line)  #   line    ,           int     
        history.append(k)
        if guess(k):
            break
    elif line == 'history'or line == 'h?':
        print(list(history))

#       , Python3 ,              (‘wb’,‘rb’),       
pickle.dump(history, open('history', 'wb'))  #    
q2 = pickle.load(open('history', 'rb'))  #    

print(q2)