def test_pop_removes_last_item(self):
        l1 = LinkedList([1, 2, 3])

        elem = l1.pop(2)
        self.assertEqual(elem, 3)
        self.assertEqual(l1.count(), 2)
        self.assertEqual(l1, LinkedList([1, 2]))
def test_remove_one_node():
    """Test to remove one node."""
    from linked_list import LinkedList
    my_list = LinkedList()
    my_list.insert('a')
    my_list.remove('a')
    assert my_list.head is None
 def test_number_averaging_normal(self):
     self.assertEquals(number_average([0.0, 1.0, 2.0, 3, 4, 5], simple_func), 2.5)
     self.assertEquals(number_average([0.0, 1.0, 2.0, 3, 4, 5], simple_func), 2.5)
     self.assertEquals(number_average([0, 1, 2, 3, 4, 11], simple_func), 3.5)
     list = LinkedList()
     list.add_last(0)
     self.assertEquals(number_average(list, simple_func), 0)
def test_linkedlist_remove_head():
    """Test LinkedList.remove for proper last Node removal."""
    from linked_list import LinkedList, Node
    input_ = "a b c".split()
    linked_list_instance = LinkedList(input_)
    linked_list_instance.remove(Node('a'))
    assert linked_list_instance.tail.pointer.pointer is None
 def test_add_adds_to_end(self):
     llist = LinkedList()
     node = Node(1)
     node2 = Node(2)
     llist.add(node)
     llist.add(node2)
     self.assertEqual(llist.head, node)
def test_linkedlist_insert_empty():
    """Test LinkedList.insert from an empty list."""
    from linked_list import LinkedList
    input_ = []
    linked_list_instance = LinkedList(input_)
    linked_list_instance.insert('a')
    assert linked_list_instance.size() == 1
def test_linkedlist_insert_string():
    """Test LinkeList.insert for tail addition to Node list."""
    from linked_list import LinkedList
    input_ = [1, 2, 3]
    linked_list_instance = LinkedList(input_)
    linked_list_instance.insert("Nadia")
    assert linked_list_instance.tail.pointer.pointer.pointer.value == "Nadia"
def test_linkedlist_pop_empty():
    """Test LinkedList.pop from an empty list."""
    from linked_list import LinkedList
    input_ = []
    linked_list_instance = LinkedList(input_)
    with pytest.raises(IndexError):
        linked_list_instance.pop()
Exemplo n.º 9
0
def test_insert_two():
    l_list = LinkedList()
    l_list.insert("David")
    l_list.insert("Thomas")
    assert l_list.head.get_data() == "Thomas"
    head_next = l_list.head.get_next()
    assert head_next.get_data() == "David"
Exemplo n.º 10
0
 def test_iterator(self):
     lst = LinkedList()
     lst.push(10)
     lst.push(20)
     iterator = iter(lst)
     self.assertEqual(next(iterator), 10)
     self.assertEqual(next(iterator), 20)
Exemplo n.º 11
0
def test_insert_two():
    l_list = LinkedList()
    l_list.insert("Shreyas")
    l_list.insert("Gune")
    assert l_list.head.get_data() == "Gune"
    head_next = l_list.head.get_next()
    assert head_next.get_data() == "Shreyas"
Exemplo n.º 12
0
def test_finding_elements_on_empty_list() -> None:
    linked_list = LinkedList()

    linked_list.find(target_key="id", target_value="an_irrelevant_value")

    assert linked_list.head is None
    assert linked_list.tail is None
Exemplo n.º 13
0
class Stack(object):

    def __init__(self, root=None):

        self.linked_list = LinkedList()

        if root is not None:
            self.push(root)

    def push(self, item):

        self.linked_list.insert_front(item)

    def pop(self):

        self.linked_list.delete_node(self.linked_list.head)

    def top(self):

        return self.linked_list.head.data

    def is_empty(self):

        if self.linked_list.head is None:
            return True

        return False

    def size(self):

        return self.linked_list.size()
Exemplo n.º 14
0
def test_reversal_two():
    """Test no errors arise when reversing a list of 2 items."""
    from linked_list import LinkedList
    new_list = LinkedList([5, 20])
    assert new_list.display() == '(20, 5)'
    new_list.reverse()
    assert new_list.display() == '(5, 20)'
Exemplo n.º 15
0
 def insert(self, data):
     LinkedList.insert(self, data)  # This updates head, no previous needed on it
     if not self.tail:  # There's nothing in the list!
         self.tail = self.head  # This is the only thing, no previous or next
     else:  # There was other stuff in the list, the old head (head.next) needs a previous
         self.head.next.previous = self.head
     self.head.previous = None  # Need to define this attribute, since LinkedList.insert only makes a regular Node
Exemplo n.º 16
0
 def test_remove_last(self):
     l = LinkedList()
     l.add_first(1)
     l.add_first(2)
     self.assertEquals(1, l.remove_last())
     self.assertEquals(1, len(l))
     self.assertEquals('[2]', str(l))
def test_size():
    joe = Node("Joe")
    bob = Node("Bob")
    new = LinkedList()
    new.insert(bob)
    new.insert(joe)
    assert new.size() == 2
def test_add_second_node():
    joe = Node("Joe")
    bob = Node("Bob")
    new = LinkedList()
    new.insert(bob)
    new.insert(joe)
    assert new.first._next.val == "Bob"
def test_search_success():
    joe = Node("Joe")
    bob = Node("Bob")
    new = LinkedList()
    new.insert(bob)
    new.insert(joe)
    assert new.search("Bob") == bob
def test_search_fail():
    joe = Node("Joe")
    bob = Node("Bob")
    new = LinkedList()
    new.insert(bob)
    new.insert(joe)
    assert new.search("Fred") is None
Exemplo n.º 21
0
class AssociativeArray:
    def __init__(self):
        self.items = LinkedList()

    def __unicode__(self):
        s = ''
        for key, value in self.items:
            s += repr(key) + ': ' + repr(value) + ', '
        return '{' + s + '}'

    __repr__ = __unicode__

    def put(self, key, value):
        for i, kv in enumerate(self.items):
            if kv[0] == key:
                l1 = self.items.take(i)
                l2 = self.items.drop(i + 1)
                self.items = l1.concat(l2)
                break
        self.items = self.items.append((key, value))

    def get(self, key):
        for k, v in self.items:
            if k == key:
                return v
def get_representative_trajectory_average_inputs(trajectory_line_segments, min_lines, min_prev_dist):
    cur_active = [False] * len(trajectory_line_segments)
    active_list = LinkedList()        
    insert_list = [] 
    delete_list = []
    out = []
    
    line_segment_endpoints = get_sorted_line_seg_endpoints(trajectory_line_segments)
        
    i = 0
    while i < len(line_segment_endpoints):
        insert_list[:] = []
        delete_list[:] = []
        prev_pos = line_segment_endpoints[i].horizontal_position
        
        while i < len(line_segment_endpoints) and numbers_within(line_segment_endpoints[i].horizontal_position, \
                                                                 prev_pos, DECIMAL_MAX_DIFF_FOR_EQUALITY):
            if not cur_active[line_segment_endpoints[i].line_segment_id]:
                insert_list.append(line_segment_endpoints[i])
                cur_active[line_segment_endpoints[i].line_segment_id] = True
            elif cur_active[line_segment_endpoints[i].line_segment_id]:
                delete_list.append(line_segment_endpoints[i])
                cur_active[line_segment_endpoints[i].line_segment_id] = False
            i += 1
            
        for line_seg_endpoint in insert_list:
            active_list.add_last_node(line_seg_endpoint.list_node)
        possibly_append_to_active_list(active_list, out, prev_pos, min_prev_dist, min_lines)
        for line_seg in delete_list:
            active_list.remove_node(line_seg.list_node)
    
    return out
            
def test_insert():
    """Test insert method."""
    from linked_list import LinkedList
    new_list = LinkedList()
    test_size = new_list.size()
    new_list.insert("test")
    assert test_size < new_list.size()
def test_search():
    """Test search method."""
    from linked_list import LinkedList
    new_list = LinkedList()
    new_list.insert([1, 2, 3, 4])
    query = new_list.search(3)
    assert query.get_data() == 3
Exemplo n.º 25
0
def compress_file(file_to_be_segmented, segment_length, output_location=None):
	"""
	A method to compress a file by segmenting the text then allocating an integer value to represent that segmented string
	then optimize the compression by creating a list of positions of each segment at a given time 
	"""

	#Edge Case: we can't do anything if the segment_length doesn't make sense
	greater_than_zero_or_raise(segment_length)

	position_list = LinkedList() 	#doubly linkedlist of nodes that correspond to a segment for easy reordering
	segment = '' 					#to represent a section of text
	initial_legend = OrderedDict() 	#to store segment as a key with (corresponding LLNode reference, compression value) as value
	output_list = [] 				#the compressed text as a list of positions of compressed values from position_list

	compression_value = 0			#an integer to represent a segment counting from 0 up by when it was added
	current_letter_index = 1		#an interger to remember where in the text the current letter is for seeking back
	with open(file_to_be_segmented) as text:

		current_letter = text.read(1)
		while current_letter:

			segment += current_letter

			
			next_letter = text.read(1)
			text.seek(current_letter_index)
			current_letter_index += 1

			#check if the segment is ready to be added
			if segment_ready_to_be_added(segment, segment_length, current_letter, next_letter):
				
				#if segment in dictionary: create an LLNode and add last position to output_list
				if segment in initial_legend:
					output_list.append(initial_legend[segment][0].position)
					position_list.move_to_head(initial_legend[segment][0])
					segment = ""

				#if segment not in dictionary: find it in head and add position to output_list
				else:
					new_node = LLNode()
					position_list.add_to_head(new_node)
					output_list.append(compression_value)
					initial_legend[segment] = (new_node, compression_value)
					compression_value += 1
					segment = ""

			current_letter = text.read(1)

	(output_list_as_string, output_legend) = format_printouts(output_list, 
															  initial_legend)

	if not output_location:
		print output_list_as_string
		print output_legend
	else:
		output_file = open(output_location, 'w+b')
		output_file.write(output_list_as_string + '\n') #print string object of output_list with spaces seperating numbers
		output_file.write(output_legend) #print string of dictionary values in order
		output_file.close()
    def test_exists_method(self):
        linked_list = LinkedList()
        find_me = {'foo4': 'bar', 'bar': 123}

        self.assertFalse(linked_list.exists(find_me))

        linked_list.insert(find_me)
        self.assertTrue(linked_list.exists(find_me))
Exemplo n.º 27
0
def linked_list():
    """Test fixture for linked list tests."""
    from linked_list import LinkedList
    ll = LinkedList()
    ll.insert('a')
    ll.insert('b')
    ll.insert('c')
    return ll
Exemplo n.º 28
0
def test_search_LinkedList():
    from linked_list import Node
    test_list = LinkedList()
    test_list2 = LinkedList([1, 2, 3])
    test_node = Node(3)
    assert test_list2.search(3).val == test_node.val
    assert test_list.search(50) is None
    assert test_list2.search(50) is None
Exemplo n.º 29
0
def test_insert():
    """Test insert works."""
    from linked_list import LinkedList
    my_list = LinkedList()
    my_list.insert('a')
    my_list.insert('b')
    my_list.insert('c')
    assert my_list.head.val == 'c'
    def test_retrieve_method(self):
        linked_list = LinkedList()
        find_me = {'foo4': 'bar', 'bar': 123}

        self.assertFalse(linked_list.retrieve(find_me))

        linked_list.insert(find_me)
        self.assertEqual(find_me, linked_list.retrieve(find_me))
Exemplo n.º 31
0
 def test_delete_with_3_items(self):
     ll = LinkedList(['A', 'B', 'C'])
     assert ll.head.data == 'A'  # First item
     assert ll.tail.data == 'C'  # Last item
     ll.delete('A')
     assert ll.head.data == 'B'  # New head
     assert ll.tail.data == 'C'  # Unchanged
     ll.delete('C')
     assert ll.head.data == 'B'  # Unchanged
     assert ll.tail.data == 'B'  # New tail
     ll.delete('B')
     assert ll.head is None  # No head
     assert ll.tail is None  # No tail
     # Delete should raise error if item was already deleted
     with self.assertRaises(ValueError):
         ll.delete('A')  # Item no longer in list
     with self.assertRaises(ValueError):
         ll.delete('B')  # Item no longer in list
     with self.assertRaises(ValueError):
         ll.delete('C')  # Item no longer in list
Exemplo n.º 32
0
 def test_count(self):
     self.assertEqual(LinkedList([1, 2, 3]).count(), 3)
from linked_list import LinkedList

# Return Kth to Last: Implement an algorithm to find the kth to last element of a singly linked list.

linked_list = LinkedList()
linked_list.add(90)
linked_list.add(2)
linked_list.add(31)
linked_list.add(7)
linked_list.add(8)
linked_list.add(9)
linked_list.add(55)
linked_list.add(12)
linked_list.add(4)


def kthToTheLast(k):
    head = linked_list.head
    tail = linked_list.head

    count = 1
    while head != None and count < k:
        count += 1
        head = head.next

    if (head == None):
        return None

    print("head: " + str(head.data))
    print("tail: " + str(tail.data))
Exemplo n.º 34
0
class LinkedListTests(unittest.TestCase):
    def setUp(self):
        self.linked_list = LinkedList()

    def tearDown(self):
        self.linked_list = None

    # test creation of empty linked list
    def test_create_linked_list(self):
        self.assertTrue(self.linked_list.is_empty())

    # test appending different key value pairs to linked list
    def test_append_to_linked_list(self):
        self.linked_list.append("test", "testing")
        self.assertEqual("testing", self.linked_list.get("test"))
        self.assertTrue(self.linked_list.is_included("test"))

        self.assertFalse(self.linked_list.is_included("another test"))
        self.linked_list.append("another test", "testing!")
        self.assertEqual("testing!", self.linked_list.get("another test"))
        self.assertTrue(self.linked_list.is_included("another test"))

    # test that linked list is empty after appending and then
    # removing a node
    def test_remove_from_linked_list(self):
        node = self.linked_list.append("test", "testing")
        self.linked_list.remove("test")
        self.assertTrue(self.linked_list.is_empty())

    # test that changing the associated value of a node with
    # a given key works
    def test_update_value_in_linked_list(self):
        self.linked_list.append("test", "testing")
        self.linked_list.update("test", "testing123")
        self.assertEqual("testing123", self.linked_list.get("test"))

    # test that returning all key value pairs in linked list works as expected
    def test_get_all_items_in_linked_list(self):
        self.linked_list.append("test", "testing")
        self.linked_list.append("testing!", "testing123!")

        self.assertEqual([('test', 'testing'), ('testing!', 'testing123!')],
                         self.linked_list.items())
        self.assertEqual(['test', 'testing!'], self.linked_list.keys())
        self.assertEqual(['testing', 'testing123!'], self.linked_list.values())
Exemplo n.º 35
0
 def test_delete_with_item_not_in_list(self):
     ll = LinkedList(['A', 'B', 'C'])
     # Delete should raise error if item not found
     with self.assertRaises(ValueError):
         ll.delete('X')  # Item not found in list
Exemplo n.º 36
0
 def setUp(self):
     self.list = LinkedList()
Exemplo n.º 37
0
 def test_remove_dups(self):
     ll_with_dups = LinkedList()
     ll_with_dups.append(2)
     ll_with_dups.append(3)
     ll_with_dups.append(2)
     ll_with_dups.append(5)
     ll_with_dups.append(6)
     ll_with_dups.append(1)
     ll_with_dups.append(2)
     ll_with_dups.append(2)
     self.assertEqual(ll_with_dups.length(), 8)
     self.assertEqual(ll_with_dups.to_s(), '2 3 2 5 6 1 2 2')
     ll_with_dups.remove_dups()
     self.assertEqual(ll_with_dups.length(), 5)
     self.assertEqual(ll_with_dups.to_s(), '2 3 5 6 1')
Exemplo n.º 38
0
 def setUp(self):
     self.ll = LinkedList(1)
     self.ll.append(2)
     self.ll.append(3)
     self.ll.append(4)
     self.gold = ['1','2','4']
Exemplo n.º 39
0
 def __init__(self, size):
     self.array_size = size
     #self.array = [None for i in range(size)]
     #self.array = [None] * size
     #self.array = [LinkedList() for i in range(size)]
     self.array = [LinkedList()] * size
Exemplo n.º 40
0
def delete_mid(l_list):
    if isinstance(l_list, LinkedList):
        fast_ptr = l_list.head
        slow_ptr = l_list.head

        while fast_ptr is not None:
            try:
                fast_ptr = fast_ptr.next
                fast_ptr = fast_ptr.next
            except AttributeError:
                break
            slow_ptr = slow_ptr.next

        print(slow_ptr.data)
    else:
        raise Exception("param not of type 'LinkedList'")


if __name__ == '__main__':
    ll = LinkedList()
    ll.push(1)
    ll.push(2)
    ll.push(3)
    ll.push(4)
    ll.push(5)
    ll.push(6)
    ll.push(7)
    print(ll)
    delete_mid(ll)
    print(ll)
Exemplo n.º 41
0
    temp = head
    prev = None
    while (temp and temp.next):
        if head == temp:
            head = temp.next
        swap_in_pairs(node1=temp, node2=temp.next, prev=prev)
        prev = temp
        temp = temp.next
    return head


def swap_in_pairs(node1, node2, prev):
    temp = node2.next
    node2.next = node1
    node1.next = temp
    if prev:
        prev.next = node2


if __name__ == '__main__':
    linked_list = LinkedList()
    llist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    linked_list.create_linked_list(input_list=llist)
    print("Linked list before")
    linked_list.print_list()
    current_head = linked_list.head
    new_head = reverse_in_pairs(head=current_head)
    new_list = LinkedList(head=new_head)
    print("Linked list after")
    new_list.print_list()
 def __init__(self, capacity):
     self.capacity = capacity
     self.data = [LinkedList()] * capacity
     self.load = 0
Exemplo n.º 43
0
    def test_add_list(self):
        my_list = LinkedList()
        new_list = my_list + LinkedList([1])
        self.assertEqual(new_list, LinkedList([1]))
        self.assertEqual(my_list, LinkedList())

        my_list = LinkedList([1, 2])
        new_list = my_list + LinkedList([3, 4])
        self.assertEqual(new_list, LinkedList([1, 2, 3, 4]))
        self.assertEqual(my_list, LinkedList([1, 2]))

        my_list = LinkedList([1, 2])
        new_list = my_list + LinkedList()
        self.assertEqual(new_list, LinkedList([1, 2]))
        self.assertEqual(my_list, LinkedList([1, 2]))

        my_list = LinkedList()
        new_list = my_list + LinkedList()
        self.assertEqual(new_list, LinkedList())
        self.assertEqual(new_list.count(), 0)
        self.assertEqual(my_list, LinkedList())
        self.assertEqual(my_list.count(), 0)
Exemplo n.º 44
0
 def test_unshift_pop(self):
     lst = LinkedList()
     lst.unshift(10)
     lst.unshift(20)
     self.assertEqual(lst.pop(), 10)
     self.assertEqual(lst.pop(), 20)
Exemplo n.º 45
0
    while current != None:
        current = current.next
        length += 1
    current = linked_list.head
    while length > k:
        current = current.next
        length -= 1
    return current.data


"""Optimized Solution"""


def kth_o(linked_list, k):
    first = linked_list.head
    second = linked_list.head
    while first != None and k > 0:
        first = first.next
        k -= 1
    while first is not None:
        first = first.next
        second = second.next

    return second.data


if __name__ == '__main__':
    ll = LinkedList(['a', 'b', 'c', 'd', 'e', 'f'])
    print(kth(ll, 1))
    print(kth_o(ll, 1))
Exemplo n.º 46
0
 def __init__(self, init_size=8):
     """Initialize this hash table with the given initial size."""
     # Create a new list (used as fixed-size array) of empty linked lists
     self.buckets = [LinkedList() for _ in range(init_size)]
Exemplo n.º 47
0
def test_pop_empty():
    """Ensure that the pop method raises an error on an empty list."""
    from linked_list import LinkedList
    test_linked_list = LinkedList()
    with pytest.raises(IndexError):
        test_linked_list.pop()
Exemplo n.º 48
0
 def test_delete_with_5_items(self):
     ll = LinkedList(['A', 'B', 'C', 'D', 'E'])
     assert ll.head.data == 'A'  # First item
     assert ll.tail.data == 'E'  # Last item
     ll.delete('A')
     assert ll.head.data == 'B'  # New head
     assert ll.tail.data == 'E'  # Unchanged
     ll.delete('E')
     assert ll.head.data == 'B'  # Unchanged
     assert ll.tail.data == 'D'  # New tail
     ll.delete('C')
     assert ll.head.data == 'B'  # Unchanged
     assert ll.tail.data == 'D'  # Unchanged
     ll.delete('D')
     assert ll.head.data == 'B'  # Unchanged
     assert ll.tail.data == 'B'  # New tail
     ll.delete('B')
     assert ll.head is None  # No head
     assert ll.tail is None  # No tail
Exemplo n.º 49
0
class TestLinkedList(unittest.TestCase):

    def setUp(self):
        self.list = LinkedList()


    def tearDown(self):
        self.list = None


    def test_append(self):
        self.list.append("Mr. Green")

        self.assertTrue(self.list.head.data == "Mr. Green")
        self.assertTrue(self.list.head.next_node is None)


    def test_append_two(self):
        self.list.append("Mr. Green")
        self.list.append("Miss Scarlet")

        self.assertTrue(self.list.head.data == "Miss Scarlet")

        new_head = self.list.head.next_node
        self.assertTrue(new_head.data == "Mr. Green")


    def test_next_node(self):
        self.list.append("Prof. Plum")
        self.list.append("Mrs. Peacock")
        self.list.append("Mr. Boddy")

        self.assertTrue(self.list.head.data == "Mr. Boddy")

        new_head = self.list.head.next_node
        self.assertTrue(new_head.data == "Mrs. Peacock")

        last = new_head.next_node
        self.assertTrue(last.data == "Prof. Plum")


    def test_len(self):
        self.list.append("Prof. Plum")
        self.list.append("Mrs. Peacock")
        self.list.append("Mr. Boddy")

        length = self.list.__len__()

        self.assertTrue(length == 3)


    def test_len_zero(self):
        length = self.list.__len__()

        self.assertTrue(length == 0)


    def test_len_one(self):
        self.list.append("Prof. Plum")
        length = self.list.__len__()

        self.assertTrue(length == 1)


    def test_succeed_getitem(self):
        self.list.append("Prof. Plum")
        self.list.append("Mrs. Peacock")
        self.list.append("Mr. Boddy")

        result = self.list.__getitem__(0)
        self.assertTrue(result == "Mr. Boddy")

        result = self.list.__getitem__(1)
        self.assertTrue(result == "Mrs. Peacock")

        result = self.list.__getitem__(2)
        self.assertTrue(result == "Prof. Plum")


    def test_fail_getitem(self):
        self.list.append("Prof. Plum")
        self.list.append("Mrs. Peacock")

        with self.assertRaises(IndexError):
            self.list.__getitem__(2)


    #@unittest.skip('Extra Challenge: pop method.')
    def test_pop(self):
        self.list.append("Prof. Plum")
        self.list.append("Mrs. Peacock")
        self.list.append("Mr. Boddy")

        old_head = self.list.pop()
        self.assertTrue(old_head.data == "Mr. Boddy")

        new_head = self.list.head
        self.assertTrue(new_head.data == "Mrs. Peacock")

        new_length = len(self.list)
        self.assertTrue(new_length == 2)


    #@unittest.skip('Extra Challenge: pop method.')
    def test_pop_empty_list(self):
        with self.assertRaises(IndexError):
            self.list.pop()


    #@unittest.skip('Extra Challenge: __delitem__ method.')
    def test_delete(self):
        self.list.append("Prof. Plum")
        self.list.append("Mrs. Peacock")
        self.list.append("Mr. Boddy")

        # Delete the list head
        self.list.__delitem__(0)
        self.assertTrue(self.list.head.data == "Mrs. Peacock")

        # Delete the list tail
        self.list.__delitem__(1)
        self.assertTrue(self.list.head.next_node is None)

        new_length = len(self.list)
        self.assertTrue(new_length == 1)


    #@unittest.skip('Extra Challenge: __delitem__ method.')
    def test_delete_value_not_in_list(self):
        self.list.append("Prof. Plum")
        self.list.append("Mrs. Peacock")
        self.list.append("Mr. Boddy")

        with self.assertRaises(IndexError):
            self.list.__delitem__(3)


    #@unittest.skip('Extra Challenge: __delitem__ method.')
    def test_delete_empty_list(self):
        with self.assertRaises(IndexError):
            self.list.__delitem__(1)


    #@unittest.skip('Extra Challenge: __delitem__ method.')
    def test_delete_next_reassignment(self):
        self.list.append("Prof. Plum")
        self.list.append("Mrs. White")
        self.list.append("Mrs. Peacock")
        self.list.append("Mr. Boddy")

        self.list.__delitem__(1)
        self.list.__delitem__(1)

        self.assertTrue(self.list.head.next_node.data == "Prof. Plum")
Exemplo n.º 50
0
def test_search_found():
    """Test that push value to list then search for it."""
    from linked_list import LinkedList
    test_linked_list = LinkedList()
    test_linked_list.push(20)
    assert test_linked_list.search(20)
Exemplo n.º 51
0
def list_fixture():
    from linked_list import LinkedList
    l = LinkedList()
    return l
Exemplo n.º 52
0
 def __init__(self, size):
     self.array_size = size
     self.array = [LinkedList() for i in range(size)]
    node = lst.root

    while node:
        if node.data < x:
            data = node.data
            lst.delete(node.data)
            lst.add(data)

        node = node.next

    #test
    n = lst.root
    line = ""
    while n:
        line += str(n.data) + ","
        n = n.next

    print(line)


if __name__ == "__main__":
    l = LinkedList(1)
    l.add(4)
    l.add(2)
    l.add(7)
    l.add(5)

    partition_list(l, 4)
    #shold return
    #4,2,1,5,7
Exemplo n.º 54
0
 def __init__(self):
     self.storage = LinkedList()
Exemplo n.º 55
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 28 12:54:49 2019

@author: pabloruizruiz
"""

from linked_list import LinkedList


def delete_middle_node(node):
    message = "Node to delete can't be head or tail nodes from the list"
    assert node.next is not None, message
    node.data = node.next.data
    node.next = node.next.next


ll = LinkedList()
ll.add_multiple([7, 4, 3])
middle_node = ll.add(5)
ll.add_multiple([7, 4, 3])

print(ll)
delete_middle_node(middle_node)
print(ll)
Exemplo n.º 56
0
 def test_push_pop(self):
     lst = LinkedList()
     lst.push(10)
     lst.push(20)
     self.assertEqual(lst.pop(), 20)
     self.assertEqual(lst.pop(), 10)
Exemplo n.º 57
0
    def test_add_equals_list(self):
        my_list = LinkedList()
        my_list += LinkedList([1, 2])
        self.assertEqual(my_list, LinkedList([1, 2]))

        my_list = LinkedList([1, 2])
        my_list += LinkedList([3, 4])
        self.assertEqual(my_list, LinkedList([1, 2, 3, 4]))

        my_list = LinkedList([1, 2])
        my_list += LinkedList()
        self.assertEqual(my_list, LinkedList([1, 2]))

        my_list = LinkedList()
        my_list += LinkedList()
        self.assertEqual(my_list.count(), 0)
        self.assertEqual(my_list, LinkedList())
Exemplo n.º 58
0
 def test_all(self):
     lst = LinkedList()
     lst.push(10)
     lst.push(20)
     self.assertEqual(lst.pop(), 20)
     lst.push(30)
     self.assertEqual(lst.shift(), 10)
     lst.unshift(40)
     lst.push(50)
     self.assertEqual(lst.shift(), 40)
     self.assertEqual(lst.pop(), 50)
     self.assertEqual(lst.shift(), 30)
Exemplo n.º 59
0
 def test_init(self):
     ll = LinkedList()
     # Initializer should add instance properties
     assert ll.head is None  # First node
     assert ll.tail is None  # Last node
Exemplo n.º 60
0
 def test_find(self):
     ll = LinkedList(['A', 'B', 'C'])
     assert ll.find(lambda item: item == 'B') == 'B'  # Match equality
     assert ll.find(lambda item: item < 'B') == 'A'  # Match less than
     assert ll.find(lambda item: item > 'B') == 'C'  # Match greater than
     assert ll.find(lambda item: item == 'X') is None  # No matching item