読者です 読者をやめる 読者になる 読者になる

珠玉のプログラミングのお題を python で書いてみた : 4

python algorithm
#!/bin/env python

"""
2.4 the sort to summarize(P18-21)
Problem C anagram : posts stop tops
"""

# global
DIC = ['pans','pots','opt','snap','stop','tops']

def main():
    print "Dictionary : ", DIC
    
    d = {}
    for i in DIC:
        sgrp = sign(i)
        if d.has_key(sgrp):
            d[sgrp] = squash(d[sgrp], i)
        else:
            d[sgrp] = [i]
    
    print "anagram : ", d

def sign(s):
    t = [x for x in s]
    t.sort()
    r = ''
    for i in t:
        r += i
    return r

def squash(ds, s):
    t = []
    t = ds
    t.append(s)
    return t

if __name__ == '__main__':
    main()

実行結果。

Dictionary :  ['pans', 'pots', 'opt', 'snap', 'stop', 'tops']
anagram :  {'opt': ['opt'], 'anps': ['pans', 'snap'], 'opst': ['pots', 'stop', 'tops']}