▼ 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.
▼sample input
python
8
UDDDUDUU
▼sample output
python
1
Image of the road
_/\      _
   \    /
    \/\/
▼my answer
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()
・ Emeticulously Pay close attention He tracks his hikes meticulously. A detailed record of hikes.
・ Topography terrain Paying close attention to small details like topography.
▼ 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]
Recommended Posts