示例#1
0
class Queue(object):
    '''
    A linked list implementation of a queue.

    This contains a LinkedList internally.  It does not extend LinkedList.
    In other words, this class uses "Composition" rather than "Inheritance".
    '''
    def __init__(self):
        '''Constructor'''
        self.queue = LinkedList()

    def debug_print(self):
        '''Prints a representation of the entire queue.'''
        self.queue.debug_print()

    def enqueue(self, item):
        '''Adds an item to the end of the queue'''
        self.queue.add(item)

    def dequeue(self):
        '''
        Dequeues the first item from the list.  This involves the following:
            1. Get the first node in the list.
            2. Delete the node from the list.
            3. Return the value of the node.
        '''
        beg = self.queue._get_node(0)
        self.queue.delete(0)
        return beg.value

    def size(self):
        '''Returns the number of items in the queue'''
        return self.queue.size
示例#2
0
class Processor(object):
    def run(self, f):
        '''Processes the given file stream.'''
        for line_i, line in enumerate(f):
            # get the line parts
            line = line.rstrip()
            print('{}:{}'.format(line_i, line))
            parts = line.split(',')
            # call this command's function
            try:
                func = getattr(self, 'cmd_{}'.format(parts[0].lower()))
                func(*parts[1:])
            except Exception as e:
                print('Error: {}'.format(e))

    def cmd_debug(self, *args):
        self.ll.debug_print()

    def cmd_create(self, *args):
        self.ll = LinkedList()

    def cmd_add(self, *args):
        self.ll.add(args[0])

    def cmd_insert(self, *args):
        self.ll.insert(int(args[0]), args[1])

    def cmd_set(self, *args):
        self.ll.set(int(args[0]), args[1])

    def cmd_get_node(self, *args):
        print(self.ll._get_node(int(args[0])))

    def cmd_delete(self, *args):
        self.ll.delete(int(args[0]))

    def cmd_swap(self, *args):
        self.ll.swap(int(args[0]), int(args[1]))

    def cmd_get(self, *args):
        self.ll.get(int(args[0]))