Hackerrank Problem #2 On Python

Hacker rank Problem 


Hello Guys,
Welcome Today I solved Problem in Hackerrank website
This problem I solved in my way
Using for loop and if condition


So Guys See my Code ...
If anything else please point out and post your code if you solve very simple....

Question:

Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike he took exactly  steps. For every step he took, he noted if it was an uphill, , or a downhill,  step. Gary's hikes start and end at sea level and each step up or down represents a  unit change in altitude. We define the following terms:
  • 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.
  • 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 Gary's sequence of up and down steps during his last hike, find and print the number of valleys he walked through.
For example, if Gary's path is , he first enters a valley  units deep. Then he climbs out an up onto a mountain  units high. Finally, he returns to sea level and ends his hike.
Function Description
Complete the countingValleys function in the editor below. It must return an integer that denotes the number of valleys Gary traversed.
countingValleys has the following parameter(s):
  • n: the number of steps Gary takes
  • s: a string describing his path


----

import math
import os
import random
import re
import sys

def countingValleys(n, s):
s_list = list(s)
x,valley = 0,0
count = []
for i in range(len(s_list)):
if s_list[i] in 'U':
x += 1
count.append(x)
elif s_list[i] in 'D':
x += -1
count.append(x)
for i in range(len(count)):
if count[i] == 0:
if count[i-1] < 0:
valley += 1
print(valley)

n = int(input())
s = input()
countingValleys(n, s)

----


By PyKAR

Comments

Popular posts from this blog

Hardy - Ramanujan Number (Magic Number) Program in Python

FLAMES CODE ON PYTHON

Count Swap for Sorting in Python