본문 바로가기

프로그래밍/Python

twisted counter 연습문제

반응형

http://krondo.com/?p=1333 여기에서 제시한 연습문제를 풀어봤다. 왠지 깔끔하지 않아보이는 코드이지만 남겨본다.


class Countdown(object):


    MARKER_REF = '~!@#$%^&*()`<>,/+_|:;'

    # a counter is 

    #   c[0] : initial value

    #   c[1] : count function

    counters = [ ]


    def add_counter(self, c, d):

    M = self.MARKER_REF

    marker_string = M[c%len(M)]*3 + M[d%len(M)]*3

    idx = len(self.counters)

        def count():

            if sum(map(lambda x : x[0], self.counters)) == 0:

                reactor.stop()

            else:

            if self.counters[idx][0] != 0:

               print marker_string, self.counters[idx][0], '...'

               self.counters[idx][0] -= 1

               reactor.callLater(d, count)

           else:

            print marker_string * 10

    self.counters.append([c, count])


    def count_start(self):

    for counter in self.counters:

    counter[1]()



from twisted.internet import reactor


c = Countdown()

c.add_counter(98, 1)

c.add_counter(24, 5)

c.add_counter(8, 11)

c.add_counter(50, 2)


reactor.callWhenRunning(c.count_start)


print 'Start!'

reactor.run()

print 'Stop!'




728x90