-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.

0

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

6 Comments

2 issues: for example psearch(12,5) should give me 12,7,2,-3,2,7,12 but gives 12, 7, 2, 2, 7, 12 and towards the end 'None' is getting printed which should not be the case.
@MirMuhammadMurtaza Nope, it gives the output you have said 12 7 2 -3 2 7 12. I just verified it now.
@MirMuhammadMurtaza There is no None at the end produced in my program. It is because you are printing your function pattern() the function has None return value
12, 7, 2, -3, 2, 7, 12,. First point was my mistake. But there is a comma at the end when I use the argument in the print as end=', '. I need the commas but not at the end. Is there a way to achieve that ?
@MirMuhammadMurtaza I have edited the answer to add commas instead of spaces.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.