LoginSignup
0
0

More than 1 year has passed since last update.

paiza.ioでpython その4

Posted at

概要

paiza.ioでpythonやってみた。
練習問題やってみた。

練習問題

forthインタープリターを実装せよ。
forthで数9を4個つかって1から15までの数を表す式を実行せよ。

サンプルコード

# coding: utf-8

stack = []
def add():
    global stack
    top1 = stack.pop()
    top2 = stack.pop()
    v = top2 + top1
    stack.append(v)
def sub():
    global stack
    top1 = stack.pop()
    top2 = stack.pop()
    v = top2 - top1
    stack.append(v)
def mul():
    global stack
    top1 = stack.pop()
    top2 = stack.pop()
    v = top2 * top1
    stack.append(v)
def div():
    global stack
    top1 = stack.pop()
    top2 = stack.pop()
    v = top2 / top1
    stack.append(v)
def dup():
    global stack
    top1 = stack.pop()
    stack.append(top1)
    stack.append(top1)
def drop():
    global stack
    top1 = stack.pop()
def get():
    global stack
    top1 = stack.pop()
    print(top1)
def push(v):
    global stack
    stack.append(int(v))
def run(str):
    s = str.split(' ')
    for i in s: 
        if i == "+":
            add()
        elif i == "-":
            sub()
        elif i == "*":
            mul()
        elif i == "/":
            div()
        elif i == "dup":
            dup()
        elif i == "drop":
            drop()
        elif i == ".":
            get()
        else:
            push(i)
	    
	    

run("9 9 - 9 9 / .")# 1
run("9 9 / 9 9 / + .")# 2
run("9 9 + 9 + 9 / .")# 3
run("9 9 9 + 9 / dup + .")# 4
run("9 9 9 + 9 / dup + - .")# 5
run("9 dup 9 + 9 + 9 / - .")# 6
run("9 9 9 + 9 / - .")# 7  
run("9 9 9 drop 9 / - .")# 8  
run("9 9 - 9 * 9 + .")# 9  
run("9 9 / 9 dup 9 / + .")# 10  
run("9 9 9 + 9 / + .")# 11  
run("9 dup 9 9 + + 9 / + .")# 12  
run("9 9 9 + 9 / dup + + .")# 13  
run("9 dup 9 9 + 9 / dup + - + .")# 14  
run("9 dup dup 9 + 9 + 9 / - + .")# 15  




実行結果

1.0
2.0
3.0
4.0
5.0
6.0
7.0
8.0
9
10.0
11.0
12.0
13.0
14.0
15.0

成果物

以上。

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