U E D R , A S I H C RSS

Classify By Anagram/박응주

상대 속도 약 1.35. test2와 test3의 간격이 너무 크다. 작성하는데 얼마나 걸리는 지 또 안재어봤다. :(
_signature를 그냥 쉘에서 해봤었는데 _signature를 테스트로 넣었어야 했다.

~cpp 
import unittest

class Anagram:
    def __init__(self):
        self._anagrams = {}
    def add(self, word):
        s = self._signature(word)
        if self._anagrams.has_key(s):
            self._anagrams[s].append(word)
        else:
            self._anagrams[s] = [word]
    def anagrams(self):
        return self._anagrams.values()
    def _signature(self, word):
        s = list(word)
        s.sort()
        return "".join(s)

class AnagramTestCase(unittest.TestCase):
    def test1(self):
        anagram = Anagram()
        anagram.add('abc')
        self.assert_(['abc'] in anagram.anagrams())
    def test2(self):
        anagram = Anagram()
        anagram.add('abc')
        anagram.add('bac')
        self.assert_(['abc', 'bac'] in anagram.anagrams())
    def test3(self):
        anagram = Anagram()
        anagram.add('efg')
        anagram.add('abc')
        anagram.add('bac')
        self.assert_(['abc', 'bac'] in anagram.anagrams())
        self.assert_(['efg'] in anagram.anagrams())
        
if __name__ == "__main__":
    #unittest.main(argv=('', '-v'))
    import sys
    import time
    t1 = time.clock()
    anagram = Anagram()
    for word in sys.stdin:
        anagram.add(word.strip())
    for words in anagram.anagrams():
        print ' '.join(words)
    t2 = time.clock()
    print t2 - t1

P3 700MGhz 384MB Win2000 Python 2.2.1에서 17만 단어로 실행하면 8.8초.
Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2009-05-27 07:09:19
Processing time 0.0097 sec