2009年8月12日水曜日

Pythonに触れる

最近自分で触れて遊ぶのはCommonLispが9割,Cが1割な気がするが,他の言語に触らないのもよろしくないと思うのでPythonで遊んでみた.

Hello,World -> FizzBuzz -> Brainfuck という順で,勉強がてら適当に書いてみた.

以下ソースコード

# Hello,World
print "Hello,World"

# FizzBuzz
# forはリストの要素に対して用いる.
for i in range(1, 100):
if (i % 15) == 0:
print "FizzBuzz"
elif (i % 5) == 0:
print "Buzz"
elif (i % 3) == 0:
print "Fizz"
else:
print i

# Brainfuck
# printの末尾に,を付けると改行の代わりに空白を出力するらしいが,
# これを回避するためにsys.stdout.writeを用れば良いようだ
import sys
# Wikipediaで拾ってきたBrainfuckのHello,World
program_array = "+++++++++[>++++++++>+++++++++++>+++++<<<-]>.>++.+++++++..+++.>-.------------.<++++++++.--------.+++.------.--------.>+."
def run_bf (pg):
l = len(pg)
ptr = 0
pc = 0
mem = {}
labels = []
while pc < l:
c = pg[pc]
if c == '>':
ptr = ptr + 1
elif c == '<':
ptr = ptr - 1
elif c == '+':
if not mem.has_key(ptr):
mem[ptr] = 0
mem[ptr] = mem[ptr] + 1
elif c == '-':
if not mem.has_key(ptr):
mem[ptr] = 0
mem[ptr] = mem[ptr] - 1
elif c == '.':
if not mem.has_key(ptr):
mem[ptr] = 0
sys.stdout.write('%c' % mem[ptr])
elif c == ',':
mem[ptr] = input() # fixme
elif c == '[':
if mem[ptr] == 0:
tmp_l = []
pc = pc + 1
while (pg[pc] != ']') or tmp_l:
if pg[pc] == ']':
tmp_l.pop()
elif pg[pc] == '[':
tmp_l.append(pc)
pc = pc + 1
else:
labels.append(pc)
elif c == ']':
if mem[ptr] != 0:
pc = labels[-1]
else:
print "no reach"
pc = pc + 1
Hello,Worldでは入力を使わないので,Brainfuckの入力のところは適当.文字型はなさそうで,文字列->文字コード(のリスト?)な関数があるのだろうけど,ぱっと見つからないので無視してしまいましたとさ.

Pythonらしい書き方,というものはまだ全く分からないが,制御構造をなんとなく使える程度にはなったのかなぁ.

0 件のコメント:

コメントを投稿