25

我今天刚学python,所以天真地想写一个关于递归的代码。那么我们如何在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()

我试图定义自我,但想不出办法。有什么建议么?非常感谢你。


是的,下面的工作,谢谢。

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()
4

3 回答 3

22

类的每个方法都必须self作为第一个参数,即这样做:

def recur(self, num):

它现在应该可以工作了。

基本上幕后发生的事情是当你这样做时

instance.method(arg1, arg2, arg3, ...)

Python 确实

Class.method(instance, arg1, arg2, arg3, ....)
于 2013-07-24T20:04:51.350 回答
-1

这是一个实际有效的代码示例

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)   
于 2020-11-29T16:43:43.890 回答
-1
# 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 + recur(self.number - 1))
result = Recursion(3)
print("Recurssion using class: ",result.recur())
于 2021-03-25T09:52:09.543 回答