# Inverse cascade challenge - Recursion

Print the following pattern, when you invoke inverse_cascade(1234)

1
12
123
1234
123
12
1

Solution:

def grow(n):
if n < 10:
print(n)
else:
grow(n // 10)
print(n)
def shrink(n):
if n < 10:
print(n)
else:
print(n)
shrink(n // 10)
grow(n // 10)
print(n)
shrink(n // 10)

Using a recursion approach, how can I improve this code without using higher order functions?

Note: No data models have to be used.

Separate grow and shrink functions are not necessary. Instead you can have a single function that prints, recurses and prints again the same value when the recursion returns.

For example like this:

n = str(n)
print(n[:digits])
if digits < len(n):
print(n[:digits])

In grow():

if n < 10:
print(n)
else:
grow(n // 10)
print(n)

print(n) is called in any case, so this can be simplified to

if n >= 10:
grow(n // 10)
print(n)

The same applies to the shrink() function.

And in

grow(n // 10)
print(n)
shrink(n // 10)

the print(n) can be eliminated by calling either grow() or shrink() with n instead of n \\ 10.

Also your code produces three output lines for a single-digit input because grow(n // 10) and shrink(n // 10) is called even if n < 10.

Together:

def grow(n):
if n >= 10:
grow(n // 10)
print(n)
def shrink(n):
print(n)
if n >= 10:
shrink(n // 10)
grow(n)
if n >= 10:
shrink(n // 10)

DRY your code. Don't Repeat yourself by having each branch do a print(). Pull it out and branch based on the recursive condition. (As Martin R has mentioned)

EDIT: OP's Question was changed such that the number is known ahead of time. Will leave the rest, but it isn't applicable to the OP's edit.

grow(n // 10)
print(n)
shrink(n // 10)

This works fine if you have a number you want to grow/shrink. However, you could generate the value 1234 based off the current level of recursion you are at.