Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Python 

Recursion error

This gives me a recursion error:
Code
def f(n: int) -> bool:
return f(n) >= f(n+1)

How can I write this so it runs?

Thanks,
Oliver
Funtion f is defined with int parameter so you can call it with f(0) or any other integer. If you really want to call it as f(n) you need to define n.

Code
n=0
f(n)

I'm not sure what you're trying to do but this will always give you maximum recursion depth exceeded because you don't have an exit condition.

(Jul 16, 2022 03:16 PM)Sentience Wrote:  This gives me a recursion error:
Code
def f(n: int) -> bool:
return f(n) >= f(n+1)
This says n is undefined:
Code
f(n)

How can I write this so it runs?

Thanks,
Oliver

You have not defined n before calling the function.
Write the following line to define n.
Code
#Sample n value
n = 5
print(f(n))

EDIT:

SIM-574702 is right about the exit condition.
Its like a base case for an induction problem in math.
[Image: pdoOihY.png]
Code
# We represent elements of N_∞ as functions f : int -> bool, where we only care about
# the values of those functions for nonnegative inputs n, and the functions are
# assumed to satisfy f(n) >= f(n+1) for all n >= 0.

This is an excerpt of what I am talking about

It’s not supposed to call itself…


How can I write this:

Code
def f(n: int) -> bool:
return f(n) >= f(n+1)

Without recursion?


Edit: Solved…

Code
def g(f: typing.Callable[[int], bool], n: int) -> bool:
return f(n) >= f(n + 1)
Wait wtf how do call g()?


Turns out I can call g just by going

g
```
def f():
def g():
f()
# then call g() inside main thread
```
(Jul 19, 2022 10:26 AM)Sentience Wrote:  Wait wtf how do call g()?


Turns out I can call g just by going

g

Edit: This thread is solved


Possibly Related Threads...
Thread / Author Replies Views Last Post
[C#] by MiguelSanchezApr 16, 2022 05:26 AM 0 114 Apr 16, 2022 05:26 AM
Last Post: MiguelSanchez
[Java] by The BrokerMar 22, 2020 05:46 PM 4 227 Mar 22, 2020 05:46 PM
Last Post: MavenGradle
[Python] by LindrosJan 13, 2020 09:12 AM 6 160 Jan 13, 2020 09:12 AM
Last Post: Lindros