r/PythonLearning • • 2d ago

school

def fib(n):

if n <= 1:

return n

return fib(n - 1) + fib(n - 2)

n = int(input("Количество чисел: "))

for i in range(n):

print(fib(i), end=" ")

0 Upvotes

10 comments sorted by

•

u/Sea-Ad7805 1d ago

This post tries to explain recursion using the fibonacci sequence but fails.

Run program above by clicking Invocation Tree Web Debugger and see its state change step by step.

If you want to learn recursion use this explanation using invocation tree.

Recursion is a powerful tool in some situations, but in many other situations it can not (or should not) be used. If you are a beginner, first get very good with for-loops, while-loops, and functions. Then later on learn recursion.

8

u/RedAndBlack1832 2d ago

Did you have a question ?

2

u/PureWasian 2d ago

Thanks for sharing?

Note that you can make this more efficient with memoization. Otherwise you're repeating a lot of function call calculations, which makes the time complexity a lot worse: O( 2n ) instead of O(n)

2

u/Naive_Programmer_232 2d ago

yep that's a recursive fibonacci algorithm. only issue with this is if n grows large, you'll run into a stack overflow error, "maximum recursion depth exceeded". So, I'd consider maybe writing this iteratively to avoid that or do a memoized (dict) version (manually or via functools) for better performance.

1

u/Vplayzgamez 2d ago

I understand not. 😵‍💫

1

u/masterofaiml 2d ago edited 2d ago

I don’t know what you are trying to say here, but i guess you might be encountering some indentation errors. I have executed your program, it works, code expects an input integer value and its prints as expected once you provide a value to it. Click the below link to open your code directly in the browser and run it and input your desired value to see your output.

This link nothing but your code shared via share option in www.pythonmastery.io, just click and run your program. Just don’t give a higher number as an input, the higher input value, the longer your program runs, though your output will instantly appear in console. Hope this helps.

https://www.pythonmastery.io/#code=ZGVmIGZpYihuKToKIGlmIG4gPD0gMToKICByZXR1cm4gbgoKIHJldHVybiBmaWIobiAtIDEpICsgZmliKG4gLSAyKQoKbiA9IGludChpbnB1dCgi0JrQvtC70LjRh9C10YHRgtCy0L4g0YfQuNGB0LXQuzogIikpCgpmb3IgaSBpbiByYW5nZShuKToKIHByaW50KGZpYihpKSwgZW5kPSIgIik=

1

u/FackThutShot 2d ago

HTML Codeblocks exist

Randoms on the Internet:

-1

u/samoromi 2d ago

def fib(n): if n <= 1: return n return fib(n - 1) + fib(n - 2)

n = int(input("Количество чисел: ")) for i in range(n): print(fib(i), end=" ")