示例#1
0
def test_value_n_from_end():
    l = SingleLinkedList()
    for i in range(10):
        l.push_back(i)

    assert l.value_n_from_end(0) == 9
    assert l.value_n_from_end(3) == 6
示例#2
0
def test_seq_constructor():
    l = SingleLinkedList([0, 1, 2, 3, 4])

    assert l.length == 5

    for i in range(5):
        assert i == l.pop_front()
示例#3
0
def test_push_back_second():
    l = SingleLinkedList()
    for i in range(5):
        l.push_back(i)

    assert l.tail.data == 4
    assert l.head.data == 0
示例#4
0
def merge_sorted_lists():
    k = 10
    n = 10
    min_value = 0
    max_value = 30
    sorted_lists = generate_sorted_lists(k,n,min_value,max_value)
    sorted_list = SingleLinkedList()
    heap = MinHeap([], 0)
    # fill in the 1st batch
    for i, l in sorted_lists.items():
        heap.add(IdAndValue(i, l.pop(0)))

    while len(sorted_lists) > 0:
        item = heap.pop()
        sorted_list.append(item.get_value())

        list_id = item.get_id()

        if list_id in sorted_lists:
            value = sorted_lists[list_id].pop(0)
            if len(sorted_lists[list_id]) <= 0:
                sorted_lists.pop(list_id)

            heap.add(IdAndValue(list_id, value))

        else:
            list_id, list = sorted_lists.items()[0]
            heap.add(IdAndValue(list_id, list.pop(0)))

            if len(list) <= 0:
                sorted_lists.pop(list_id)
    while not heap.is_empty():
        sorted_list.append(heap.pop())

    print k*n, len(sorted_list), sorted_list
示例#5
0
文件: test_suite.py 项目: xni/SLL
 def test_get_by_index(self):
     count = 10
     l = SingleLinkedList(100 * i for i in range(count))
     indices = list(range(count))
     random.shuffle(indices)
     for random_index in indices:
         value = l.get_n_th_node(random_index).value
         self.assertEqual(100 * random_index, value)
示例#6
0
def test_front():
    l = SingleLinkedList()
    for i in range(10):
        l.push_back(i)
        assert 0 == l.front()

    l = SingleLinkedList()
    for i in range(10):
        l.push_front(i)
        assert i == l.front()
示例#7
0
 def add(self, key, value):
     index = self._get_hash_key(key)
     if (self._hash_table[index]):
         # Need to check for duplicate keys
         #  Overwrite value for existing key
         self._hash_table[index].add_rear(key, value)
     else:
         hash_bucket = SingleLinkedList()
         hash_bucket.add_rear(key, value)
         self._hash_table[index] = hash_bucket
示例#8
0
文件: test_suite.py 项目: xni/SLL
    def test_exceptions(self):
        l1 = SingleLinkedList([1])
        l2 = SingleLinkedList([1])

        l1_node = l1.get_n_th_node(0)
        self.assertRaises(NodeIsUnreachableError,
                          l2.insert_before, l1_node, 3)
        self.assertRaises(InvalidPositionError,
                          l1.insert_at_position, 100, 100)
        self.assertRaises(InvalidPositionError,
                          l1.get_n_th_node, 1)
示例#9
0
文件: test_suite.py 项目: xni/SLL
 def test_insert_after(self):
     l = SingleLinkedList([1])
     node = l.get_n_th_node(0)
     l.insert_after(node, 2)
     self._check_list(l, (1, 2))
     l.insert_after(node, 3)
     self._check_list(l, (1, 3, 2))
     l.insert_after(l.get_n_th_node(2), 7)
     self._check_list(l, (1, 3, 2, 7))
示例#10
0
def test_erase_tail():
    l = SingleLinkedList()
    l.push_back(1)
    assert l.tail.data == 1

    l.push_back(2)
    assert l.tail.data == 2

    l.push_back(3)
    assert l.tail.data == 3

    l.erase(2)

    assert l.tail.data == 2
class Stack:
    def __init__(self):
        self._sll = SingleLinkedList()

    def push(self, value):
        node = Node(value)
        self._sll.insert(node, pos=0)

    def pop(self):
        if self._sll.isEmpty():
            raise Exception("Empty Stack")

        node = self._sll.head
        self._sll.head = self._sll.head.next
        return node.value
class Queue:
    def __init__(self):
        self._sll = SingleLinkedList()

    def enqueue(self, value):
        node = Node(value)
        self._sll.append(node)

    def dequeue(self):
        if self._sll.isEmpty():
            raise Exception("Empty Queue")
        v = self._sll.head
        self._sll.head = self._sll.head.next

        return v.value
示例#13
0
文件: test_suite.py 项目: xni/SLL
 def test_insert_before_by_reordering(self):
     l = SingleLinkedList([1])
     node = l.get_n_th_node(0)
     l.insert_before_by_reordering(node, 3)
     self._check_list(l, (3, 1))
     l.insert_before_by_reordering(node, 5)
     self._check_list(l, (5, 3, 1))
     node = l.get_n_th_node(2)
     node = l.insert_before_by_reordering(node, 8)
     self._check_list(l, (5, 3, 8, 1))
     node = l.insert_before_by_reordering(node, 6)
     self._check_list(l, (5, 3, 8, 6, 1))
示例#14
0
def topo_sort_by_dfs(dg: DirectedGraph):
    adj = dg.adj
    vertex_nums = len(adj)
    visited = [False] * vertex_nums
    reverse_adj = [SingleLinkedList() for _ in range(vertex_nums)]

    # 构造逆邻接表
    for i in range(vertex_nums):
        v = adj[i].head
        while v:
            if v.val is None: break
            id_ = v.val[0]
            reverse_adj[id_].append((i, 1))
            v = v._next

    def dfs(i):
        v = reverse_adj[i].head
        while v:
            if v.val is None or visited[v.val[0]]: break
            id_ = v.val[0]
            visited[id_] = True
            dfs(id_)
            v = v._next
        print(i)

    # 遍历
    for i in range(vertex_nums):
        if visited[i]: continue
        visited[i] = True
        dfs(i)
示例#15
0
def test_erase_middle():
    l = SingleLinkedList()
    l.push_back(1)
    l.push_back(2)
    l.push_back(3)

    assert l.head.next.data == 2
    l.erase(1)
    assert l.head.next.data == 3
示例#16
0
def test_pop_back():
    l = SingleLinkedList()

    l.push_back(1)
    assert l.head.data == 1
    assert l.tail.data == 1

    l.push_back(2)
    assert l.head.data == 1
    assert l.tail.data == 2

    l.push_back(3)
    assert l.head.data == 1
    assert l.tail.data == 3

    assert l.pop_back(), 3
    assert l.pop_back(), 2
    assert l.pop_back(), 1
示例#17
0
class SingleLinkedSet:
    """ Data structure for storing only unique values. 
    
    Not thread-safe.
    """
    def __init__(self, iterable=None):
        self._container = SingleLinkedList()
        if iterable:
            for item in iterable:
                self.add(item)
        
    def add(self, value):
        if not self._container.contains(value):
            self._container.append(value)

    def contains(self, value):
        return self._container.contains(value)

    def __contains__(self, value):
        return self.contains(value)
示例#18
0
def test_push_back():
    l = SingleLinkedList()
    l.push_back(1)
    assert l.tail.data == 1
    assert l.head.data == 1

    l.push_back(2)
    assert l.tail.data == 2
    assert l.head.data == 1
    assert l.head.next.data == l.tail.data

    l.push_back(3)
    assert l.tail.data == 3
    assert l.head.next.next.data == 3
示例#19
0
def test_push_front():
    l = SingleLinkedList()
    l.push_front(1)
    assert l.head.data == 1
    assert l.tail.data == 1

    l.push_front(2)
    assert l.head.data == 2
    assert l.tail.data == 1
    assert l.head.next.data, l.tail.data

    l.push_front(3)
    assert l.head.data == 3
    assert l.head.next.data == 2
示例#20
0
def test_erase_head():
    l = SingleLinkedList()
    l.push_front(1)
    assert l.head.data == 1

    l.erase(0)
    assert l.head == None
示例#21
0
def test_remove_value_middle():
    l = SingleLinkedList()
    for i in range(5):
        l.push_back(i)

    l.remove_value(2)

    assert l.head.next.next.data == 3
示例#22
0
def test_value_at():
    l = SingleLinkedList()
    for i in range(5):
        l.push_back(i)

    assert l.value_at(0) == 0
    assert l.value_at(2) == 2
    assert l.value_at(4) == 4
示例#23
0
def test_remove_value_back():
    l = SingleLinkedList()
    for i in range(5):
        l.push_back(i)

    l.remove_value(4)

    assert l.tail.data == 3
示例#24
0
文件: test_suite.py 项目: xni/SLL
    def test_insert_first_element_to_empty_list(self):
        l = SingleLinkedList()
        l.insert_at_position(0, 'D')
        self._check_is_single_element_list(l)

        l = SingleLinkedList()
        l.insert_at_position(-1, 'D')
        self._check_is_single_element_list(l)
示例#25
0
def test_remove_value_front():
    l = SingleLinkedList()
    for i in range(5):
        l.push_back(i)

    l.remove_value(0)

    assert l.head.data == 1
class SingleLinkedStack0:
    def __init__(self):
        self.items = SingleLinkedList()
        self.length = 0

    def push(self, item):
        self.items.append(item)
        self.length += 1
        return True

    def pop(self):
        if len(self.items) == 0:
            return None
        return self.items.pop(self.length - 1)

    def __len__(self):
        return len(self.items)

    def __repr__(self):
        """
        显示栈的容量
        """
        return "<SingleLinkedStack0: %d>" % self.length
示例#27
0
def test_insert_tail():
    l = SingleLinkedList()
    for i in range(5):
        l.push_back(i)

    l.insert(4, 33)

    assert l.tail.data == 33
    assert l.length == 6
示例#28
0
def test_reverse():
    l = SingleLinkedList()
    for i in range(5):
        l.push_front(i)

    l.reverse()

    assert l.head.data == 0
    assert l.tail.data == 4
    assert l.tail.next == None

    for i in range(5):
        assert l.pop_front() == i
def is_palindrome1(single_linked):
    # 如果回文串长度为 0 或 1 则为回文串
    if single_linked.length in [0, 1]:
        return True
    fast, slow = single_linked.head, single_linked.head
    # 寻找中间节点
    while fast._next and fast._next._next:
        slow = slow._next
        fast = fast._next._next
    # 后半部分逆序
    prev = slow._next
    if not prev._next:
        second_part = SingleLinkedList(prev)
    else:
        current = prev._next
        after = prev._next._next
        prev._next = None
        while True:
            current._next = prev
            prev = current
            current = after
            if not current:
                second_part = SingleLinkedList(prev)
                break
            else:
                after = current._next
    # 判断是否是回文串
    node1 = single_linked.head
    node2 = second_part.head
    while node2:
        if node1.val != node2.val:
            return False
        else:
            node1 = node1._next
            node2 = node2._next
    return True
示例#30
0
def test_instert_head():
    l = SingleLinkedList()
    for i in range(5):
        l.push_back(i)

    assert l.head.data == 0
    assert l.tail.data == 4

    l.insert(0, 33)
    assert l.head.data == 33
示例#31
0
def test_insert_middle():
    l = SingleLinkedList()

    for i in range(10):
        l.push_back(i)

    l.insert(3, 99)

    assert l.head.next.next.next.data == 99
    assert l.head.next.next.next.next.data == 3
示例#32
0
def test_pop_front():
    l = SingleLinkedList()
    for i in range(5):
        l.push_back(i)

    for i in range(4):
        assert l.pop_front() == i
        assert l.head.data == i + 1

    assert l.head.data == l.tail.data
    assert l.tail.data == 4

    l.pop_front()

    assert l.head == None
    assert l.tail == None
示例#33
0
 def information_getting(self):
     info = input(
         "If you want to know your statistics, insert info, otherwise GAME OVER: "
     )
     print()
     if info.lower() == "info":
         print()
         print(f"* {self.ranking()} * {self.username}")
         ll = SingleLinkedList()
         for key, value in self.game["players"][self.username].items():
             if type(value) != list:
                 ll.insert_last(f"{key}: {value}")
         ll.print_list()
         print()
     print("Thanks for playing. See you next time!")
     exit()
def sum_lists(list1, list2):
    current_l1_node = list1.head()
    current_l2_node = list2.head()
    rest = 0
    sum_list = SingleLinkedList.new()
    while current_l1_node is not None or current_l2_node is not None:
        l1_digit = current_l1_node.data() if current_l1_node else 0
        l2_digit = current_l2_node.data() if current_l2_node else 0
        sum = l1_digit + l2_digit + rest
        if is_two_digit_number(sum):
            rest = sum / 10
            sum %= 10
        else:
            rest = 0
        if at_both_ends(current_l1_node, current_l2_node):
            sum_list.insert_data_at_beggining(sum)
            if rest > 0:
                sum_list.insert_data_at_beggining(rest)
            break
        else:
            sum_list.insert_data_at_beggining(sum)
        current_l1_node = current_l1_node.next_element() if current_l1_node else None
        current_l2_node = current_l2_node.next_element() if current_l2_node else None
    return sum_list
示例#35
0
 def __init__(self, iterable=None):
     self._container = SingleLinkedList()
     if iterable:
         for item in iterable:
             self.add(item)
    fast = single_linked.head
    slow = single_linked.head

    # 慢指针前进过程中前半部分逆序
    while fast and fast._next:
        fast = fast._next._next
        next_ = slow._next
        slow._next = prev
        prev = slow
        slow = next_

    # 针对奇数情况
    if fast:
        slow = slow._next

    # 对比
    while slow:
        if slow.val != prev.val:
            return False
        else:
            slow = slow._next
            prev = prev._next
    return True


if __name__ == "__main__":
    test = SingleLinkedList()
    for i in ['a', 'b']:
        test.append(i)

    print(is_palindrome2(test))
示例#37
0
def test_iteration():
    l = SingleLinkedList([0, 1, 2, 3, 4, 5])
    i = 0
    for element in l:
        assert element == i
        i += 1
示例#38
0
文件: test_suite.py 项目: xni/SLL
    def test_contains(self):
        l = SingleLinkedList()
        self.assertFalse(l.contains(0))
        self.assertFalse(l.contains(1))
        self.assertFalse(l.contains(None))

        l = SingleLinkedList([1, 2, 3])
        self.assertTrue(l.contains(1))
        self.assertTrue(l.contains(2))
        self.assertTrue(l.contains(2.0))
        self.assertTrue(l.contains(3))
        self.assertFalse(l.contains(4))
        self.assertFalse(l.contains(-1))
        self.assertFalse(l.contains(None))
        self.assertFalse(l.contains({'some': 'datatype'}))
        self.assertFalse(l.contains(2.01))
            sum %= 10
        else:
            rest = 0
        if at_both_ends(current_l1_node, current_l2_node):
            sum_list.insert_data_at_beggining(sum)
            if rest > 0:
                sum_list.insert_data_at_beggining(rest)
            break
        else:
            sum_list.insert_data_at_beggining(sum)
        current_l1_node = current_l1_node.next_element() if current_l1_node else None
        current_l2_node = current_l2_node.next_element() if current_l2_node else None
    return sum_list

# TEST 1
list1 = SingleLinkedList.new()
list1.append_from_iterable(iterable=[1, 2, 3])
list2 = SingleLinkedList.new()
list2.append_from_iterable(iterable=[4, 1, 6])
new_list = sum_lists(list1, list2)
new_list.show()

# TEST 2
list1 = SingleLinkedList.new()
list1.append_from_iterable(iterable=[6, 4, 8])
list2 = SingleLinkedList.new()
list2.append_from_iterable(iterable=[3, 1, 9])
new_list = sum_lists(list1, list2)
new_list.show()

# TEST 3
示例#40
0
文件: test_suite.py 项目: xni/SLL
 def test_empty(self):
     l = SingleLinkedList()
     self.assertTrue(l.empty())
     l = SingleLinkedList([0])
     self.assertFalse(l.empty())
 def __init__(self):
     self._sll = SingleLinkedList()
示例#42
0
def test_back():
    l = SingleLinkedList()
    for i in range(10):
        l.push_back(i)

    assert 9 == l.tail.data
示例#43
0
文件: test_suite.py 项目: xni/SLL
 def test_insert_before(self):
     l = SingleLinkedList([1])
     node = l.get_n_th_node(0)
     l.insert_before(node, 5)
     self._check_list(l, (5, 1))
     l.insert_before(node, 4)
     self._check_list(l, (5, 4, 1))
     l.insert_before(l.get_n_th_node(0), 9)
     self._check_list(l, (9, 5, 4, 1))
     l.insert_before(l.get_n_th_node(2), 12)
     self._check_list(l, (9, 5, 12, 4, 1))
示例#44
0
文件: test_suite.py 项目: xni/SLL
 def test_insert_at_position(self):
     l = SingleLinkedList([9, 6, 5])
     l.insert_at_position(0, -3)
     self._check_list(l, (-3, 9, 6, 5))
     l.insert_at_position(0, -4)
     self._check_list(l, (-4, -3, 9, 6, 5))
     l.insert_at_position(1, -5)
     self._check_list(l, (-4, -5, -3, 9, 6, 5))
     l.insert_at_position(4, -6)
     self._check_list(l, (-4, -5, -3, 9, -6, 6, 5))
     l.insert_at_position(7, -7)
     self._check_list(l, (-4, -5, -3, 9, -6, 6, 5, -7))
示例#45
0
 def category_picking(self):
     print(
         f'''Hello {self.username}, lets play a game. To start, you need to pick a category.''',
         end="\n\n")
     ll = SingleLinkedList()
     for i in self.game['categories'].keys():
         ll.insert_last(i)
     ll.print_list()
     print()
     self.category = input("Please pick a category: ")
     print()
     while True:
         if ll.find(self.category) is None:
             self.category = input(
                 "There is no such category. Please pick again: ")
             print()
         else:
             word_ll = SingleLinkedList()
             for i in self.list_of_categories[self.category]:
                 word_ll.insert_last(i)
             self.word = word_ll.pick_random()
             self.list_of_players[
                 self.username]["categories_picked"].append(
                     self.category.lower())
             self.list_of_players[self.username]["favorite_category"] = max(
                 set(self.list_of_players[self.username]
                     ["categories_picked"]),
                 key=self.list_of_players[
                     self.username]["categories_picked"].count)
             break