-2

I want to define a function as f(a,b) such that it generates a series as: 10,8,6,4,2,0,2,4,6,8,10 if a=10 and b=2 using Recursion.

def pattern(a,b):
    if a-b < 0:    
        print(a)
        return pattern(a+b,b)
        print(a)
    else:
        print(a)
        return pattern(a-b,b)

The result I get is

10
8
6
4
2
0
2
0
2
0
.....  infinity

... but this is wrong.

Austin
  • 25,759
  • 4
  • 25
  • 48

1 Answers1

2

You just need to use recursion

from __future__ import print_function
def psearch(a,b):
  if a > 0:
    print(a,end = ',')
    psearch(a - b,b)
    print(',',end="")
    print(a,end = "")
  else:
    print(a,end="")

psearch(12,5)
print()

OUTPUT

12,7,2,-3,2,7,12 
Albin Paul
  • 3,330
  • 2
  • 14
  • 30