Python Recursion within Class

Question:

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()
Asked By: Rabbitybunny

||

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, ....)
Answered By: freakish

This is a code example that actually works

class Card():
    def __init__(self,cardsPlayedList,cardPosition):
        self.cardsPlayedList = cardsPlayedList
        self.cardPosition = cardPosition
    #    self.cardPosition

    def getNewCard(self,cardPosition):
        cardNum = 0
        cardInList = False
        
        cardNum = random.randint(1,len(cardList)-1)          # Get random card from List - 1 to 52 
        for x in self.cardsPlayedList:
            if(cardNum == x):
                cardInList = True                            

        if(cardInList == False):
            self.cardsPlayedList.insert(self.cardPosition, cardNum)    # if card not already played then store in list
            return cardNum
        else:
            return self.getNewCard(cardPosition)   
Answered By: user14730382
# USING FUNCTION    
def function_recursion(number):
    if number <= 1:
        return number
    else:
        return (number + function_recursion(number - 1))
result = function_recursion(5)
print("function recurssion: ", result)

#USING CLASS
class Recursion:
    def __init__(self, number):
        self.number = number
        
    def recur(self):
        if self.number <= 1:
            return True
        else:
            return (self.number + self.recur(self.number - 1))
result = Recursion(3)
print("Recurssion using class: ",result.recur())
Answered By: Abayomi Olowu
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.