I've gotten a little bit rusty with my Python having instead been working with Haskell and Prolog over the last 6 months. So I've been doing Hackerrank questions to attemp to refresh myself.
I'm on a windows machine, using Visual Studio Code. Environments I do not typically work on.
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. I've been using the Visual Studio Code debugger to step through the code I've written, which I have pasted below.
#!/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 written but I am just being eluded by what I have wrote, however this behaviour in my mind is very strange compared with previous experience with python execution.
Here are some screenshots of myself debugging through the code I've written. Each screenshot was taken having done one "step over" command with the debugger.
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.