Exemple #1
0
    def test_extend_empty_both_list(self):
        linked_list = LinkedList()
        linked_list1 = LinkedList()

        linked_list1.extend(linked_list)
        self.assertEqual(linked_list.head, None)
        self.assertEqual(linked_list.tail, None)
 def test_remove_empty_list(self):
     """Remove from an empty LinkedList."""
     ll = LinkedList()
     prestring = ll.__str__()
     ll.remove(self.insert_float)
     poststring = ll.__str__()
     self.assertEqual(prestring, poststring)
 def test_pop_from_empty_list(self):
     """Pop from a LinkedList that is empty."""
     ll = LinkedList()
     self.assertTrue(ll.head is None)
     node = ll.pop()
     self.assertTrue(node is None)
     self.assertTrue(ll.head is None)
    def test_first_item(self):
        test_list = LinkedList()
        test_list.insert_front(5)

        self.assertEqual(5,
                         test_list.pop_front()._node_value,
                         "first item did not insert correctly")
Exemple #5
0
def reverse_part_of_linked_list(head: LinkedList, start: int,
                                end: int) -> LinkedList:
    if not head or start == end:
        return head

    outside_pointer = LinkedList(None)
    outside_pointer.next = head

    current_node = head
    previous_node = outside_pointer

    while start > 1:
        previous_node = current_node
        current_node = current_node.next
        start -= 1
        end -= 1

    while end > 1:
        next_node = current_node.next
        current_node.next = next_node.next
        next_node.next = previous_node.next
        previous_node.next = next_node
        end -= 1

    return outside_pointer.next
def test_add_first_one_item():
    linked_list = LinkedList()
    linked_list.add_first(1)

    assert len(linked_list) == 1
    assert linked_list.head == 1
    assert linked_list.tail == 1
Exemple #7
0
 def enqueue(self, value):
     new_item = LinkedList(value)
     new_item.previous = self._head
     new_item.next = self._head.next
     self._head.next.previous = new_item
     self._head.next = new_item
     self._size += 1
Exemple #8
0
class Stack:
    def __init__(self) -> None:
        self._list = LinkedList()

    def __len__(self) -> int:
        return len(self._list)

    def __iter__(self) -> Generator[T]:
        for item in self._list:
            yield item

    def push(self, data: T) -> None:
        self._list.add_first(data)

    def peek(self) -> T:
        if len(self._list) == 0:
            raise IndexError("peek from empty list")
        return self._list.head.data

    def pop(self) -> T:
        if len(self._list) == 0:
            raise IndexError("pop from empty list")
        data = self._list.head.data
        self._list.remove_first()
        return data
Exemple #9
0
 def test_append(self):
     linked_list = LinkedList()
     linked_list.append(data=0)
     linked_list.append(data=1)
     self.assertEqual(linked_list.head.data, 0)
     self.assertEqual(linked_list.tail.data, 1)
     self.assertNotEqual(linked_list.head, None)
     self.assertNotEqual(linked_list.tail, None)
def test_kth_from_end_zero():
    linked_list = LinkedList()
    values = ["apples", "bananas", "cucumbers"]
    for value in reversed(values):
        linked_list.insert(value)
    actual = linked_list.kth_from_end(0)
    expected = "cucumbers"
    assert actual == expected
    def test_remove_item(self):
        ll = LinkedList()
        ll.add(1)
        ll.add(2)

        self.assertEqual(len(ll), 2)
        ll.remove(1)
        self.assertEqual(len(ll), 1)
def test_container():
    linked_list = LinkedList()
    linked_list.add_last(1)
    linked_list.add_last(2)

    assert 1 in linked_list
    assert 2 in linked_list
    assert 3 not in linked_list
 def test_pop_from_one_list(self):
     """Pop from a LinkedList with one node."""
     ll = LinkedList()
     ll.insert(self.insert_string)
     self.assertEqual(ll.head.value, self.insert_string)
     node = ll.pop()
     self.assertEqual(node.value, self.insert_string)
     self.assertTrue(ll.head is None)
def test__get(constructor_arg):
    ll = LinkedList(constructor_arg)
    if constructor_arg:
        for index, item in enumerate(constructor_arg):
            assert isinstance(ll._get(index), LinkedListNode)
            assert ll._get(index).value == item
    else:
        assert ll.head is None
Exemple #15
0
 def test_insert_at_index(self):
     self.ll = LinkedList('Data1', 'Data2', 'Data3', 'Data4', 'Data5')
     self.ll.insert_at_index(3, 'Data3.5')
     self.assertEqual(self.ll[3], 'Data3.5', 'Insert at index should set the data at the index')
     self.assertEqual(self.ll[2], 'Data3', 'Insert at index should not change the data at the index before it')
     self.assertEqual(self.ll[4], 'Data4', 'Insert at index should move the other data up an index')
     with self.assertRaises(IndexError, msg='Insert at out of bounds index should raise IndexError'):
         self.ll.insert_at_index(len(self.ll) + 1, 'Data7')
def test_search():
    items = range(10)
    a_list = LinkedList(items)
    # searching for a non-contained item returns None
    assert a_list.search(object()) is None
    # prove those values are searchable
    for item in items:
        assert a_list.search(item).data == item
 def test_text_representation(self):
     self.assertEqual(repr(self.ll), 'LinkedList()')
     self.ll = LinkedList(1)
     self.assertEqual(repr(self.ll), 'LinkedList(1)')
     self.ll = LinkedList([1, 2, 3, 4])
     self.assertEqual(repr(self.ll), 'LinkedList([1, 2, 3, 4])')
     self.ll = LinkedList(1, 2, 3, 4)
     self.assertEqual(repr(self.ll), 'LinkedList(1, 2, 3, 4)')
def test_iterate_over_linked_list():
    my_list = LinkedList()
    for i in range(5):
        my_list.insert_before(i)

    for el in my_list:
        for el1 in my_list:
            print('{} {}'.format(el, el1))
Exemple #19
0
 def test_node_removal(self):
     self.ll = LinkedList(4, 7, 9, 11)
     check_node = self.ll._get_node_at_index(2)
     with self.assertRaises(ValueError):
         self.ll._remove_node(self.ll.tail)
     self.ll._remove_node(self.ll.head)
     self.assertEqual(self.ll, LinkedList(7, 9, 11))
     self.ll._remove_node(check_node)
     self.assertEqual(self.ll, LinkedList(7, 11))
    def test_insert_float_into_empty(self):
        """Insert into a LinkedList that is empty."""
        ll = LinkedList()

        self.assertTrue(ll.head is None)
        ll.insert(self.insert_float)
        self.assertEqual(ll.head.value, self.insert_float)
        self.assertTrue(isinstance(ll.head.value, float))
        self.assertTrue(ll.head.next is None)
def test_add_last_two_items():
    linked_list = LinkedList()
    linked_list.add_last(1)
    linked_list.add_last(2)

    assert len(linked_list) == 2
    assert linked_list.head == 1
    assert linked_list.tail == 2
    assert linked_list.tail.next_ is None
Exemple #22
0
 def test_add_first_to_empty_list(self):
     node1 = LinkedListNode("node 1")
     my_linked_list = LinkedList()
     my_linked_list.add_first(node1)
     print(my_linked_list)
     self.assertEqual(my_linked_list.head.node_value, 'node 1')
     self.assertEqual(my_linked_list.head.next, None)
     self.assertEqual(my_linked_list.tail.node_value, 'node 1')
     self.assertEqual(my_linked_list.tail.next, None)
     self.assertEqual(my_linked_list.length, 1)
Exemple #23
0
 def test_value_at(self):
     linked_list = LinkedList()
     linked_list.append(data=0)
     linked_list.append(data=1)
     linked_list.append(data=2)
     linked_list.append(data=3)
     linked_list.append(data=None)
     self.assertEqual(linked_list.valueAt(1), 1)
     self.assertEqual(linked_list.valueAt(0), 0)
     self.assertEqual(linked_list.valueAt(3), 3)
    def get_constants(self):

        constants = LinkedList()

        constants.push_back('pi')
        constants.push_back('e')
        constants.push_back('-pi')
        constants.push_back('-e')

        return constants
Exemple #25
0
    def test_search(self):
        lst = LinkedList([82, 57, 16, 20, 21, 84, 99, 56, 100, 46])

        node = lst.search(99)
        self.assertEqual(node.data, 99)

        node = lst.search(57)
        self.assertEqual(node.data, 57)

        node = lst.search(777)
        self.assertIsNone(node)
Exemple #26
0
    def test_add_empty_both_list(self):
        linked_list = LinkedList()
        len1 = len(linked_list)

        linked_list1 = LinkedList()
        len2 = len(linked_list1)

        linked_list2 = linked_list + linked_list1
        self.assertEqual(linked_list2.head, None)
        self.assertEqual(linked_list2.tail, None)
        self.assertEqual(len(linked_list2), len1 + len2)
    def test_insert_front(self):

        #Arrange
        linked_list = LinkedList()

        #Act
        linked_list.insert_front(1)
        linked_list.insert_front(2)

        #Assert
        self.assertEqual(2, linked_list.head.value, "value is not correct")
    def test_remove_list_with_value_at_tail(self):
        """Remove from a populated LinkedList a value it contains at its tail."""
        ll = LinkedList()
        ll.insert(self.insert_float)
        ll.insert(self.insert_int)
        ll.insert(self.insert_string)

        ll.remove(self.insert_float)
        expected = '(' + "'" + self.insert_string + "'" + ', ' + \
            str(self.insert_int) + ')'
        poststring = ll.__str__()
        self.assertEqual(expected, poststring)
    def test_delete_any(self):
        test_list = LinkedList()
        test_list.insert_front(5)
        test_list.insert_front(7)
        test_list.insert_front(9)
        test_list.insert_front(7)
        test_list.delete_item(7)

        self.assertEqual(True, test_list.__contains__(7), "7 was not deleted")
Exemple #30
0
class Stack:
    def __init__(self):
        self.list = LinkedList()

    def push(self, item):
        self.list.append_left(item)

    def pop(self):

        if self.list.n == 0:
            raise EmptyStackException

        return self.list.pop(0)
Exemple #31
0
 def test_reverse(self):
     linked_list = LinkedList()
     linked_list.append(data=0)
     linked_list.append(data=1)
     linked_list.append(data=2)
     linked_list.append(data=3)
     linked_list.append(data=4)
     linked_list.reverse()
     self.assertEqual(linked_list.head.data, 4)
     self.assertEqual(linked_list.head.next.data, 3)
     self.assertEqual(linked_list.head.next.next.data, 2)
     self.assertEqual(linked_list.head.next.next.next.data, 1)
     self.assertEqual(linked_list.tail.data, 0)
class FIFOQueue(object):
    def __init__(self):
        self.list = LinkedList()

    def enqueue(self, item):
        self.list.append_right(item)

    def dequeue(self):

        if not self.list.n:
            raise EmptyQueueException

        return self.list.pop(0)
Exemple #33
0
 def test_get_node_by_index(self):
     node1 = LinkedListNode("node 1")
     node2 = LinkedListNode("node 2")
     my_linked_list = LinkedList()
     my_linked_list.add_first(node1)
     my_linked_list.add_last(node2)
     print(my_linked_list)
     with self.assertRaises(IndexError):
         my_linked_list.get_node_by_index(2)
     self.assertEqual(
         my_linked_list.get_node_by_index(0).node_value, 'node 1')
     self.assertEqual(
         my_linked_list.get_node_by_index(1).node_value, 'node 2')
Exemple #34
0
    def test_init(self):
        lst = LinkedList()
        self.assertEqual(list(lst), [])

        lst = LinkedList([])
        self.assertEqual(list(lst), [])

        lst = LinkedList([2, 5, 7, 10])
        self.assertEqual(list(lst), [2, 5, 7, 10])

        expected_list = [random.randint(0, 100) for _ in range(20)]
        lst = LinkedList(expected_list)
        self.assertEqual(list(lst), expected_list)
    def test_reversing_list(self):
        test_list = LinkedList()
        test_list.insert_front(5)
        test_list.insert_front(7)
        test_list.insert_front(9)

        test_list.reverse_list()
        node = test_list.pop_front()

        self.assertEqual(5, node._node_value, "list was not reversed")
def test_b_empty():
    list_a = LinkedList()
    for value in reversed([1, 2, 3]):
        list_a.insert(value)
    list_b = LinkedList()
    actual = zip_lists(list_a, list_b)
    expected = LinkedList()
    for value in reversed([1, 2, 3]):
        expected.insert(value)
    assert str(actual) == str(expected)
def add_linked_lists(n1: LinkedList, n2: LinkedList) -> LinkedList:
    result = LinkedList(None)
    temp = result
    carry_over = 0
    while n1 is not None or n1 is not None or carry_over > 0:
        if n1 is not None:
            carry_over += n1.value
            n1 = n1.next
        if n2 is not None:
            carry_over += n2.value
            n2 = n2.next
        carry_over, next_value = divmod(carry_over, 10)
        temp.next = temp = LinkedList(next_value)
    return result.next
Exemple #38
0
    def test_insert(self):
        lst = LinkedList([82, 57, 16, 20, 21, 84, 99, 56, 100, 46])

        inserted = lst.insert(7, 555)
        self.assertTrue(inserted)

        inserted = lst.insert(2, 86)
        self.assertTrue(inserted)

        inserted = lst.insert(200, 86)
        self.assertFalse(inserted)

        self.assertEqual(list(lst),
                         [82, 57, 86, 16, 20, 21, 84, 99, 555, 56, 100, 46])
    def test_search_list_without_value(self):
        """Search a populated LinkedList for a value it doesn't contain."""
        ll = LinkedList()
        ll.insert(self.insert_float)
        ll.insert(self.insert_int)
        ll.insert(self.insert_string)

        node = ll.search(self.value_not_in_list)
        self.assertTrue(node is None)
    def test_size_of_populated_list(self):
        """Get the size of a populated LinkedList."""
        ll = LinkedList()
        ll.insert(self.insert_float)
        ll.insert(self.insert_int)
        ll.insert(self.insert_string)

        self.assertEqual(ll.head.value, self.insert_string)
        self.assertEqual(ll.size(), 3)
 def test_init(self):
     ll = LinkedList()
     self.assertTrue(ll.is_empty(), msg="initalizing an empty linked list should be empty")
     ll = LinkedList('Data')
     self.assertFalse(ll.is_empty(), msg="initalizing a linked list with one element should not be empty")
     ll = LinkedList(['Data', 'Data2'])
     self.assertFalse(ll.is_empty(), msg="initalizing a linked list with one list should not be empty")
     ll = LinkedList('Data', 'Data2', 'Data3')
     self.assertFalse(ll.is_empty(), msg="initalizing a linked list with multiple element should not be empty")
 def test_partition_around_x(self):
     self.linky = LinkedList()
     l = [1, 2, 3, 4, 5, 6, 7, 5, 8, 9, 10]
     for i in range(len(l)):
         self.linky.insert(l[i])
     self.linky.partition_around_x(5)
     self.assertListEqual([1, 2, 3, 4, 5, 5, 10, 9, 8, 7, 6],
                          self.linky.print_me())
    def test_str_many_list(self):
        """Get the string representation of a LinkedList with many values."""
        ll = LinkedList()
        ll.insert(self.insert_float)
        ll.insert(self.insert_int)
        ll.insert(self.insert_string)

        self.assertEqual(ll.__str__(), '(' + "'" + self.insert_string +
            "', " + str(self.insert_int) + ', ' + str(self.insert_float) +
            ')')
    def test_search_list_with_value_at_tail(self):
        """Search a populated LinkedList for a value it contains at its tail."""
        ll = LinkedList()
        ll.insert(self.insert_float)
        ll.insert(self.insert_int)
        ll.insert(self.insert_string)

        node = ll.search(self.insert_float)
        self.assertTrue(isinstance(node, LinkedListNode))
        self.assertEqual(node.value, self.insert_float)
    def test_insert_float_into_populated(self):
        """Insert into a LinkedList that is already populated with some
        values
        """
        ll = LinkedList()
        ll.insert(self.insert_float)
        ll.insert(self.insert_int)
        ll.insert(self.insert_string)

        self.assertEqual(ll.head.value, self.insert_string)
        ll.insert(self.insert_float)
        self.assertEqual(ll.head.value, self.insert_float)
        self.assertTrue(isinstance(ll.head.value, float))
        self.assertEqual(ll.head.next.value, self.insert_string)
    def test_pop_from_many_list(self):
        """Pop from a LinkedList with many nodes."""
        ll = LinkedList()
        ll.insert(self.insert_float)
        ll.insert(self.insert_int)
        ll.insert(self.insert_string)

        self.assertEqual(ll.head.value, self.insert_string)
        node = ll.pop()
        self.assertEqual(node.value, self.insert_string)
        self.assertEqual(ll.head.value, self.insert_int)
 def test_rem_dups(self):
     self.linky = LinkedList()
     self.linky.insert(1)
     self.linky.insert(1)
     self.linky.insert(2)
     self.linky.insert(2)
     self.linky.insert(3)
     self.linky.insert(3)
     self.linky.rem_dups()
     self.assertListEqual([3, 2, 1], self.linky.print_me())
 def test_merge(self):
     self.ll = LinkedList(4, 7, 9, 11)
     self.assertEqual(self.ll.merge(LinkedList(2, 5, 6, 12, 15, 16)),
                      LinkedList(2, 4, 5, 6, 7, 9, 11, 12, 15, 16),
                      'Merge linked lists should return a sorted linked list')
     self.assertEqual(self.ll.merge(LinkedList(5, 12, 15, 16)),
                      LinkedList(4, 5, 7, 9, 11, 12, 15, 16),
                      'Merge linked lists should return a sorted linked list')
     self.assertEqual(self.ll.merge(LinkedList()),
                      LinkedList(4, 7, 9, 11),
                      'Merge linked lists should return a sorted linked list')
    def test_remove_index(self):
        ll = LinkedList()
        ll.add(1)
        ll.add(2)

        ll.remove_item_at(0)
        self.assertEqual(ll.get_item_at(0), 2)
 def test_get_slices(self):
     self.ll = LinkedList(1, 2, 3, 4, 5)
     self.assertEqual(self.ll[:], LinkedList(1, 2, 3, 4, 5), "Get slice '[:]' should return a shallow copy of the list")
     self.assertEqual(self.ll[2:], LinkedList(3, 4, 5), "Get slice '[2:]' should return a shallow subcopy of the list")
     self.assertEqual(self.ll[:2], LinkedList(1, 2), "Get slice '[:2]' should return a shallow subcopy of the list")
     self.assertEqual(self.ll[1:3], LinkedList(2, 3), "Get slice '[1:3]' should return a shallow subcopy of the list")
     self.assertEqual(self.ll[1:1], LinkedList(), "Get slice '[1:1]' should return an empty linked list")
     self.assertEqual(self.ll[5:], LinkedList(), "Get slice '[5:]' should return an empty linked list")
     self.assertEqual(self.ll[-3:], LinkedList(3, 4, 5), "Get slice '[-3:]' should return a shallow subcopy of the list")
     self.assertEqual(self.ll[:-3], LinkedList(1, 2), "Get slice '[:-3]' should return a shallow subcopy of the list")
     self.assertEqual(self.ll[-4:-2], LinkedList(2, 3), "Get slice '[-4:-2]' should return a shallow subcopy of the list")
     self.assertEqual(self.ll[-2:-2], LinkedList(), "Get slice '[:2]' should return a shallow subcopy of the list")
     self.assertEqual(self.ll[:-5], LinkedList(), "Get slice '[:-5]' should return an empty linked list")
     self.assertEqual(self.ll[1:-5], LinkedList(), "Get slice '[1:-5]' should return an empty linked list, values stop is less than start")
     self.assertEqual(self.ll[::-1], LinkedList(5, 4, 3, 2, 1))
 def test_remove_items(self):
     with self.assertRaises(ValueError, msg='Remove functions should raise ValueError on empty linked list'):
         self.ll.remove_item(None)
     with self.assertRaises(ValueError, msg='Remove functions should raise ValueError on empty linked list'):
         self.ll.remove_head()
     with self.assertRaises(ValueError, msg='Remove functions should raise ValueError on empty linked list'):
         self.ll.remove_tail()
     self.ll = LinkedList(1, 2, 3, 4, 5, 3)
     self.ll.remove_item(2)
     self.assertFalse(2 in self.ll)
     self.ll.remove_item(3)
     self.assertTrue(3 in self.ll)
     self.ll.remove_head()
     self.assertEqual(self.ll['head'], 4)
     with self.assertRaises(ValueError):
         self.ll.remove_item('None')
     with self.assertRaises(ValueError):
         self.ll.remove_item(None)
 def test_get(self):
     with self.assertRaises(IndexError, msg="Get at head/tail from empty linked list should return IndexError"):
         self.ll.get_at_head()
         self.ll.get_at_tail()
     self.ll = LinkedList(1, 2, 3, 4)
     self.assertEqual(self.ll.get_at_head(), 1, 'Get at head should get head data')
     self.assertEqual(self.ll.get_at_tail(), 4, 'Get at tail should get tail data')
     self.assertEqual(self.ll.get_at_index(0), 1, 'Get at index 0 should get first item')
     self.assertEqual(self.ll.get_at_index(2), 3, 'Get at index 2 should get third item')
     self.assertEqual(self.ll.get_at_index(2), self.ll[2])
     self.assertEqual(self.ll.get_at_head(), self.ll['head'])
     self.assertEqual(self.ll.get_at_tail(), self.ll['tail'])
     with self.assertRaises(IndexError, msg='Get at out of bounds index should throw an IndexError'):
         self.ll[len(self.ll)]
     self.assertEqual(self.ll[-1], 4, 'Get at index -1 should return tail item')
     self.assertEqual(self.ll[-2], 3, 'Get at index -2 should return tail item')
     self.assertEqual(self.ll[len(self.ll) - 1], 4, 'Get at last index should return tail item')
     self.assertEqual(self.ll[-len(self.ll)], 1, 'Get at index (-length of list) should return head item')
def test_remove():
    items = list(range(10))
    a_list = LinkedList(items)
    # removing a value that isn't in it should return false
    assert a_list.remove(object()) is False
    assert list(a_list) == list(reversed(items))
    # get 7 and remove it
    seven = a_list.search(7)
    assert a_list.remove(seven) is True
    assert list(a_list) == [9, 8, 6, 5, 4, 3, 2, 1, 0]
    # remove all the even-numbered values
    for node in a_list:
        if node & 1 == 0:
            assert a_list.remove(a_list.search(node)) is True
    assert list(a_list) == [9, 5, 3, 1]
Exemple #54
0
 def setUp(self):
     self.LinkedList = LinkedList()
     self.values = [-3.0, 'new', [], {'test': 1}]
    def test_single_item(self):
        ll = LinkedList()
        ll.add(1)

        self.assertEqual(len(ll), 1)
def test_insert():
    a_list = LinkedList()
    a_list.insert(1)
    assert list(a_list) == [1]
    assert a_list.size() == 1
def test_pop(items):
    s = LinkedList(items)
    for item in reversed(items):
        assert s.pop() == item
    with pytest.raises(IndexError):
        s.pop()
def test_display(items, capfd):
    a_list = LinkedList(items)
    a_list.display()
    out, err = capfd.readouterr()
    assert out == str(tuple(reversed(items))) + '\n'
    assert not err