4
\$\begingroup\$

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

1
12
123
1234
123
12
1

Solution:

def inverse_cascade(n):
    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.

\$\endgroup\$
3
\$\begingroup\$

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:

def inverse_cascade(n, digits=1):
    n = str(n)
    print(n[:digits])
    if digits < len(n):
        inverse_cascade(n, digits+1)
        print(n[:digits])
\$\endgroup\$
2
\$\begingroup\$

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 inverse_cascade(n):
    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)
\$\endgroup\$
1
\$\begingroup\$

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.

def inverse_cascade(max_level, level=1, value=0):
    value = value * 10 + level
    print(value)

    if max_level != level:
        cascade(max_level, level + 1, value)
        print(value)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.