練習問題(アルゴリズム編)

'''
python main.py 1 2 + 4 5 + *
> 27
python main.py 1 2 + 3 * 4 5 / -
> 8.2
python main.py 5 13 + 6 / 2 % 4 5 * -
> -19
'''
import sys
st = []
args = sys.argv
if len(args) < 2:
    print("no element")
    exit()
for e in args[1:]:
  try:
    if e=='+':
      b, a = st.pop(), st.pop()
      st.append(a+b)
    elif e=='-':
      b, a = st.pop(), st.pop()
      st.append(a-b)
    elif e=='*':
      b, a = st.pop(), st.pop()
      st.append(a*b)
    elif e=='/':
      b, a = st.pop(), st.pop()
      st.append(a/b)
    elif e=='%':
      b, a = st.pop(), st.pop()
      st.append(a%b)
    else:
      st.append(int(e))
  except IndexError:
    print('index error!')
    exit(1)
print(float(st.pop()))

トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS