-3

I wrote a function to traverseMountain(altitude, stepsleft, substring) as helper function to part of a solution to one of the hackerrank problems. I consider it better practice to test functions as I write them, and this is where I am encountering my problem.

#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the countingValleys function below.
def countingValleys(n, s):
    altitude = 0
    mountiansCount = 0
    valleysCount = 0
    def tailRecurseSolution(stepsleft, substring):
        head, tail = substring[0], substring[1:]
        if (head == 'U'):
            mountiansCount+=1
            traverseMountain(n-1, tail)
        if (head == 'D'):
            traverseValley(altitude+1, n-1, tail)
    

#    return valleysCount

    
def traverseMountain(altitude, stepsleft, substring):
    head, tail = substring[0], substring[1:]
    if (head=="D"):
         altitude-=1
    if (head=="U"):
         altitude+=1
    stepsleft-=1
    if (altitude<=0 or stepsleft<=0 or (not tail)):
        x = stepsleft
        return x
    elif (altitude>0 and stepsleft>0 and tail):
        traverseMountain(altitude, stepsleft,tail)


#def traverseValley(alt, stepsleft, substring):
#    return x

if __name__ == '__main__':
    altitude = 0
    stepsleft = 99
    path = "UUUDUDDD"
    print(traverseMountain(altitude, stepsleft, path))

You can ignore the countingValleys function as its imcomplete and not being called.

What I was expecting to happen was for the function traverseMountian to meet the if conditional, and would step into the block upon the last recursive call (when altitude variable is 0 or the tail is the empty string) and then exit the function and return the value of the stepsLeft variable.

What I am witnessing is that my debugger steps inside of that if statement, but immediately jumps to inside the elif statement (I do not understand why it would do that) and the variables I receive are reset?

I wanted to make a post here in case it's intended behaviour of the code I've spent a lot of time today just trying to figure out why Python does not terminate the function after the return statement. I've played out with the conditionals, the placing of the return statement etc. but without success.

Eoin Dowling
  • 373
  • 3
  • 15
  • 1
    You don't need those images; they are unreadable anyway. The problem is you aren't returning the return value from the recursive call. – chepner Feb 02 '20 at 19:00

1 Answers1

2

You're returning x but in your recursion call you're not doing anything with the return value.

You might want return traverseMountain(altitude, stepsleft,tail) as your last line in traverseMountain?

scign
  • 812
  • 5
  • 15