序文: このコードは、素数ではなく、フィボナッチ数を見つけていることに気付きました。
質問: 何らかの理由で、savework()
機能が動作していません。Python インタラクティブ セッションを実行して を繰り返し実行するget_next_prime()
と、そのセッション内で意図した順序で次の番号が生成されます。ただし、セッションを閉じて新しいセッションを開くと、(pickle.dump
などの理由で) 以前のエントリが記憶されているはずですが、そうではありません。実行ごとにピクルされたバイトファイルを呼び出す必要があります。なぜそうではないのですか?
初心者です:お手柔らかにお願いします。ありがとうございました!
コード:
# Write a function which, for each run, returns the smallest positive prime number larger than the one returned previously.
""" Find and maintain a cumulative list of Prime numbers """
import pickle
import atexit
try:
with open("dict_of_primes","rb") as file1, \
open("last_prime_index_found","rb") as file2:
dict_of_primes = pickle.load(file1)
last_prime_index_found = pickle.load(file2)
# Start fresh if either file could not be found
except FileNotFoundError:
dict_of_primes = {}
last_prime_index_found = -1
def get_next_prime():
""" Get the next prime number """
global last_prime_index_found
n = last_prime_index_found + 1
if n in [0,1]:
dict_of_primes[n] = n
else:
dict_of_primes[n] = \
dict_of_primes[n-1] +\
dict_of_primes[n-2]
last_prime_index_found = n
return dict_of_primes[n]
def save_work():
""" Saves data for next session """
with open("dict_of_primes","wb") as file1, \
open("last_prime_index_found","wb") as file2:
pickle.dump(dict_of_primes,file1)
pickle.dump(last_prime_index_found,file2)
# This will insure that save_work() is called
# when you end your session
atexit.register(save_work)
Python インタラクティブ セッション:
`C:\Users\Fiona Murphey\Desktop>python`
`Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32`
`Type "help", "copyright", "credits" or "license" for more information.`
`>>> from lastprime import *`
`>>> get_next_prime()`
`0`
`>>> get_next_prime()`
`1`
`>>> get_next_prime()`
`1`
`>>> get_next_prime()`
`2`
`>>> get_next_prime()`
`3`
`>>> get_next_prime()`
`5`
`>>> save_work()`
`>>> exit()`
端末内:-
C:\Users\Fiona Murphey\Desktop>python
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from lastprime import *
>>> get_next_prime()
0
>>>