Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Recursion within Class

Tags:

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() 
like image 307
Rabbitybunny Avatar asked Jul 24 '13 20:07

Rabbitybunny


People also ask

Can a class be recursive?

When an object of some class has an attribute value of that same class, it is a recursive object.

How do you call a recursive function in Python?

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).

Can I call a function inside itself Python?

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.

How do you break a recursion in Python?

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.


1 Answers

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, ....) 
like image 75
freakish Avatar answered Sep 20 '22 22:09

freakish