Python recursive function printar correctly

Asked

Viewed 56 times

1

I am starting in python and I would like the result of my execution to be as follows:

[ [ 0 , 1 , 2 ] , [ 3 , 4 , 5 ] , [ 6 , 7 , 8 ] , [ 9 ] ]
[ ’ ∗ ∗ ∗ ∗ ’ , ’∗ ∗ ∗ ∗ ’ , ’ ∗ ∗ ’ ]

But I’m not getting it.

My code is like this:

def g(a, b):
    if len(a) < b: return [a]
    return [a[:b]] + g(a,b + 1)


print(g(list(range(10)), 3))
print(g("*" * 10, 4))

Could you help me?

1 answer

1


If the size of the sub-lists is fixed, then the value of b should not change. But you were adding 1 in the recursive call, which increases the size to be considered.

In fact what should change in the recursive call is the list itself, so just take from the "b-th" element on:

def g(a, b):
    if len(a) < b: return [a]
    return [a[:b]] + g(a[b:], b)

See the code running on Ideone.com.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.