Home > other >  How do I make this function recursive?
How do I make this function recursive?

Time:09-22

I need to use the formula v = (start * 2) 5 to print the resulting values. The start parameter is the value in which the sequence starts and the count parameter is how many values get printed. I have no idea how to get the base case to get called.

def print_sequence_rec(start, count):
        else:
            v = (start * 2)   5
            print(v, end="")
            print_sequence_rec(start, count   1)

For example, the function print_sequence_rec(2, 5) should print 2 9 23 51 107 219

CodePudding user response:

Make that count - 1 instead of 1 so that count decreases by one each call. The base case is when count == 0.

You'll also need to do something with v. I suggest passing it to the recursive invocation.

def print_sequence_rec(start, count):
    # base case
    if count == 0:
        pass
    # recursive case
    else:
        v = (start * 2)   5
        print(v, end="")
        print_sequence_rec(v, count - 1)

Or more likely you should get rid of it and move the computation to the recursive call:

def print_sequence_rec(start, count):
    # base case
    if count == 0:
        pass
    # recursive case
    else:
        print(start, end="")
        print_sequence_rec((start * 2)   5, count - 1)

CodePudding user response:

John's answer does a nice job addressing your question, but this actually seems like a good case to use a generator.

For example...

def gen_sequence_rec(start, count):  
    while count >= 0:               
        yield start
        start = (start * 2)   5
        count -= 1

...then you can save the sequence as a list...

seq = list(gen_sequence_rec(2,5))

#[2, 9, 23, 51, 107, 219]

...and print however you want...

print(seq)

[2, 9, 23, 51, 107, 219]

print(' '.join([str(x) for x in seq]))

2 9 23 51 107 219 
  • Related