def test_init(self):
     data = 'ABC'
     node = Node(data)
     # Initializer should add instance properties
     assert node.data is data
     assert node.next is None
     assert node.prev is None
 def append(self, item, number_of_columns=0):
     """Insert the given item at the tail of this linked list.
     TODO: Running time: O(1) Why and under what conditions?"""
     # TODO: Create new node to hold given item
     node = Node(item)
     if type(item) is list:
         node.data = LinkedList(node.data)
         # TODO: Append node after tail, if it exists
         if self.tail is None:
             self.head = node
             self.tail = node
         else:
             self.tail.next = node
             self.tail = node
     else:
         # start from first column
         columns = 0
         for node in self:
             if columns == number_of_columns:
                 linkedlist = node.data
                 linkedlist.append(item)
                 break
             else:
                 # count columns
                 columns += 1
예제 #3
0
 def test_remove_not_exisiting(self):
     head = Node(5)
     linked = LinkedList(head)
     linked.append(9)
     node = linked.remove(7)
     self.assertEqual(node, None, 'should be None')
     self.assertEqual(str(linked), '5->9', 'should be 5->9')
예제 #4
0
 def push(self, value):
     if self.has_space():
         item = Node(value)
         item.set_next_node(self.top_item)
         self.top_item = item
         self.size += 1
     else:
         print("No more room on stack")
def sum_lists(num1, num2):
    if num1 is None or num2 is None:
        return num1 or num2

    carry = 0

    # We use a dummy node as the head of the sum list.
    # We can also set the head as None.
    # But this needs more if-else checks as we move head through the list using head.next as None has no next parameter.
    head = new_head = Node(0)

    while num1 is not None or num2 is not None:
        # caution: don't forget to check for None
        if num1 is None:
            num1_value = 0
        else:
            num1_value = num1.value

        if num2 is None:
            num2_value = 0
        else:
            num2_value = num2.value

        num_sum = carry + num1_value + num2_value

        if num_sum >= 10:
            carry = 1
            num_sum = num_sum % 10
        else:
            carry = 0

        current = Node(num_sum)
        head.next = current

        head = head.next

        # caution: don't forget to check for None
        if num1 is not None:
            num1 = num1.next
        if num2 is not None:
            num2 = num2.next

    if carry > 0:
        current.next = Node(carry)

    return new_head.next
    def test_sum_lists(self):
        head1 = Node(5)
        head1.next = Node(8)
        head1.next.next = Node(7)

        head2 = Node(3)
        head2.next = Node(8)

        result_sum = sum_lists(head1, head2)
        self.assertEqual(result_sum.value, 8)
        self.assertEqual(result_sum.next.value, 6)
        self.assertEqual(result_sum.next.next.value, 8)

        head3 = None
        head4 = None
        result_sum2 = sum_lists(head3, head4)
        self.assertEqual(result_sum2, None)
예제 #7
0
파일: chapter04.py 프로젝트: justinvyu/ctci
 def add_node_at_depth(t, depth=0):
     if t is BinaryTree.empty:
         return
     if depth not in depths:
         depths[depth] = Node.empty
     depths[depth] = Node(t.label, depths[depth])
     add_node_at_depth(t.left, depth + 1)
     add_node_at_depth(t.right, depth + 1)
예제 #8
0
 def test_search_not_existing(self):
     head = Node(5)
     linked = LinkedList(head)
     linked.append(7)
     linked.append(11)
     node = linked.search(15)
     self.assertEqual(node, None, 'should be None')
     self.assertEqual(str(linked), '5->7->11', 'should be 5->7->11')
def test_length():
    print("------TEST LENGTH------")
    s_list = LinkedList()
    s_list.add_in_tail(Node(12))
    s_list.add_in_tail(Node(55))
    s_list.add_in_tail(Node(128))
    s_list.add_in_tail(Node(55))
    s_list.add_in_tail(Node(130))
    s_list.print_all_nodes()
    try:
        print(s_list.len())
        if s_list.len() == 5:
            print("test length success")
        else:
            print("test lenght failed")
    except Exception:
        print("error test lenght")
예제 #10
0
def main():
    ll = LinkedList()
    data = [char for char in 'FOLLOW UP']
    for char in data[::-1]:
        node = Node(char)
        ll.insert(node)
    remove_duplicates(ll.head)
    print "%s" % ll == "%s" % ['F', 'O', 'L', 'W', ' ', 'U', 'P']
예제 #11
0
 def setUp(self):
     self.head1 = Node(1)
     self.head2 = Node(1)
     self.head2.next = Node(2)
     self.head2.next.next = Node(5)
     self.head2.next.next.next = Node(2)
     self.head2.next.next.next.next = Node(1)
     self.head3 = Node(1)
     self.head3.next = Node(2)
     self.head4 = None
    def test_partition(self):
        head = Node(5)
        head.next = Node(3)
        head.next.next = Node(1)
        head.next.next.next = Node(2)
        head.next.next.next.next = Node(4)

        head2 = None

        result_head = partition(head, 3)
        self.assertEqual(result_head.value, 1)
        self.assertEqual(result_head.next.value, 2)
        self.assertEqual(result_head.next.next.value, 5)
        self.assertEqual(result_head.next.next.next.value, 3)
        self.assertEqual(result_head.next.next.next.next.value, 4)

        result_head2 = partition(head2, 3)
        self.assertEqual(result_head2, None)
예제 #13
0
 def test_pop_two(self):
     head = Node(5)
     linked = LinkedList(head)
     linked.append(7)
     node = linked.pop()
     self.assertEqual(node.val, 7, 'should be 7')
     node = linked.pop()
     self.assertEqual(node.val, 5, 'should be 5')
     self.assertEqual(str(linked), '', 'should be empty')
예제 #14
0
def main():
    ll = LinkedList()
    data = [char for char in '123456789']
    for char in data[::-1]:
        node = Node(char)
        ll.insert(node)
    print ll
    print ll.size()
    print kth_tolast(ll.head, 5).val == '123456789'[-5]
def set_up(l1, l2):

    intersecting_node = Node(5)
    intersecting_node.next = Node(6)
    intersecting_node.next.next = Node(7)

    l1tail = l1.head
    l2tail = l2.head

    while l1tail.next is not None:
        l1tail = l1tail.next

    l1tail.next = intersecting_node

    while l2tail.next is not None:
        l2tail = l2tail.next

    l2tail.next = intersecting_node
 def test_linking_nodes(self):
     node1 = Node('A')
     node2 = Node('B')
     node3 = Node('C')
     # Link nodes together
     node1.next = node2
     node1.prev = None
     node2.next = node3
     node2.prev = node1
     node3.prev = node2
     node3.next = None
     # Node links should be transitive
     assert node1.prev is None
     assert node1.next is node2  # One link
     assert node2.prev is node1
     assert node1.next.next is node3  # Two links
     assert node3.prev is node2
     assert node3.next is None
    def setUp(self):
        self.head1 = Node(1)
        self.head1.next = Node(3)
        self.head1.next.next = Node(6)
        self.head1.next.next.next = Node(5)

        self.loop_node = Node(3)
        self.head2 = Node(1)
        self.head2.next = self.loop_node
        self.head2.next.next = Node(6)
        self.head2.next.next.next = Node(5)
        self.head2.next.next.next.next = Node(4)
        self.head2.next.next.next.next.next = self.loop_node

        self.head3 = None

        self.head4 = Node(1)
        self.head4.next = None
def create_transactions():
    global local_clock
    global bchain
    global time_table
    while True:
        print(bchain)
        print(colored(f"\n\n(alert) This client ID is {PORT}.", 'cyan'))
        print(
            "What type of transaction do you want to issue?\n\t1. Transfer\n\t2. Balance\n\t3. Send Sync"
        )
        option = int(input())
        if option == 1:
            # update the clock for each transaction
            local_clock[CLIENT_ID] += 1
            print("Enter the Reciever ID: ")
            reciever = int(input())
            print("Enter the amount you wish to send: ")
            amount = float(input())
            print(
                colored(
                    f"(message) You {PORT} are sending {amount} to {reciever}, clock: {local_clock[CLIENT_ID]}",
                    'yellow'))
            if calculateBalance(bchain, INIT_BAL, PORT) >= amount:
                transaction = Node(PORT, reciever, amount,
                                   local_clock[CLIENT_ID])
                bchain.append(transaction)
                print(colored("(response) SUCCESS", 'green'))
            else:
                print(colored("(response) INCORRECT", 'red'))
                local_clock[CLIENT_ID] -= 1
        elif option == 2:
            # this should be simple since there is no need to check or make any request to other clients
            print(colored(f"(message) Checking balance for {PORT}.", 'yellow'))
            balance = calculateBalance(bchain, INIT_BAL, PORT)
            print(colored(f"(response) The balance is: ${balance}.", 'green'))
            for client in CLIENTS:
                balance = calculateBalance(bchain, INIT_BAL, client)
                print(
                    colored(
                        f"(response) The estimated balance for {client} is: ${balance}.",
                        'green'))
        elif option == 3:
            print("Enter the Reciever ID: ")
            reciever = int(input())
            msg = build_msg(reciever)
            send_sync = threading.Thread(name="Send sync message thread",
                                         target=send_to_clients,
                                         args=(msg, reciever))
            send_sync.start()
            send_sync.join()
        else:
            print(colored("Incorrect transaction type.", 'yellow'))
        update_clock(local_clock, CLIENT_ID)
        print(colored(f"(message) Clock: {local_clock}", 'yellow'))
        print(colored(f"(message) Updated TT for {CLIENT_ID}", 'yellow'))
        print(colored(f"(message) TT: {time_table}", 'yellow'))
예제 #19
0
 def insert(self, value):
     node = Node(value)
     node.next = None
     if self.length == 0:
         self.head = self.last = node
     else:
         last = self.last
         last.next = node
         self.last = node
     self.length += 1
예제 #20
0
    def setUp(self):
        """Create a test linked list"""

        myllhead = Node(1)
        myllhead.append(2)
        myllhead.append(2)
        myllhead.append(3)
        myllhead.append(3)

        self.myllhead = myllhead
예제 #21
0
def sum_lists(ll1, ll2, reverse=True):
	if reverse:
		head1 = ll1
		head2 = ll2
		current1 = head1
		current2 = head2
		carry = 0
		prev = None

		while current1 is not None:
			if current2 is not None:
				sm = current1.value + current2.value + carry
				carry, current1.value = sm // 10, sm % 10
				prev = current1
				current1, current2 = current1.next, current2.next

		while current2 is not None:
			prev.next = Node()
			current1 = prev.next
			current1.value = current2.value + carry
			prev = current2
			current2 = current2.next

		if carry != 0:
			prev.next = Node()
			prev.next.value = carry

		return head1

	else:
		ll1_str = ''
		ll2_str = ''

		while ll1 is not None:
			ll1_str += str(ll1.value)
			ll1 = ll1.next
		while ll2 is not None:
			ll2_str += str(ll2.value)
			ll2 = ll2.next

		result_str = str(int(ll1_str) + int(ll2_str))

		return create_linkedlist(result_str)
예제 #22
0
def main1():
    """ open the file and read the file"""

    file = open('file1', 'r')
    lines_of_file = file.readlines()
    for singl in lines_of_file:
        words = singl.lower().split()
        for word in words:
            first = Node(word)
            """Inserting the element into linked list"""
            obj.insert(first)
    print("The word in the linked list--->")
    obj.traverse()
    """Taking input from user the element to be searched"""

    search1 = input(("Enter the word you want to search in the list:"))
    if obj.search(search1):
        """ If search word is found then deleting this word from file
        as well as from linked list"""

        obj.delete_word(search1)
        """Deleting word from file by over writting ."""
        f = open("file1", 'w')
        f.write("")
        f.close()
        length = obj.len()
        f = open('file1', 'a+')
        for i in range(0, length):
            f.write(" " + obj.index(i))
        f.close()
        print("The word you searched is deleted :")
    else:
        """The search element is not found then adding the element into Linkedlist 
        as well as into the file"""

        add_word = Node(search1)
        obj.insert(add_word)
        f = open('file1', 'a+')
        f.write(" " + search1)
        f.close()
        print("The word you search is added to the list:")
    print("After the searching the word your list is updated!!")
    obj.traverse()
예제 #23
0
 def assgin(self, key, value):
     array_index = self.compress(self.hash(key))
     # self.array[array_index] = [key, value]
     list_at_index = self.array[array_index]
     payload = Node([key, value])
     for item in list_at_index:
         if item[0] == key:
             item[1] = value
             return
     list_at_index.insert(payload)
def test_clean():
    print("------TEST CLEAN------")
    s_list = LinkedList()
    s_list.add_in_tail(Node(12))
    s_list.add_in_tail(Node(55))
    s_list.add_in_tail(Node(128))
    s_list.add_in_tail(Node(55))
    s_list.add_in_tail(Node(130))
    s_list.print_all_nodes()
    print("---------------")
    try:
        s_list.clean()
        s_list.print_all_nodes()
        if s_list.head == None and s_list.tail == None:
            print("test for clean success")
        else:
            print("test for clean failed")
    except Exception:
        print("error test clean")
예제 #25
0
    def enqueue(self, item):
        """Insert the given item at the back of this queue.
        Running time: O(???) – Why? [TODO]"""
        new_node = Node(item)
        try:
            self.tail.next = new_node
        except AttributeError:  # queue is empty
            self.head = new_node
            self.tail = new_node

        self.tail = new_node
예제 #26
0
def is_anagram_by_comparison(s1, s2):
    # check if len match. for each char in s1, check if matching in s2.
    if len(s1) != len(s2):
        return False

    if len(s2) == 0:
        return True

    # turn s2 into ll for easy removal
    it = iter(s2)
    ll = LinkedList(Node(next(it)))
    for c in it:
        ll.append(Node(c))

    # for each char in string1, remove from string2 if exist
    for c in s1:
        if ll.remove(c) < 0:
            return False

    return True
def contract(ll: LinkedList,head,other):
    #print(f"linkedlist is {ll}")
    
    prevnode=ll.head
    for elem in ll:

        if ll.head.data==head:
            if elem.data==other:
                ll.remove_node(targetnode_data=other)
        elif ll.head.data==other:
            if elem.data==head:
                ll.remove_node(targetnode_data=head)

                ll.remove_node(targetnode_data=other)
                ll.add_first(node=Node(head))
        else:
            if elem.data==other:
                ll.add_after(targetnode=other,newnode=Node(head))
                ll.remove_node(targetnode_data=other)
            prevnode=elem
예제 #28
0
 def push(self, item):
     """Insert the given item on the top of this stack.
     Running time: O(1) because we only have to reassign the head pointer
     which does not depend on the number of items in the list """
     new_node = Node(item)
     self.list.size += 1               # increment size
     if self.list.head is None:        # case where list is empty
         self.list.head = new_node
         return
     new_node.next = self.list.head
     self.list.head = new_node
예제 #29
0
def partation(ll, K):
    """
    Kの大きさで分割して並び替えたものを返す。
    """
    n = ll
    left, right = Node(), Node()
    while True:
        if n.data < K:
            left.appendToTail(n.data)
        else:
            right.appendToTail(n.data)
        if n.next == None:
            break
        n = n.next

    # これだと宣言の関係上一番始めがNoneになっているのでとりのぞいてから連結する
    right = right.get_Nth_node(1)
    left = left.get_Nth_node(1)
    left.appendNodeToTail(right)
    return left
def test_insert():
    print("------TEST INSERT------")
    s_list = LinkedList()
    n1 = Node(12)
    n2 = Node(55)
    n3 = Node(128)
    n4 = Node(55)
    n5 = Node(130)
    n1.next = n2
    n2.next = n3
    n3.next = n4
    n4.next = n5
    s_list.add_in_tail(n1)
    s_list.add_in_tail(n2)
    s_list.add_in_tail(n3)
    s_list.add_in_tail(n4)
    s_list.add_in_tail(n5)
    s_list.print_all_nodes()
    print("---------------")
    try:
        nnew = Node(1001)
        s_list.insert(n2, nnew)
        s_list.print_all_nodes()
        print("head", s_list.head, s_list.head.value)
        print("tail", s_list.tail, s_list.tail.value)
        node = s_list.head
        count = 0
        while node != None:
            if node.value == 55 and node.next.value == 1001:
                count = count + 1
            if node.value == 1001 and node.next.value == 128:
                count = count + 1
            node = node.next
        if count == 2:
            print("test insert success")
        else:
            print("test insert failed")
    except Exception:
        print("error test insert")

    print("------empty linked list------")
    s_list_empty = LinkedList()
    s_list_empty.print_all_nodes()
    nnew_empty = Node(10001)
    try:
        s_list_empty.insert(n2, nnew_empty)
        s_list_empty.print_all_nodes()
        print(s_list_empty.head, s_list_empty.head.value)
        print(s_list_empty.tail, s_list_empty.tail.value)
        if s_list_empty.head.value == 10001 and s_list_empty.tail.value == 10001 \
                and s_list_empty.head == s_list_empty.tail:
            print("test insert in empty list success")
        else:
            print("test insert in empty list failed")
    except Exception:
        print("error test insert")