0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

第11回オフラインリアルタイムどう書くの参考問題。python による実装例。

0
Last updated at Posted at 2013-05-18

オフラインリアルタイムどう書く
http://atnd.org/events/38770
の参考問題
http://nabetani.sakura.ne.jp/hena/ord11arithseq/
の実装例を python で書いた。
python2.7 と python3.3 の両方で動作確認済み。

他の言語などの解答例は
http://qiita.com/items/c206fbc645c255cb7de6
から辿れます。

で。
こんな感じ。

solver.py
# coding:utf-8
import re

def solve( src ):
    def impl( s, seq ):
        if 2<len(s) and ( s[1]-s[0] != s[-1]-s[-2] ) :
            return 0
        if len(seq)==0:
            return len(s)
        return max(  impl( s, seq[1:] ),  impl( s+seq[0:1], seq[1:] ) )
    nums="0123456789abcdefghijklmnopqrstuvwxyz"
    return "%d" % impl( [], [ nums.index(c) for c  in list( src ) ] )

def test( samples ) :
    for line in samples.splitlines():
        a=re.split( "\s+", line ) # num, input, expected
        if len(a) <3:
            continue
        actual = solve( a[1] )
        ok=actual==a[2]
        print( [ "ok" if ok else "***NG***", a[1:3], actual ] )

test( """
0   12345abcz   5   12345
1   012abku 4   0aku
2   01245689cdeghik 6   048cgk
49  012346abceghjknortv 5   01234 他 2 件""" )

例によってテストデータの大半を省略。

F# で色々試してくださっている matarillo さんのコメント
http://qiita.com/items/6ab69f5f514cb2d0e7a8#comment-73ec472aa6be28061f68
から着想を得て書いた。

末尾再帰にならない再帰なのでスタックが溢れる感じだけど、たかだか36なので大丈夫。だった。

python らしさを出したいと思っているんだけれども、内包表記を一個使えただけで、いまひとつ。今回も for 文の else を使うチャンスがなかった。残念。

python 初心者なので色々発見があり。

  • #coding:utf-8 には効果がある。(python2.7の場合)
  • 定義の前にメソッド(関数?)呼んだらエラー
  • 36進数をなんとかする関数はないらしい。
  • やっぱり後置 if はないらしい。
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?