R Shriya
R Shriya

Reputation: 43

Decrease value in Python

Stuck on a problem where I am supposed to decrease the value of n by a value of k using Python Recursion. If n = 10 and k = 2, my output should be:

10,8,6,4,2,0,2,4,6,8,10

n should decrease by k and then increase by k again. I wrote the below code:

def pattern(n):
    k = 2
    if n <=0:
        print(n, end= ",")
        #pattern(n+k)            
    else:
        print(n, end = ",")
        pattern(n-k)

pattern(5)

but my output is:

5, 3, 1,-1

My answer should be:

5,3,1,-1,1,3,5

Upvotes: 0

Views: 827

Answers (2)

Izaak van Dongen
Izaak van Dongen

Reputation: 2545

Here I've corrected your code:

def pattern(n, k, outer=True):
    print(n, end=",")
    if n > 0:
        pattern(n - k, k, False)
        if outer:
            print(n)
        else:
            print(n, end=",")

pattern(10, 2)
pattern(5, 3)

I've made k an argument to pattern.

I've also fixed the recursive algorithm. I think the most crucial part is that you need to print the number again after the recursive step.

There is also some logic to make sure no comma is printed at the end. This is a little convoluted, and if you're willing to use generators there's a much nicer way (that also removes the side-effects of the function, which is a plus):

def gen_pattern(n, k):
    yield n
    if n > 0:
        yield from gen_pattern(n - k, k)
        yield n

def fmt_gen_pattern(n, k):
    return ",".join(map(str, gen_pattern(n, k)))

print(fmt_gen_pattern(10, 2))
print(fmt_gen_pattern(5, 3))

Here is the output generated by either of these:

10,8,6,4,2,0,2,4,6,8,10
5,2,-1,2,5

This is not the same output as you spelled out, but I'm pretty sure this is what you meant.

Upvotes: 3

Ajay Dabas
Ajay Dabas

Reputation: 1444

Your method of recursion lacks the base case that will stop the recursion. Hence, it'll recurse infinitely and abort eventually.

Here are two correct approaches to do it.

def method1(current,direction,n,k):
    if current<=0:
        direction = 'Up'
    if direction=='Up' and current>=n:
        print(current,end=' ')
        return
    if direction=='Down':
        print(current,end=' ')
        method1(current-k,direction,n,k)
    else:
        print(current,end=' ')
        method1(current+k,direction,n,k)

def method2(n,k):
    if n<=0:
        print(n,end=' ')
        return
    print(n,end=' ') # This print shows decreasing n
    method2(n-k,k) # Recurse
    print(n,end=' ') # This print shows increasing n

n = 5
k = 2
# assert k<=n, "k cannot be greater than n" # Optional check
print('Method 1')
method1(n,'Down',n,k)
print('\nMethod 2')
method2(n,k)

Output

Method 1
5 3 1 -1 1 3 5 
Method 2
5 3 1 -1 1 3 5 

Upvotes: 0

Related Questions