前言:我意识到这段代码正在寻找斐波那契数字,而不是素数。
问题:由于某种原因,savework()
功能无效。当我运行python交互式会话并重复运行get_next_prime()
时,它会在该会话中按预期生成序列中的下一个数字。但是,当我关闭会话并打开一个新会话时,它应该记住之前的条目(因为pickle.dump
等),但不是。 应每次运行时调用pickle字节文件。为什么不呢?
我是初学者:请保持温柔。谢谢!
代码:
# 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
>>>