예제 #1
0
def main():
    n = -1
    while n < 0:
        try:
            n = int(input('Введите n: '))
            if n < 0:
                raise ValueError
        except ValueError:
            print('Нужно вводить целое положительное число!')
    l = LL()
    result = 0

    for i in range(1, n + 1):
        f = None
        while f is None:
            try:
                f = float(input(f'Введите x{i}: '))
            except ValueError:
                print('Нужно вводить число!')
        l.add(f)
    ch = l.first
    while ch.next is not None:
        result += sqrt(10 + ch.value**2)
        ch = ch.next

    print(f'Резульат: {result}')
예제 #2
0
def main():
    n = -1
    while n < 0:
        try:
            n = int(input('Введите n: '))
            if n < 0:
                raise ValueError
        except ValueError:
            print('Нужно вводить целое положительное число!')
    if n < 2:
        print('Недостаточно значений для расчёта.')
        return
    l = LL()
    result = 1

    for i in range(1, n + 1):
        f = None
        while f is None:
            try:
                f = float(input(f'Введите x{i}: '))
            except ValueError:
                print('Нужно вводить число!')
        l.add(f)
    ch = l.first.next
    ct = l.last
    while ch.next is not None:
        result *= ch.prev.value + ch.value + 2 * ct.value
        ch = ch.next
        ct = ct.prev

    print(f'Резульат: {result}')
예제 #3
0
def test_partition():
    a = [3, 5, 8, 5, 10, 2, 1]

    li = LinkedList()
    li.build_from_collection(a)
    li.print_list()
    partition(li, 5)
    li.print_list()
예제 #4
0
def list_of_depths(root):
    """
    This solution is a modification of breadth first search.
    """
    q = MyQueue()
    depth_lists = []

    seen = []
    q.add((root, 0))
    seen.append(root)

    while not q.is_empty():
        q.print_queue()
        node, depth = q.remove().data
        
        try:
            depth_lists[depth].insert(node)
        except IndexError:
            depth_lists.append(LinkedList())
            depth_lists[depth].insert(node)
        
        adjacent_nodes = [node.left, node.right]
        for child in adjacent_nodes:
            if child is not None and child not in seen:
                seen.append(child)
                q.add((child, depth + 1))

    return depth_lists
예제 #5
0
def test_weave():
    a = ['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4']
    print(a)

    li = LinkedList()
    li.build_from_collection(a)
    li.print_list()
    weave(li)
    li.print_list()
예제 #6
0
def test_delete_middle_node():
    a = ['a', 'b', 'c', 'd', 'e', 'f']

    li = LinkedList()
    li.build_from_collection(a)
    li.print_list()
    middle_node = kth_to_last(li, 3)
    delete_middle_node(middle_node)
    li.print_list()
class Stack:
    def __init__(self):
        self.items = LinkedList()

    def getItems(self):
        return self.items

    def size(self):
        return self.items.size()

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def isEmpty(self):
        return self.items.isEmpty()
예제 #8
0
def main():
    n = -1
    while n < 0:
        try:
            n = int(input('Введите n: '))
            if n < 0:
                raise ValueError
        except ValueError:
            print('Нужно вводить целое положительное число!')

    l = LinkedList()
    fac_sum = 0
    cur_fac = 1
    for i in range(1, n + 1):
        cur_fac *= i
        fac_sum += 1 / cur_fac
        l.add(i * fac_sum)

    for i in l.list():
        print('%.2f' % i)
예제 #9
0
def sum_lists(a, b):
    a_num = 0
    a_mult = 1
    a_curr = a.head
    while a_curr is not None:
        a_num += a_curr.data * a_mult
        a_curr = a_curr._next
        a_mult *= 10

    b_num = 0
    b_mult = 1
    b_curr = b.head
    while b_curr is not None:
        b_num += b_curr.data * b_mult
        b_curr = b_curr._next
        b_mult *= 10

    output_num = a_num + b_num
    print(output_num)
    output_mult = 1
    while output_num // (output_mult * 10) > 0:
        output_mult *= 10

    output = LinkedList()
    if output_num == 0:
        output.insert(0)
        return output

    while output_num != 0:
        digit = int(output_num // output_mult)
        output.insert(digit)
        output_num = output_num - (digit * output_mult)
        output_mult /= 10

    return output
예제 #10
0
def test_palindrome():
    a = ['aabbaa', 'catac', 'ababab']
    for x in a:
        print(x)
        li = LinkedList()
        li.build_from_collection(x)
        li.print_list()
        print('Is a palindrome:', is_a_palindrome(li))
예제 #11
0
def test_loop_detection():
    li = LinkedList()
    li.insert('C')
    li.insert('E')
    li.insert('D')

    c_node = li.head._next._next
    c_node._next = li.head
    li.head = c_node
    #Oops now we have a loop.

    li.insert('B')
    li.insert('A')

    loop_node = loop_detection(li)
    if loop_node is not None:
        print('Has loop at node %s.' % loop_node.data)
    else:
        print('Contains no loop.')
예제 #12
0
class ListStack(Stack):
    """Creates a class of stack using the linked list.

    Attributes:
        list: the linked list of the data.
    """

    def __init__(self):
        """Initializes the class.
        """
        super(ListStack, self).__init__()
        self.__list = LinkedList()

    def purge(self):
        """Cleans the stack.
        """
        self.__list.purge()
        self._count = 0

    def push(self, obj):
        """Pushes an object into the stack.
        """
        self.__list.append(obj)
        self._count += 1

    def pop(self):
        """Pop an object up the stack.
        """
        if self._count == 0: raise IndexError
        result = self.__list.head.datum
        self.__list.remove(result)
        self._count -= 1
        return result

    def top(self):
        """Get the top object of a stack.
        """
        if self._count == 0: raise IndexError
        return self.__list.head.datum
예제 #13
0
class ListQueue(Queue):
    """Creates a class of queue using the list.

    Attributes:
        list: the list of the data.
    """

    def __init__(self):
        """Initializes the class.
        """
        super(ListQueue, self).__init__()
        self._list = LinkedList()

    def purge(self):
        """Cleans the queue.
        """
        self._list.purge()
        self._count = 0

    def head(self):
        """Gets the head element.
        """
        if self._count == 0: raise IndexError
        return self._list.head.datum

    def enqueue(self, obj):
        """Enqueue.
        """
        self._list.append(obj)
        self._count += 1

    def dequeue(self):
        """Dequeue.
        """
        result = self.head()
        self._list.remove(result)
        self._count -= 1
        return result
예제 #14
0
def is_a_palindrome(li):
    """
    This solution relies on the fact that the linked list
    implementation inserts nodes at the head of the list.
    It first scans the list to count the number of elements.
    Then we pop off the first half of the list while inserting
    into a new list. This will reverse the elements in a stack-like
    manner. If the original list contains an odd number
    of elements we discard the middle element. Finally, we
    check to see if the two lists we're left with match.
    This solution destroyes the original list, we could
    easily add a step to copy it into a new list first to avoid
    destroying it.
    """
    n = 0
    curr = li.head
    while curr is not None:
        n += 1
        curr = curr._next

    li2 = LinkedList()
    k = n // 2
    while k > 0:
        popped_node = li.get_first()
        li2.insert(popped_node.data)
        k -= 1

    if n % 2 == 1:
        #Remove the middle element and discard it.
        _ = li.get_first()

    while not li2.is_empty():
        li2_el = li2.get_first()
        li_el = li.get_first()
        if li2_el.data != li_el.data:
            return False

    return True
예제 #15
0
 def insert(self, val):
     index = self._hash(val)
     if self.table[index] is None:
         _list = LinkedList()
         self.table[index] = _list
     self.table[index].insert(val)
예제 #16
0
def bst_sequences(root):
    """
    This is a Python implementation of Gayle's solution from CtCI.
    I struggled with this problem so I just want to move past it.
    """
    result = LinkedList()

    if root is None:
        result.insert(LinkedList())
        return result

    prefix = LinkedList()
    prefix.add(root.data)

    #Recurse on left and right subtrees
    left_sequences = bst_sequences(root.left)
    right_sequences = bst_sequences(root.right)

    #Weave together each list from the left and right sides.
    while not left_sequences.is_empty():
        left = left_sequences.get_first().data
        while not right_sequences.is_empty():
            right = right_sequences.get_first().data
            weaved = LinkedList()
            weave_lists(left, right, weaved, prefix)
            result.add_all(weaved)

    return result
 def __init__(self):
     self.items = LinkedList()
예제 #18
0
def test_sum_lists(num_a, num_b):
    a = LinkedList()
    a_str = str(num_a)
    for digit in a_str:
        a.insert(int(digit))

    b = LinkedList()
    b_str = str(num_b)
    for digit in b_str:
        b.insert(int(digit))

    a.print_list()
    b.print_list()

    result = sum_lists(a, b)
    result.print_list()
예제 #19
0
 def __init__(self):
     """Initializes the class.
     """
     super(ListQueue, self).__init__()
     self._list = LinkedList()
예제 #20
0
 def setUp(self):
     self.linked_list = LinkedList()
예제 #21
0
class TestLinkedList(unittest.TestCase):
    linked_list = None

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

    def test_init(self):
        self.assertEqual(self.linked_list.head, None,
                         "Initial HEAD should be None")
        self.assertEqual(len(self.linked_list), 0,
                         "Initial length should be zero")

    def test_len(self):
        self.assertEqual(len(self.linked_list), 0,
                         "Newly initiated list's length should be zero")
        self.linked_list.insert(1)
        self.assertEqual(len(self.linked_list), 1, "List length should be 1")

    def test_list(self):
        node1 = self.linked_list.Node(1, None)
        node2 = self.linked_list.Node(2, node1)
        node3 = self.linked_list.Node(3, node2)
        self.linked_list.insert(1)
        self.linked_list.insert(2)
        self.linked_list.insert(3)
        self.assertEqual([node3, node2, node1], list(self.linked_list))

    def test_str(self):
        self.linked_list.insert(1)
        self.linked_list.insert(2)
        self.linked_list.insert(3)
        self.assertEqual(str(self.linked_list), '[3, 2, 1]',
                         "List should be printed as [3, 2, 1]")
        self.linked_list.delete(2)
        self.assertEqual(str(self.linked_list), '[3, 1]',
                         "List should be printed as [3, 1]")
        self.linked_list.delete(3)
        self.assertEqual(str(self.linked_list), '[1]',
                         "List should be printed as [1]")
        self.linked_list.delete(1)
        self.assertEqual(str(self.linked_list), '[]',
                         "List should be printed as []")

    def test_insert(self):
        self.assertEqual(
            self.linked_list.insert(1), self.linked_list.Node(1, None),
            "Inserting 1 into list should return node with value=1")
        self.assertEqual(list(self.linked_list), [self.linked_list.Node(1)],
                         "Inserting 1 into empty list should give [1]")
        self.linked_list.insert(3, 1)
        self.assertEqual(self.linked_list.head.next,
                         self.linked_list.Node(3, None),
                         "Inserting 3 into pos=1 of [1] should give [1,3]")
        self.linked_list.insert(2, 1)
        self.assertEqual(
            self.linked_list.head.next.value,
            self.linked_list.Node(2, None).value,
            "Inserting 2 into pos=1 of [1,3] should give [1,2,3]")

    def test_contains(self):
        self.linked_list.insert(1)
        self.linked_list.insert(2)
        self.linked_list.insert(3)
        self.assertEqual(
            1 in self.linked_list, True,
            "After inserting 1 into the list, we should be able to find it there"
        )
        self.assertEqual(
            4 in self.linked_list, False,
            "After inserting 1 into the list, we should be able to find it there"
        )
        #print(self.linked_list)

    def test_search(self):
        self.linked_list.insert(1)
        self.linked_list.insert(2)
        self.linked_list.insert(3)
        self.assertEqual(
            self.linked_list.search(2).value,
            self.linked_list.Node(2, None).value,
            "Searching for 2 in [3,2,1] should return node with value=2")
        self.assertEqual(self.linked_list.search(4), None,
                         "Searching for 4 in [3,2,1] should return None")

    def test_delete(self):
        self.linked_list.insert(1)
        self.linked_list.insert(2)
        self.linked_list.insert(3)
        self.assertEqual(
            self.linked_list.delete(2).value,
            self.linked_list.Node(2, None).value,
            "Deleting 2 from [3,2,1] should return the node with value 2")
        self.linked_list.delete(3)
        self.assertEqual(
            self.linked_list.head, self.linked_list.Node(1, None),
            "Deleting 2 and 3 from [3,2,1] should leave the list as [1]")