countingValleys HackerRank Solution:Looking for countingValleys solution for Hackerrank problem? Get solution with source code and detailed explainer video
An avid hiker keeps meticulous records of their hikes. During the last hike that took exactly steps, for every step it was noted if it was an uphill,U, or a downhill,D step. Hikes always start and end at sea level, and each step up or down represents a 1 unit change in altitude. We define the following terms:
A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level.
A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.
Given the sequence of up and down steps during a hike, find and print the number of valleys walked through.
Go to problem statement
Youtube Channel partner: CodingCart
Mentor: Satyendra Jaiswal
Source Code: for
# Write your code here def countingValleys(steps, path): count=0 res=0 for c in path: if c=='U': count+=1 else: count-=1 if count==0 and c=='U': res+=1 return res
Full Source Code: countingValleys
#!/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 # # Write your code here def countingValleys(steps, path): count=0 res=0 for c in path: if c=='U': count+=1 else: count-=1 if count==0 and c=='U': res+=1 return res 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()
This post is in partner with CodingCart.