You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python生成指定长度斐波那契序列及字符串数值求和问题求助

问题描述

需要用Python实现两个需求:

  • 提取字符串中的整数(排除空格干扰),对最后两个数值求和,保留两位数完整性
  • 从原始字符串的两个起始值生成长度为5的斐波那契序列(每个新数为序列最后两数之和)

遇到的问题:执行newnumber= old[-1] + old[-2]时,取出的是数字“5”和空格,无法正确计算。

原始文件内容:

31 5

参考代码:

with open("C:\Users\dylan\Downloads\rosalind_fib.txt", "r") as old:
    old = old.read()
    ## An attempt to make the numbers the only elemenet, this did not work --> old = list(old)
new = open("C:\Users\dylan\Downloads\new.txt", "w")

## to test the values for each index --> print(old[###])

while len(old) < 6:
    newnumber= old[-1] + old[-2]
    old += newnumber
    if len(old) == 6:
        break
new.write(old)

new.close()
print(new)

期望输出:

31 5 36 41 77
解决方案

核心问题是你把文件读取的整个字符串直接操作,导致空格被当作序列的一部分。正确的做法是先将字符串分割为整数列表,再进行斐波那契序列生成:

修正后的代码:

# 读取并处理原始数据
with open(r"C:\Users\dylan\Downloads\rosalind_fib.txt", "r") as f:
    # 读取内容后按空格分割,转成整数列表
    sequence = list(map(int, f.read().split()))

# 生成长度为5的斐波那契序列
target_length = 5
while len(sequence) < target_length:
    # 取最后两个数求和
    next_num = sequence[-1] + sequence[-2]
    sequence.append(next_num)

# 将序列转为空格分隔的字符串并写入文件
result = " ".join(map(str, sequence))
with open(r"C:\Users\dylan\Downloads\new.txt", "w") as f:
    f.write(result)

print(result)

代码解释

  1. 读取并转换数据:用split()自动分割所有空格(包括换行符),得到纯数字字符串列表,再用map(int, ...)转成整数列表,彻底排除空格干扰。
  2. 生成序列:循环直到列表长度达到5,每次取最后两个整数求和,添加到列表末尾。
  3. 写入结果:将整数列表转为空格分隔的字符串,写入目标文件,同时打印结果。

内容的提问来源于stack exchange,提问作者Dylan Ellis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 21:01:21