recursion

Taking looped inputs and outputs


Think of me trying to make a program that goes on to calculate Fibonacci numbers in a sequential order forever. I want to make the command produce output and treat the output as an input by performing some operation on it. How would I write such a program in python and how would I get it to stop if it's not going to automatically stop after a certain point?

So I have tried manually inputting values but don't know how to do it automatically as I am a newbie.


Solution

  • to calculate Fibonacci numbers in a sequential order...

    So you'd have a function for that calculation. A generator could be a choice:

    def gen_fib():
        a, b = 0, 1  # Let's start the sequence with 1 (not 0)
        while True:
            yield b
            a, b = b, a+b
    

    ...forever.

    That suggests you would just keep iterating over the iterator with a for loop:

    for a in gen_fib():
        # ...
    

    I want to make the command produce output...

    for a in gen_fib():
        print(a)  # output
    

    ...and treat the output as an input by performing some operation on it.

    prev = 2
    for a in gen_fib():
        print(a)  # output
        ratio = a / prev  # calculation
        prev = a
    

    how would I get it to stop if it's not going to automatically stop after a certain point?

    It is up to you to define the condition for when the program should stop. This could be the user just killing the program (then there is nothing to do), or some satisfactory state that is reached. For instance, maybe you want to print the ratio of two consecutive Fibonacci numbers, which is known to converge, and exit when that calculated ratio isn't changing by much anymore:

    def gen_fib():
        a, b = 0, 1  # Let's start the sequence with 1 (not 0)
        while True:
            yield b
            a, b = b, a+b
    
    
    prev, prev_ratio = 2, 2
    for a in gen_fib():
        ratio = a / prev   # calculation
        print(a, ratio)  # output
        if abs(ratio - prev_ratio) < 1e-16:
            break  # That ratio is good enough!
        prev, prev_ratio = a, ratio