Python

conditional expression の代替

ref: Python 2.5 の新機能 なんか久々に紫藤さんのサイトを覗いたら、ちょっと面白い。 今まで、Python には三項演算子が無かったので、単に条件によって代入される値を変えるために if predicate: value = then_value else: value = else_value と書くのは…

list の hash

ref:2007-12-02 - プログラミング日記 なるほど。同値関係を定義できるのに、同一オブジェクトじゃないと同一ハッシュにならないという状況はいろいろまずそうだから、それを回避するわけだ。 しかし、新スタイルクラスではobjectに__hash__が定義されている…

help とか

今日気づいたこと。 Python 2.5.1 (r251:54863, Oct 5 2007, 13:50:07) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> type(help) <class 'site._Helper'> >>> type(copyrig</class>…

KeyError を warning にする

ref:2007-11-29 - プログラミング日記 ref:jijixi's diary - sm1506603 (忙しい人のための 「たたかえ!キャシャーン」(Full Ver.)) , そろそろ 6.3-Release も近いようだが , エラーでなく.. Python の場合、組み込みクラスのオブジェクトに setattr でき…

exit

ref:L'eclat des jours(2007-11-26) ref:DARK SERVER - (2007.11.26) 面白いなぁ。ちなみに実装は lib/site.py にある。 Python 2.4 の場合 def setquit(): """Define new built-ins 'quit' and 'exit'. These are simply strings that display a hint on ho…

quick sort

ref:Quick Sort - mono-hateの日記 なんか以前も Haskell での quick sort について書いたような記憶があるけども、Python でもできたりするな。 def quicksort(xs): if len(xs) == 0: return [] x = xs[0] return quicksort([y for y in xs[1:] if y < x]) …

ニコニコダウンローダの Safari 対応

ニコニコ動画はなんか自作の Python スクリプトでダウンロードしていたりする。自動で Firefox の profile から cookie を読むようにしてあるので、ダウンロードするとブラウザの方で再ログインというはめにならずに、まあ、そこそこ快適。 で、なんか Safar…

Python Pipeline

ref:python-pipelines - Google Code ref:Python Pipelines - Wikipedia, the free encyclopedia ふとしたことで、Hartmann Pipelineというものを知った。Python Pipeline なんていう Python 実装があるとのことでのぞいてみたら、"This project currently h…

decorator

ref:西尾泰和のブログ @ Cybozu Labs: Pythonで関数名を安全に変更する via:jijixi's diary - Pythonで関数名を安全に変更する (西尾泰和のブログ @ Cybozu Labs) 面白いなぁ。 で、ついでにいうと deprecated は decorator としても使えるようになっていて…

with

ref:http://twitter.com/hayamizu/statuses/337466862 with_statement ってあんまり知られてないなぁ。Python 2.5 からだけど。 from __future__ import with_statement import sys with file(sys.argv[0], 'r') as fp: for line in fp: sys.stdout.write(li…

イテレータ

ref:Life is beautiful: 教えながら学ぶRuby:イテレータに片思い これくらいで、イテレータが云々とか言っているのはなんだかなぁ、とか思ったりしないでもない。なので、あえて Ruby 以外で。 Haskell で。 hello :: String -> [String] -> IO () hello to…

property

ref:jijixi's diary - プロパティ , ふと思ったんだけど、Ruby みたいに無引数の関数呼び出しでカッコを省略できる言語って少数派じゃないだろうか? あぁ、property なんてのがあったのか。

アクセッサ

ref:L'eclat des jours(2007-09-01) もうずいぶん昔読んだ本に、クラス内部でもアクセッサを使えということは書かれていた気がする。なんだっけ、GoF 本か、(More) Effective C++ か、Effective Java かたぶんその辺。 そういや、setter を使うときは self …

locale.getpreferredencoding()

Mac OS 10.4 にて。 OS 標準の Python 2.3.5 の場合 % /usr/bin/python -c 'import locale; print locale.getpreferredencoding()' UTF-8MacPorts の Python 2.5.1 の場合 % /opt/local/bin/python2.5 -c 'import locale; print locale.getpreferredencoding…

ランダムな文字列生成

ref:http://subtech.g.hatena.ne.jp/secondlife/20070821/1187667574 ref:http://subtech.g.hatena.ne.jp/secondlife/20070820/1187578797 ref:http://d.hatena.ne.jp/knagano/20070820/1187621230 ref:http://d.hatena.ne.jp/knagano/20070821/1187656060 …

自分で拡張すればいいのに

ref: :gnuvince.net ? Blog Archive ? My 5 things I hate about Python ref:西尾泰和のブログ: LL魂準備日記 ref:Matzにっき(2007-07-19) 分からないでもないけど 1、2 なんか、そのまま自分で拡張すればいいじゃねえかと。 dict.get 見たいなのが list に…

ニコニコ動画ダウンローダ

ref:404 Blog Not Found:perl - 勝手に添削 - ニコニコ動画ダウンローダー 以前、Irvine(via OLE) でダウンロードする Perl スクリプトを書いたけど、なんか FLV のダウンロードにも Cookie が必要になっているっぽいので、Firefox の Cookie を使ったり、フ…

ElementTree で巨大な XML を処理する

ElementTree のページに書いてあることだけど、メモとして。 xml.etree.ElementTree.iterparse を使うと、DOM のようにメモリを食わず、SAX よりプログラムしやすいかと思いきや、試しに Wikipedia のダンプデータを食わしてみたら、がんがんメモりを食う。…

n倍完全数

ref:ダブル完全数 自分自身も含めた約数の和が自分自身の n 倍になる数を n 倍完全数というらしい。ということで、n 倍完全数を列挙するプログラムとか。 愚直な解き方。 def divisors(n): return (i for i in xrange(1, n + 1) if n % i == 0) def perfect_…

h-index #3

Haskell は分からない、という、はてブ指数を言い出した人がブックマークでコメントしていたので、同等の処理を Ruby と Python で。 余計なことにユニットテスト付き。 module Enumerable def take_while ret = [] each do |val| break unless yield val re…

一方向リスト

ref:Fomalhaut of Piscis Australis : [python] どう書く?-- 一方向リスト編 ref:Fomalhaut of Piscis Australis : [python] どう書く?-- 一方向リスト編その2 ref:DARK SERVER - $ [python] どう書く?-- 一方向リスト編 def get_endpoint( linked_list )…

take

ref:Floating Log 18.7.2007 こういう機能はイディオムでおいておくのではなく、ちゃんと部品化して可読性を高める、とう癖が大事なのではないかと思う。 def take(n, iterable): i = 0 for item in iterable: if i >= n: break i += 1 yield item for eleme…

小町算 #2

ちょ、さいとうさんのチェック早い。ということで、とりあえず電卓版を晒しておく。あいかわらず整数演算なのでダメダメなんですが。 import sys import operator def join(a, b): return int(str(a) + str(b)) OPERATORS = { '+': operator.add, '-': opera…

小町算

ref:Karetta|キミならどう書く 2.0 - 2007 - その 2 とりあえず、通常の演算優先順位で。全部で 303 個の式ができるという結果が出ました。まぁ、eval のおかげだし、Brute Force なんだけど。 しかし、最近の計算機だとこれを10秒ぐらいで計算してしまうん…

小町算 #3

下のダメダメなのは捨てて、有理数を導入したまじめなのを。 import sys import re from rational import Rational OPERATORS = '+ - * / '.split(' ') NUM_PAT = re.compile(r'\d+') def exp_eval(exp): r = Rational fixed_exp = NUM_PAT.sub(r'r(\g<0>)',…

uniq

ref:アレイのuniq Doukaku? ちょいとトリッキーなのと素朴で遅い奴。 def uniq(iterable): """ >>> uniq([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9]) [3, 1, 4, 5, 9, 2, 6, 8, 7] """ s = set() return [s.add(i) or i for i in iterable if i not in …

油売り算 #2

幅優先探索自体を部品化してしまうのが、関数型プログラミングなんだろうなと思ったのでやってみた。まぁ、だからなんだという話だ。 import sys from collections import deque class cons(object): __slots__ = ('car', 'cdr') def __init__(self, car, cd…

油売り算

ref:Karetta|キミならどう書く 2.0 - 2007 - その 1 Python で書いてみた。 import sys from collections import deque def solve_abura(a, b, c): limits = (a, b, c) choices = ((0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)) def is_complete(state):…

シフト演算

A right shift by n bits is defined as division by pow(2,n). A left shift by n bits is defined as multiplication with pow(2,n); for plain integers there is no overflow check so in that case the operation drops bits and flips the sign if the…

Singleton

ref:http://www.nishiohirokazu.org/pwe2007/2007/06/post_2.html たぶん、__metaclass__ とか __new__ あたりを使うのがいいんだろうけど、よくわからない。ある意味では class Singleton(object): pass Singleton = Singleton() とかそういうのでいいのか…