0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

数式の計算( 1 桁) Python3編

Posted at

文字列で書かれている数式を確定させて出力させる問題
前回学んだことを活かして下記のように
はじめ、+かーかそうでなければ数値として、答え変数に代入し、
その後、+かーかでフラグを立てて
その次の数値をフラグ通りに計算するという方法。

s = input()
ans = 0
flag = 0
for i in s:
    if i == '+':
        flag = 1
    elif i == '-':
        flag = 2        
    else:
        if flag == 0:
            ans = int(i)
        elif flag == 1:
            ans += int(i)
        elif flag == 2:
            ans -= int(i)
print(ans)

答えを見てみるともっと簡単になってた。
奇数が数式で、偶数の場合数値が出るので
そこで場合分けする方法だった。

s = input()

ans = 0
add = True
for i in range(len(s)):
    if i % 2 == 0:
        if add:
            ans += int(s[i])
        else:
            ans -= int(s[i])
    else:
        if s[i] == "+":
            add = True
        else:
            add = False

print(ans)

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?