0

I am unable to understand as to why the below code does not return the value of 'out' despite it containing values (as evident by uncommenting the print statement)

# Goal is to reverse a list using recurcive functions. 
# Ex: [1,'yes', 8, 'pipe', 102]  - > [102, 'pipe', 8, 'yes', 1]

inp = [1,'yes', 8, 'pipe', 102]
out = []
def recFn(ctr, out):

  if ctr == len(inp)-1:
    return out
  else:
    out = [inp[ctr]] + out

  # print(out)

  recFn(ctr+1, out)

recFn(0, out)

I get NO output. Can someone tell me why this is the case?

Krishna
  • 115
  • 6
  • 1
    Print the result: `print(recFn(0, out))` – Mad Physicist Jul 02 '22 at 23:07
  • _I get NO output_ There isn't a print statement anywhere in this code. Why are you expecting to see output? – John Gordon Jul 02 '22 at 23:09
  • Even when I try storing the function call (last line) in a variable and print the variable, it does not show any output. – Krishna Jul 02 '22 at 23:10
  • Also, on the last line of the function, the function _calls_ itself but does not _return_ the value. – John Gordon Jul 02 '22 at 23:11
  • @MadPhysicist that does not work, since the function is returning a value – Krishna Jul 02 '22 at 23:11
  • @JohnGordon I was actually running this in Colab, so was expecting the cell to show the "return" output. Also, I am trying to use the IF statement to return the final list – Krishna Jul 02 '22 at 23:13
  • Two changes needed to get function to work: 1) condtion should be `if ctr == len(inp):` and 2) need `return recFn(ctr+1, out)` at bottom of function. – DarrylG Jul 02 '22 at 23:13
  • Adding "return" to the recursive function call (line: last-1) worked. Thank you @DarryIG !! – Krishna Jul 02 '22 at 23:24
  • @DarrylG comment is right, but why we need to return the function ? The main purpose of recursion is to execute the same functionality on smaller sub-set of the problem. Without return statement the pervious function call invoke is lost, to understand this more, try to print out the values of out, with return statement, and without return statement, you will notice at the end of recursion function call assigned to None, which makes a lot of sense, since the last recursive call is lost,, since the function does not return the recursive call. – araldhafeeri Jul 02 '22 at 23:27
  • @araldhaferri yes got it. Makes a lot of sense now! – Krishna Jul 02 '22 at 23:29

0 Answers0