-
Notifications
You must be signed in to change notification settings - Fork 0
/
counting_valleys.py
48 lines (38 loc) · 1.05 KB
/
counting_valleys.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import os
# Complete the countingValleys function below.
def countingValleys(n, s):
steps = list(s)
up = down = sea_level = valleys = 0
for step in steps:
if step == 'U':
up += 1
else:
down += 1
if up == down:
if sea_level == -1:
if up == 1 and step == 'U':
valleys += 1
# reset
sea_level = up = down = 0
continue
elif up > down:
sea_level = 1
continue
elif down > up:
# Below sea level
if sea_level >= 0:
sea_level = -1
up = 0
continue
elif sea_level == -1:
if up == 1 and step == 'U':
valleys += 1
continue
return valleys
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
s = input()
result = countingValleys(n, s)
fptr.write(str(result) + '\n')
fptr.close()