プログラミング過程

朝起きて
http://ja.doukaku.org/comment/4258/
をみて、なるほど、そういう発想があったか!と思ってコーディングした
過程を録画すればよかった(参考:http://d.hatena.ne.jp/higepon/20071108/1194495170)と思ったけど
とりあえずPythonの対話的シェルで書いたのでそれを丸ごと貼ってみる。
途中#で始まるのは後から書いたコメント

>>> def divid(n, s):
	from itertools import cycle
	print cycle(3)

	
>>> divid(3, "")
Traceback (most recent call last):
  File "<pyshell#110>", line 1, in <module>
    divid(3, "")
  File "<pyshell#109>", line 3, in divid
    print cycle(3)
TypeError: 'int' object is not iterable
# cycleは数字じゃなくてリスト状(iterable)のものを取る
>>> from itertools import cycle
>>> cycle(range(3))
<itertools.cycle object at 0x0270AAA8>
# (0, 1, 2, 0, 1, 2...)と繰り返す無限リスト状のジェネレータ
>>> zip(_, "hoge")
[(0, 'h'), (1, 'o'), (2, 'g'), (0, 'e')]
# zipは短い方にあわせる
>>> def divid(n, s):
	from itertools import cycle
	print zip(cycle(range(n)), s)


# とりあえず部品ができたので関数に入れておく	
>>> from collections import defaultdict
>>> defaultdict(list)
defaultdict(<type 'list'>, {})
# defaultdictを使いかけたけど、必要ないと気づく
>>> xs = [(0, 'h'), (1, 'o'), (2, 'g'), (0, 'e')]
# zipの結果にxsって名前をつけといて
>>> [x for x in xs is x[0] == 0]
Traceback (most recent call last):
  File "<pyshell#119>", line 1, in <module>
    [x for x in xs is x[0] == 0]
NameError: name 'x' is not defined
# if って書くべきところをisって書いちゃった
>>> [x for x in xs if x[0] == 0]
[(0, 'h'), (0, 'e')]
# 0のモノだけを取り出すリスト内包
>>> [c for i, c in xs if i == 0]
['h', 'e']
# [0]はださいのでタプルアンパッキングを使う
>>> "".join(c for i, c in xs if i == 0)
'he'
# joinでつなぐ。二つ目の部品できあがり。
>>> def divid(n, s):
	from itertools import cycle
	print ["".join(c for i, c in xs if i == 0)zip(cycle(range(n)), s)
	       
SyntaxError: invalid syntax
# 貼り付けミス
>>> def divid(n, s):
	from itertools import cycle
	xs = zip(cycle(range(n)), s)
	print ["".join(c for i, c in xs if i == j)
	       for j in range(n)]

	
>>> divid(3, "1234567890")
['1470', '258', '369']
>>> def divid(n, s):
	from itertools import cycle
	xs = zip(cycle(range(n)), s)
	return ["".join(c for i, c in xs if i == j)
	       for j in range(n)]

>>> divid(3, "1234567890")
['1470', '258', '369']
>>>