python - 尝试将斐波那契项添加到文件名时获取不完整的数据
问题描述
我有关于 load_fib、write_fib、fib 和 return_fib 的代码。我得到一个数字 n,需要加载最后计算的 fib 序列,并在文件名中添加 n 个额外的 fibonacci 项,并返回文件上写入的最后一个 fibonacci 数字。我想知道为什么我得到0
数据而不是0 1 1 2
尝试global_fib(3, filename)
然后with open(filename, "r") as f: ... data = f.read()
。
fib_called = False
def global_fib(n, filename):
global gf
gf = load_fib(filename)
i = 0
write_fib(filename)
while i < n:
fib()
write_fib(filename)
i += 1
return return_fib()
import os
def fib():
global fib_called
if len(gf) == 1:
gf.append(1)
else:
gf.append(int(gf[-1] + gf[-2]))
fib_called = not fib_called
def write_fib(filename):
global fib_called
if fib_called == True:
filename.open('w')
filename.write(str(gf[-1]) + ' ')
fib_called = not fib_called
import os.path
def load_fib(filename):
if os.path.exists(filename):
filename.open('r')
content == filename.read()
return list(content)
else:
f = open(filename,'w')
f.write('0' + ' ')
return [0]
def return_fib():
return gf[-1]
解决方案
在您的load_fib
函数中,当您分配包含文件数据的变量时会出现拼写错误 -
def load_fib(filename):
if os.path.exists(filename):
filename.open('r')
content == filename.read() # <-- this line
return list(content)
应该从 double equals 更改(用于测试相等性)
content == filename.read()
单等于(赋值)
content = filename.read()
推荐阅读
- assembly - 打开Calc.exe的Shellcode太长太复杂,看不懂!我的第一个漏洞利用程序
- javascript - Pact:用相同的端点编写不同的交互
- java - 从文本文件中读取用户名和密码并将它们与文本字段进行比较是行不通的,即使它们完全相同
- ios - locationManager.location 返回 nil
- node.js - 更新后的 npm 问题
- pgadmin-4 - 如何在 pgadmin 4 上使用 sql 选项卡
- html - 使用边框时伪元素不是完整的容器宽度
- mysql - 价格因月份而异的房产的数据库结构
- sqlite - asci hex 到 blob sql
- ios - 如何在 App Store 上私下上传应用程序?