LoginSignup
0
1

More than 3 years have passed since last update.

【python】谷の数を数えるプログラム 

Last updated at Posted at 2020-06-06

【python】谷の数を数えるプログラム 

▼設問

  • 高さ0地点からスタート
  • Uだと1上に。Dだと1下に進む。
  • 終了は必ず高さ0地点になる。
  • スタートから終了までの谷の数を求める。

url

▼sample input

8
UDDDUDUU

▼sample output

1
進んだ道のイメージ
_/\      _
   \    /
    \/\/

▼my answer

def countingValleys(n, s):
    #UとDを1と-1に変換
    ss = list(map(int, (s.replace("U","1 ").replace("D","-1 ").split())))

    #谷になる条件(0->-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:熱心な
hiker:ハイカー

・meticulously
細心の注意を払って
He tracks his hikes meticulously.
ハイキング(hikes)を細かく記録。

・topography
地形
Paying close attention to small details like topography.


for文を一文にする。

▼my answer(ifを一文化)

def countingValleys(n, s):
    #UとDを1と-1に変換
    ss = list(map(int, (s.replace("U","1 ").replace("D","-1 ").split())))

    #ifを一文で書く
    x = ans=0
    for i in ss:
        ans += 1 if x==0 and x+i < 0 else 0
        x += i
    return ans

[Trueの場合の式] if [条件] else [Falseの場合の式]

※elseのあとにpassが使えない。
→ 0でそれっぽく動いた。



更に簡略化すべく、内包表記でトライしてみようとしたものの、for文の中に式が複数ある場合の内包表記の書き方がわからず、、

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1