# [Python] A program that counts the number of valleys

▼ Question

--Start from 0 height --If it is U, it is on 1. If it is D, it goes down by 1. ――The end will always be at a height of 0. --Calculate the number of valleys from the start to the end.

url

▼sample input

#### `python`

``````
8
UDDDUDUU
``````

▼sample output

#### `python`

``````
1
``````

#### `Image of the road`

``````
_/\      _
\    /
\/\/
``````

#### `python`

``````
def countingValleys(n, s):
#U and D as 1-Convert to 1
ss = list(map(int, (s.replace("U","1 ").replace("D","-1 ").split())))

#Condition to become a valley (0->-Find the number of occurrences of 1)
x=0
ans=0
for i in ss:
if x==0 and x+i < 0:
ans+=1
x += i
return ans

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()
``````

・ Avid hiker avid: enthusiastic hiker: hiker

・ Emeticulously Pay close attention He tracks his hikes meticulously. A detailed record of hikes.

・ Topography terrain Paying close attention to small details like topography.

## Make the for statement one sentence.

▼ my answer (if is a culture)

#### `python`

``````
def countingValleys(n, s):
#U and D as 1-Convert to 1
ss = list(map(int, (s.replace("U","1 ").replace("D","-1 ").split())))

#Write if in one sentence
x = ans=0
for i in ss:
ans += 1 if x==0 and x+i < 0 else 0
x += i
return ans
``````

`[Expression for True] if [Condition] else [Expression for False]`

• Pass cannot be used after else. → It moved like that at 0.

For further simplification, I tried to use the comprehension notation, but I didn't know how to write the comprehension notation when there are multiple expressions in the for statement.