I just learn python today, and so am thinking about writing a code about recursion, naively. So how can we achieve the following in python?
class mine: def inclass(self): self = mine(); def recur(num): print(num, end="") if num > 1: print(" * ",end="") return num * self.recur(num-1) print(" =") return 1 def main(): a = mine() print(mine.recur(10)) main()
I tried to define self, but could not think of a way to do so. Any suggestions? Thank you very much.
Yes the following work, thanks.
class mine: def recur(self, num): print(num, end="") if num > 1: print(" * ",end="") return num * self.recur(self, num-1) print(" =") return 1 def main(): a = mine() print(mine.recur(mine, 10)) main()
When an object of some class has an attribute value of that same class, it is a recursive object.
In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We use the k variable as the data, which decrements (-1) every time we recurse. The recursion ends when the condition is not greater than 0 (i.e. when it is 0).
In Python, it's also possible for a function to call itself! A function that calls itself is said to be recursive, and the technique of employing a recursive function is called recursion. It may seem peculiar for a function to call itself, but many types of programming problems are best expressed recursively.
One way to break out of a recursive function in Python is to throw an exception and catch that at the top level. Some people will say that this is not the right way to think about recursion, but it gets the job done.
Each method of a class has to have self
as a first parameter, i.e. do this:
def recur(self, num):
and it should work now.
Basically what happens behind the scene is when you do
instance.method(arg1, arg2, arg3, ...)
Python does
Class.method(instance, arg1, arg2, arg3, ....)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With