Home > Blockchain >  for loop in recursive function python
for loop in recursive function python

Time:07-20

I tried to use for loop in a recursive function to find all path that the child class related to its parents.

class A:
    pass
class B(A):
    pass
class C(A):
    pass
class F(A):
    pass
class L(C,B):
    pass
class D(B,F):
    pass
class M(L,D):
    pass


def bases(cls):
    if cls == object:
        return [object]
    
    for Class in cls.__bases__:
        return [cls]   bases(Class)


print(bases(M))
# the output should be this:
# [[M, L, C, A], [M, L, B, A], [M, D, B, A], [M, D, F, A]]

but the output is [M, L, C, A] . keyword Return didn't allow For Loop to do well . then I wrote the code like this:

for Class in cls.__bases__:
    path = [cls]   bases(Class)
return path

and the output would be [M, D, F, A] . I replaced return with yield but it didn't work and I get error:

TypeError: can only concatenate list (not "generator") to list

what can I do to solve this problem???

CodePudding user response:

Try the following implementation using recursion:

class A:
    pass
class B(A):
    pass
class C(A):
    pass
class F(A):
    pass
class L(C,B):
    pass
class D(B,F):
    pass
class M(L,D):
    pass

def bases(cls):
    if cls.__bases__ == (object, ): # if "root"
        return [cls.__name__]
    return [[cls.__name__, *granpas] for base in cls.__bases__ for granpas in bases(base)]

print(bases(M)) # [['M', 'L', 'C', 'A'], ['M', 'L', 'B', 'A'], ['M', 'D', 'B', 'A'], ['M', 'D', 'F', 'A']]
  • Related