2
$\begingroup$

My loop is pretty simple. The function takes in two parameters, a and b; both are integers where a<=b. The function will then create a list of numbers from a to b.

This is what I created:

 def cat(a,b):
     j = []      
     for i in range (a,b):
     j.append(a+1)
     a +=1

I honestly cannot figure out how to turn this into a recursive function.. I have tried things which I realize don't make any sense and I'm not really sure where to start. Any help would really be appreciated :) Thanks

$\endgroup$
  • 1
    $\begingroup$ The code you've shown us does not work in Python, as it is badly formatted. Also note that the a += 1 statement has no effect at all and you can just delete it. And also, there is no return statement. How about if you first show us a working solution without recursion, so that we can be sure you know what you're asking? $\endgroup$ – Andrej Bauer Jun 10 '17 at 12:28
  • 2
    $\begingroup$ This is awfully close to a programming question (which would be offtopic here), but answers that explore the principles of converting loops to recursion would be a good fit here. $\endgroup$ – Raphael Jun 10 '17 at 12:33
  • $\begingroup$ The range should be range(a,b+1). $\endgroup$ – Yuval Filmus Jun 10 '17 at 12:46
  • 1
    $\begingroup$ @Raphael IMO, it is a programming question, pure and simple. The question asks nothing about general principles. $\endgroup$ – David Richerby Jun 10 '17 at 13:10
1
$\begingroup$

Here is a recursive version of this procedure, in python:

def cat(a,b):
  if a == b:
    return [a]
  else:
    return [a] + cat(a+1,b)

Another option is

def cat(a,b):
  if a == b:
    return [b]
  else:
    return cat(a,b-1) + [b]

These conversions are heavily geared toward this particular function. Here is a more general conversion, in the context of state machines without input (inputs can easily be added):

def run_my_algorithm(state = None):
  if state is None:
    state = initial_state
  if is_final_state(state):
    return extract_answer(state)
  else:
    state = next_state(state)
    return run_my_algorithm(state)

Hopefully the notation is self-explanatory.

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