예제 #1
0
	def __init__(self):
		DLL.__init__(self)

		# Meaningful aliases for push and pop
		# for stack operations
		self.push = self.push_front
		self.pop = self.pop_front
예제 #2
0
def test_remove_first_instance_of_value_from_doubly_linked_list(itr):
    """Test that removing any node from any length list adjusts the list."""
    from dll import DLL
    l = DLL(itr)
    l.remove(1)
    assert l.head.val == 0
    assert l.head.nxt.val == 0
    assert l.head.nxt.nxt.val == 1
    assert l.length == len(itr) - 1
예제 #3
0
def test_remove_head_of_doubly_linked_list(itr):
    """Test that removing the head from any length list moves the head."""
    from dll import DLL
    l = DLL(itr)
    l.remove(itr[-1])
    assert l.head.val == itr[-2]
    assert l.length == len(itr) - 1
    assert l.tail.val == itr[0]
    assert l.head.prev is None
예제 #4
0
def test_remove_tail_from_doubly_linked_list(itr):
    """Test that removing tail from any length list adjusts the list."""
    from dll import DLL
    l = DLL(itr)

    l.remove(itr[0])

    assert l.tail.val == itr[1]
    assert l.tail.nxt is None
    assert l.length == len(itr) - 1
예제 #5
0
def test_shift_one_item_from_any_length_doubly_linked_list(itr):
    """Test that shift item removes head from DLL."""
    from dll import DLL
    l = DLL(itr)
    x = l.shift()
    assert x == itr[0]
    assert l.head.val == itr[-1]
    assert l.tail.val == itr[1]
    assert l.tail.nxt is None
    assert l.length == len(itr) - 1
예제 #6
0
def test_pop_one_item_from_any_length_doubly_linked_list(itr):
    """Test that pop item removes head from DLL."""
    from dll import DLL
    l = DLL(itr)
    x = l.pop()
    assert x == itr[-1]
    assert l.head.val == itr[-2]
    assert l.head.prev is None
    assert l.tail.val == itr[0]
    assert l.length == len(itr) - 1
예제 #7
0
    def __init__(self, id, load_function, MAX_SIZE, TIMEOUT):
        '''
		params:
		    id: unique identifier
		    load_function: if there's a cache miss, use this function to load
		    		   the value associated with a given key
		    MAX_SIZE: int, maximum number of items the ServerNode can hold
		    TIMEOUT: int/float, seconds until a node times out from unuse
		'''
        self.id = id
        self.load_function = load_function
        self.nodes = DLL(MAX_SIZE, TIMEOUT)
예제 #8
0
def test_shift_multiple_items_from_any_length_doubly_linked_list(itr):
    """Test that shift items removes head from DLL."""
    from dll import DLL
    from random import randint
    l = DLL(itr)
    num = randint(2, len(itr) - 1)
    for _ in range(num):
        x = l.shift()
    assert x == itr[num - 1]
    assert l.head.val == itr[-1]
    assert l.tail.val == itr[num]
    assert l.tail.nxt is None
    assert l.length == len(itr) - num
예제 #9
0
def parenthetics(string):
    """The parenthetics module checks for open, broken, or balanced sets."""
    matches = DLL()
    for char in string:
        if char == "(":
            matches.append(char)
        if char == ")":
            if matches.head is None or matches.pop() != "(":
                return -1
    if matches.head is None:
        return 0
    else:
        return 1
예제 #10
0
 def test_search(self):
     dll = DLL()
     # Test an empty Linked List
     assert dll.search(5) == 'Linked List is empty.'
     # Test Linked List with some nodes
     dll.addNode(1)
     dll.addNode(2)
     dll.addNode(3)
     assert dll.search('python') == False
     assert dll.search(3) == True
def test_dll(fin):
    for cmd in fin:
        cmd = cmd.strip().split()
        if cmd[0] == "new":
            dll = DLL()
            test_print(dll)
        elif cmd[0] == "insert":
            test_insert(dll, int(cmd[1]))
        elif cmd[0] == "remove":
            test_remove(dll)
        elif cmd[0] == "move_to_next":
            test_move_to_next(dll)
        elif cmd[0] == "move_to_prev":
            test_move_to_prev(dll)
        elif cmd[0] == "move_to_pos":
            test_move_to_pos(dll, int(cmd[1]))
        elif cmd[0] == "get_first_node":
            test_get_first_node(dll)
        elif cmd[0] == "get_last_node":
            test_get_last_node(dll)
        elif cmd[0] == "clear":
            test_clear(dll)
        elif cmd[0] == "sort":
            test_sort(dll)
        elif cmd[0] == "partition":
            test_partition(dll)
예제 #12
0
def test_doubly_linked_list_constructor_with_iterable(itr):
    """Test that a DLL created with an iterable contains all items."""
    from dll import DLL
    l = DLL(itr)
    assert l.head.val == itr[-1]
    assert l.tail.val == itr[0]
    assert l.length == len(itr)
예제 #13
0
class Deque(object):
    """Python Implementation of Deque Data Structure"""

    def __init__(self, iter=None):
        """Constructor Function for Deque."""
        self.container = DLL()
        if iter:
            for val in iter:
                self.container.append(val)

    def append(self, val):
        """Add val to the end of the Deque."""
        self.container.append(val)

    def appendleft(self, val):
        """Add val to the start of the Deque."""
        self.container.insert(val)

    def pop(self):
        """Remove and return the value at the end of the Deque."""
        rtn_val = self.container.shift()
        if rtn_val is not None:
            return rtn_val
        raise AttributeError

    def popleft(self):
        """Remove and the return the value at the front of the Deque."""
        rtn_val = self.container.pop()
        if rtn_val is not None:
            return rtn_val
        raise AttributeError

    def peek(self):
        """Return the next value that would be popped."""
        try:
            return self.container.tail.val
        except AttributeError:
            return None

    def peekleft(self):
        """Return the next value that would popleft."""
        try:
            return self.container.head.val
        except AttributeError:
            return None

    def size(self):
        """Return the size of the Deque."""
        return self.container.size()
예제 #14
0
 def test_size(self):
     dll = DLL()
     size = dll.size()
     # Test an empty Linked List
     assert size == 0
     # Test Linked List with some nodes
     dll.addNode(1)
     dll.addNode(2)
     dll.addNode(3)
     size = dll.size()
     assert size == 3
예제 #15
0
class Deque(object):
    """Python Implementation of Deque Data Structure"""
    def __init__(self, iter=None):
        """Constructor Function for Deque."""
        self.container = DLL()
        if iter:
            for val in iter:
                self.container.append(val)

    def append(self, val):
        """Add val to the end of the Deque."""
        self.container.append(val)

    def appendleft(self, val):
        """Add val to the start of the Deque."""
        self.container.insert(val)

    def pop(self):
        """Remove and return the value at the end of the Deque."""
        rtn_val = self.container.shift()
        if rtn_val is not None:
            return rtn_val
        raise AttributeError

    def popleft(self):
        """Remove and the return the value at the front of the Deque."""
        rtn_val = self.container.pop()
        if rtn_val is not None:
            return rtn_val
        raise AttributeError

    def peek(self):
        """Return the next value that would be popped."""
        try:
            return self.container.tail.val
        except AttributeError:
            return None

    def peekleft(self):
        """Return the next value that would popleft."""
        try:
            return self.container.head.val
        except AttributeError:
            return None

    def size(self):
        """Return the size of the Deque."""
        return self.container.size()
예제 #16
0
class ProperTarget(unittest.TestCase):
    """This handles the case where the file is a proper dll.
    """
    def setUp(self):
        self.myDll = DLL(goodDataSource)

    def testGetMemorySize(self):
        """ProperTarget::getMemorySize()"""
        assertEquals('Memory size: ', self.myDll.getMemorySize(), 8192)

    def testGetRoundedMemorySize(self):
        """ProperTarget::getRoundedMemorySize()"""
        assertEquals('Rounded size: ', self.myDll.getRoundedMemorySize(),
                     65536)

    def testGetBaseAddress(self):
        """ProperTarget::getBaseAddress()"""
        assertEquals('Base address: ', '%x' % self.myDll.getBaseAddress(),
                     '73dc0000')
예제 #17
0
class ImproperTarget(unittest.TestCase):
    """This handles the case where the filename provided to DLL is not a dll.
    All queries against a non-dll should return 0.
    """
    def setUp(self):
        self.myDll = DLL(badDataSource)

    def testGetMemorySize(self):
        """ImproperTarget::getMemorySize()"""
        assertEquals('Memory size: ', self.myDll.getMemorySize(), 0)

    def testGetRoundedMemorySize(self):
        """ImproperTarget::getRoundedMemorySize()"""
        assertEquals('Rounded memory size: ',
                     self.myDll.getRoundedMemorySize(), 0)

    def testGetBaseAddress(self):
        """ProperTarget::getBaseAddress()"""
        assertEquals('Base address: ', self.myDll.getBaseAddress(), 0)
예제 #18
0
class Queue(object):
    """Structure for values in a queue where first item in is first out."""
    def __init__(self, iterable=None):
        """Construct a new queue."""
        self._values = DLL(iterable)

    @property
    def front(self):
        """Get the node at front of the queue."""
        return self._values.tail

    @property
    def back(self):
        """Get the node at back of the queue."""
        return self._values.head

    def __len__(self):
        """Overwrite the default return for len function."""
        return len(self._values)

    def size(self):
        """Get the size of the queue."""
        return len(self)

    def enqueue(self, val):
        """Add a value to the end of the queue."""
        self._values.push(val)

    def dequeue(self):
        """Remove the value from the front of the queue and return it."""
        try:
            return self._values.shift()
        except IndexError:
            raise IndexError('Cannot dequeue from empty queue.')

    def peek(self):
        """Get the value from the front of the queue without removing it."""
        if self.front:
            return self.front.val
        return None
예제 #19
0
class Queue(object):
    """Queue class that contains a DLL."""
    def __init__(self, iter=None):
        self._container = DLL()
        if iter:
            for val in iter:
                self._container.append(val)

    def enqueue(self, val):
        """Adds a value to the end of the queue."""
        self._container.append(val)

    def dequeue(self):
        """Removes and returns value from front of queue."""
        temp_value = self._container.pop()
        if temp_value is not None:
            return temp_value
        raise ValueError

    def peek(self):
        """Returns the next value in the queue without dequeing it."""
        try:
            return self._container.head.val
        except AttributeError:
            return None

    def size(self):
        """Returns the size of the queue."""
        return self._container.size()
예제 #20
0
def test_remove(test_empty_DLL, test_DLL):
    with pytest.raises(ValueError):
        test_empty_DLL.remove(3)
    test_DLL.remove(2)
    assert test_DLL.to_string() == '(3, 1)'
    test_DLL.remove(3)
    assert test_DLL.to_string() == '(1)'
    test_DLL.remove(1)
    assert test_DLL.to_string() == '()'
    long_DLL = DLL([5, 5, 6, 7, 4, 6, 0])
    long_DLL.remove(5)
    assert long_DLL.to_string() == '(0, 6, 4, 7, 6, 5)'
    long_DLL.remove(6)
    assert long_DLL.to_string() == '(0, 4, 7, 6, 5)'
예제 #21
0
def stringShiftDriver(str, offset):
    strTarget = ""
    if len(str) == 0 or offset == 0: return str
    for i in range(len(str)):
        try:
            if (ord(str[i]) > 255): continue
            if str[i].isalpha():  # ALPHA
                if str[i].isupper():  #UP
                    strTarget += DLL.find(alphaList.head, str[i].lower(),
                                          offset, ofAlpha).upper()
                elif str[i].islower():  #LOW
                    strTarget += DLL.find(alphaList.head, str[i], offset,
                                          ofAlpha)
            elif str[i].isnumeric():  # NUM
                strTarget += DLL.find(digitList.head, str[i], offset, ofDigit)
            else:  # ALL OTHERS
                strTarget += str[i]
                continue
        except:
            print("usage: utf-8")
            continue
    return strTarget
예제 #22
0
class ProperTarget( unittest.TestCase ):
    """This handles the case where the file is a proper dll.
    """
    def setUp( self ):
        self.myDll = DLL( goodDataSource )
        
    def testGetMemorySize( self ):
        """ProperTarget::getMemorySize()"""
        assertEquals( 'Memory size: ' ,
                      self.myDll.getMemorySize(),
                      8192 )
                      
    def testGetRoundedMemorySize( self ):
        """ProperTarget::getRoundedMemorySize()"""
        assertEquals( 'Rounded size: ' ,
                      self.myDll.getRoundedMemorySize(),
                      65536 )
          
    def testGetBaseAddress( self ):
        """ProperTarget::getBaseAddress()"""
        assertEquals( 'Base address: ',
                      '%x' % self.myDll.getBaseAddress(),
                      '73dc0000' )
예제 #23
0
 def test_addNode(self):
     dll = DLL()
     dll.head
     dll.addNode(1)
     assert str(dll.head) == 'DLLNode object: data=1'
     assert dll.head.previous == None
     assert dll.head.next == None
     dll.addNode(2)
     assert str(dll.head) == 'DLLNode object: data=2'
     assert dll.head.previous == None
     assert str(dll.head.next) == 'DLLNode object: data=1'
     assert dll.size() == 2
     assert dll.head.next.next == None
예제 #24
0
class Deque(object):
    """Structure for values in a deque, a double-ended queue."""

    def __init__(self, iterable=None):
        """Construct a ne deque."""
        self._values = DLL(iterable)

    @property
    def front(self):
        """Get the node at front of the deque."""
        return self._values.tail

    @property
    def end(self):
        """Get the node at end of the deque."""
        return self._values.head

    def __len__(self):
        """Overwrite the default return for len function."""
        return len(self._values)

    def append(self, val):
        """Add a value to the end of the deque."""
        self._values.push(val)

    def appendleft(self, val):
        """Add a value to the front of the deque."""
        self._values.append(val)

    def pop(self):
        """Remove the value from the end of the deque and return it."""
        try:
            return self._values.pop()
        except IndexError:
            raise IndexError('Cannot pop from empty deque.')

    def popleft(self):
        """Remove the value from the front of the deque and return it."""
        try:
            return self._values.shift()
        except IndexError:
            raise IndexError('Cannot popleft from empty deque.')

    def peek(self):
        """Get the value from the end of the deque without removing it."""
        if self.end:
            return self.end.val

    def peekleft(self):
        """Get the value from the front of the deque without removing it."""
        if self.front:
            return self.front.val

    def size(self):
        """Get the size of the deque."""
        return len(self)
예제 #25
0
class ImproperTarget(unittest.TestCase): 
    """This handles the case where the filename provided to DLL is not a dll.
    All queries against a non-dll should return 0.
    """
    def setUp(self):    
        self.myDll = DLL( badDataSource )
               
    def testGetMemorySize( self ):
        """ImproperTarget::getMemorySize()"""
        assertEquals( 'Memory size: ', 
                      self.myDll.getMemorySize(),
                      0 )
                              
    def testGetRoundedMemorySize( self ):
        """ImproperTarget::getRoundedMemorySize()"""
        assertEquals( 'Rounded memory size: ',
                      self.myDll.getRoundedMemorySize(),
                      0 )

    def testGetBaseAddress( self ):
        """ProperTarget::getBaseAddress()"""
        assertEquals( 'Base address: ',
                      self.myDll.getBaseAddress(),
                      0 )
예제 #26
0
class ServerNode():
    def __init__(self, id, load_function, MAX_SIZE, TIMEOUT):
        '''
		params:
		    id: unique identifier
		    load_function: if there's a cache miss, use this function to load
		    		   the value associated with a given key
		    MAX_SIZE: int, maximum number of items the ServerNode can hold
		    TIMEOUT: int/float, seconds until a node times out from unuse
		'''
        self.id = id
        self.load_function = load_function
        self.nodes = DLL(MAX_SIZE, TIMEOUT)

    def get_state(self):
        '''
		returns: list of current nodes
		'''
        nodes = []
        for node in self.nodes:
            nodes.append(node)
        return nodes

    def get(self, key):
        '''
		returns: value associated with given key

		If a key is not found, load the data into the cache and return.
		'''
        result = self.nodes.get(key)
        if result is None:
            value = self.load_function(key)
            self.nodes.add(key, value)
            return value
        else:
            return result
예제 #27
0
def test_remove(test_empty_DLL, test_DLL):
    with pytest.raises(ValueError):
        test_empty_DLL.remove(3)
    test_DLL.remove(2)
    assert test_DLL.to_string() == '(3, 1)'
    test_DLL.remove(3)
    assert test_DLL.to_string() == '(1)'
    test_DLL.remove(1)
    assert test_DLL.to_string() == '()'
    long_DLL = DLL([5, 5, 6, 7, 4, 6, 0])
    long_DLL.remove(5)
    assert long_DLL.to_string() == '(0, 6, 4, 7, 6, 5)'
    long_DLL.remove(6)
    assert long_DLL.to_string() == '(0, 4, 7, 6, 5)'
예제 #28
0
def test_remove_random_inner_node_from_doubly_linked_list(itr):
    """Test that removing any node from any length list adjusts the list."""
    from dll import DLL
    from random import choice
    l = DLL(itr)

    remove_item = choice(itr[1:-1])
    l.remove(remove_item)
    with pytest.raises(ValueError):
        l.remove(remove_item)
    assert l.length == len(itr) - 1
예제 #29
0
def test_dll(fin):
    for cmd in fin:
        cmd = cmd.strip().split()
        if cmd[0] == "new":
            dll = DLL()
            test_print(dll)
        elif cmd[0] == "insert":
            test_insert(dll, int(cmd[1]))
        elif cmd[0] == "remove":
            test_remove(dll)
        elif cmd[0] == "move_to_next":
            test_move_to_next(dll)
        elif cmd[0] == "move_to_prev":
            test_move_to_prev(dll)
        elif cmd[0] == "move_to_pos":
            test_move_to_pos(dll, int(cmd[1]))
        elif cmd[0] == "remove_all":
            test_remove_all(dll, int(cmd[1]))
        elif cmd[0] == "sort":
            test_sort(dll)
        elif cmd[0] == "reverse":
            test_reverse(dll)
예제 #30
0
def findPairsWithSumX(head, tail, x):
    result = []
    if head is None or tail is None:
        return result
    while head != tail and tail.next != head:
        if head.data + tail.data == x:
            result.append((head.data, tail.data)
            head, tail = head.next, tail.prev
        elif head.data + tail.data < x:
            head = head.next
        else:
            tail = tail.prev
    return result

s = [1, 2, 4, 5, 6, 8, 9]
dll = DLL()
for i in s:
    dll.append(i)
dll.printList()
print findPairsWithSumX(dll.head, dll.tail, 7)
예제 #31
0
    while current and current.next:
        if current.next.data > newNode.data:
            break
        current = current.next
    if current is None:
        dll.head = newNode
    elif current.next is None:
        current.next = newNode
        newNode.prev = current
        dll.tail = newNode
    else:
        newNode.next = current.next
        newNode.prev = current
        newNode.next.prev = newNode
        current.next = newNode


dll = DLL()
for i in range(7):
    dll.append(2 * i + 1)
dll.printList()
sortedInsert(dll, 0)
dll.printList()
sortedInsert(dll, 4)
dll.printList()
sortedInsert(dll, 16)
dll.printList()
sortedInsert(dll, 0)
dll.printList()
sortedInsert(dll, 7)
dll.printList()
예제 #32
0
        dll.head = None
        dll.tail = None
        return
    if k == 1:
        node = dll.head
        dll.head = node.next
        node.next = None
        dll.head.prev = None
    else:
        current = dll.head
        while current and k > 1:
            current = current.next
            k -= 1
        if current is None:
            return
        elif current.next is None:
            dll.tail = current
            current.prev.next = None
            current.prev = None
        else:
            current.prev.next = current.next
            current.next.prev = current.prev


dll = DLL()
for i in range(8):
    dll.append(i)
dll.printList()
deleteAt(dll, 8)
print dll.tail
dll.printList()
예제 #33
0
 def setUp(self):    
     self.myDll = DLL( badDataSource )
예제 #34
0
 def setUp(self):
     self.myDll = DLL(badDataSource)
예제 #35
0
 def __init__(self, iter=None):
     """Constructor Function for Deque."""
     self.container = DLL()
     if iter:
         for val in iter:
             self.container.append(val)
예제 #36
0
 def __init__(self, iter=None):
     self._container = DLL()
     if iter:
         for val in iter:
             self._container.append(val)
예제 #37
0
def test_shift_single():
    test_DLL = DLL([1])
    assert test_DLL.shift() == 1
    assert test_DLL.shift() is None
예제 #38
0
 def setUp(self):
     self.dll = DLL()
예제 #39
0
def test_pop_single():
    test_DLL = DLL([1])
    assert test_DLL.pop() == 1
    assert test_DLL.pop() is None