HackerRank Counting Valleys
path = [1 if step == 'U' else -1 for step in path]
mountainArray = [0] * (steps + 2)
for i in range(len(path)):
mountainArray[i+1] = mountainArray[i] + path[i]seaLevls = [idx for idx, val in enumerate(mountainArray) if val == 0]#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'countingValleys' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER steps
# 2. STRING path
#
def countingValleys(steps, path):
# Write your code here
path = [1 if step == 'U' else -1 for step in path]
mountainArray = [0] * (steps + 2)
for i in range(len(path)):
mountainArray[i+1] = mountainArray[i] + path[i]
seaLevls = [idx for idx, val in enumerate(mountainArray) if val == 0]
valleys = 0
for i in range(1, len(seaLevls)):
left = seaLevls[i-1]
right = seaLevls[i]
if mountainArray[left + 1] < 0 and mountainArray[right - 1] < 0:
valleys += 1
return valleys
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
steps = int(input().strip())
path = input()
result = countingValleys(steps, path)
fptr.write(str(result) + '\n')
fptr.close()Last updated