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

基于斐波那契数列的可断点续算Python函数开发需求

Preserving Fibonacci Calculation State in Python

Got it, here's a straightforward solution using a Python class to maintain the state of your Fibonacci sequence calculations. This way, you can pause after computing, say, the 150th number, and later jump straight to calculating the 400th without redoing all the work from the start.

The Solution: Stateful Fibonacci Generator

We'll use a class to track the last two computed Fibonacci numbers and our current position in the sequence. This persistent state is key to avoiding redundant calculations.

class FibonacciGenerator:
    def __init__(self):
        # Initialize with the first two Fibonacci numbers (F(0)=0, F(1)=1)
        self.prev_prev = 0  # Represents F(n-2)
        self.prev = 1       # Represents F(n-1)
        self.current_index = 1  # We start having calculated up to index 1

    def compute_to(self, target_index):
        if target_index < 0:
            raise ValueError("Fibonacci indices must be non-negative integers.")
        
        # Handle the base case for index 0 immediately
        if target_index == 0:
            return 0
        
        # If we've already calculated up to the target, return the value directly
        if target_index <= self.current_index:
            # If you need frequent access to earlier indices, add a cache list to store all computed values
            # For this problem's focus on forward calculation, we'll keep it simple here
            raise NotImplementedError("This implementation prioritizes forward calculation. Add a cache list if you need to access earlier indices often.")
        
        # Calculate from our last known index up to the target
        for _ in range(self.current_index + 1, target_index + 1):
            next_num = self.prev_prev + self.prev
            self.prev_prev, self.prev = self.prev, next_num
            self.current_index += 1
        
        return self.prev

How to Use It

Here's how you'd implement the exact scenario you described:

# Create an instance of our stateful generator
fib_calculator = FibonacciGenerator()

# Compute up to the 150th Fibonacci number (this "pauses" once done)
fib_150 = fib_calculator.compute_to(150)
print(f"150th Fibonacci number: {fib_150}")

# Now compute the 400th number—no need to recalculate the first 150!
fib_400 = fib_calculator.compute_to(400)
print(f"400th Fibonacci number: {fib_400}")

Key Notes

  • State Preservation: The class retains prev_prev, prev, and current_index between calls, so every compute_to only calculates the numbers it hasn't already computed.
  • Optional Caching: If you need to frequently access earlier indices (not just move forward), add a self.cache = [0, 1] list in the __init__ method, then append each new number to the cache as you compute it. This lets you return self.cache[target_index] directly if it's already stored.
  • Error Handling: Basic validation ensures you can't pass negative indices, with a note on extending functionality for backward lookups if needed.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 22:28:13