Skip to content Skip to sidebar Skip to footer

Python Recursion Issue; I Can’t Change My Hard Code Into A Recursive Function

beside(picture,picture) #beside takes two pictures as arguments and prints them side by side in a 1:1 ratio. stackn(n,picture) #stackn takes a number and a picture

Solution 1:

I suppose you mainly need an idea of how you can do it and not a way to find someone that writes the code for you. I would suggest to use a n-ary beside operation in place of your one, in such a way to simplify the code for n=2,3,4,... Since I cannot modify it I will define a new one in terms of your binary operation in this way:

def beside_pictures(pictures):
    assert len(pictures) >0result= pictures[-1]
    for tmp in pictures[:-1:-1]:  # reverse order, starting from-1result= beside(tmp, result)
    returnresult

Now we are ready to transform your test function in a one line function:

def test(n, picture):
    assert n > 0show(beside_pictures([stackn(2**i,picture) for i in range(n)]))

UPDATE: If the requirement to have a recursive function is strict, one possible solution is the following one:

def test(n, picture):
    if n == 1:
        return stackn(1,picture)
    return beside(test(n-1, picture), stackn(2**(n-1),picture))

Post a Comment for "Python Recursion Issue; I Can’t Change My Hard Code Into A Recursive Function"