I have been writing code in HackerRank to count how many valleys that a hiker (Gary) walked through in a hike. Right now, it looks something like this.
#Defining variables for later use and a list of Gary's steps
steps = ["U", "D", "D", "D", "D", "D", "U", "U"]
sea_level = 0
valleys = 0
#For loop to calculate how many valleys Gary hiked through
for step in steps:
step_ud = step
if step_ud == "U":
sea_level += 1
elif sea_level == 0:
valleys += 1
elif step_ud == "D":
sea_level -= 1
elif sea_level == 0:
valleys += 1
print(valleys)
When I run the code, however I receive no output. My expected output was 1, knowing that Gary only walked through 1 valley.
The term valley was defined as: "A valley is a non-empty sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level."
The question was written as: "Given Gary's sequence of up and down steps during his last hike, find and print the number of valleys he walked through."
I have taken a look at these 3 posts:
How to flush output of Python print?
python `print` does not work in loop
I have also tried some other methods, but they haven't helped. These are things I've tried.
I imported the sys module and used the sys.stdout.flush() function to flush the stdout.
import sys
...
#Loop with lines to determine whether it's a valley.
...
print(valleys)
sys.stdout.flush()
I've also tried making my own function of flushing the stdout, but that didn't work either.
def my_print(text):
sys.stdout.write(str(text))
sys.stdout.flush()
Then I used the function after printing to flush.
import sys
...
#Loop with lines to determine whether it's a valley.
...
print(valleys)
my_print(text)
Currently I'm pretty lost in knowing what I have to fix. Thanks for the help.