[Python] Python Recursion within Class [duplicate]

Discussão em 'Python' iniciado por Stack, Setembro 29, 2024.

  1. Stack

    Stack Membro Participativo

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

    Continue reading...

Compartilhe esta Página