Ejemplo n.º 1
0
def rev_order_rec(LL1, LL2, carry):
    if (LL1 == None or LL1.head == None) and (LL2 == None or LL2.head == None):
        return LinkedList()
    value = 0
    if LL1 == None or LL1.head == None:
        value = LL2.head.data
    elif LL2 == None or LL2.head == None:
        value = LL1.head.data
    else:
        value = LL1.head.data + LL2.head.data
    value += carry
    tmp = value

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

    if LL1 == None or LL1.head == None:
        res = rev_order_rec(None, LinkedList(LL2.head.next), carry)
    elif LL2 == None or LL2.head == None:
        res = rev_order_rec(LinkedList(LL1.head.next), None, carry)
    else:
        res = rev_order_rec(LinkedList(LL1.head.next),
                            LinkedList(LL2.head.next), carry)

    n = Node(value)
    print("curr value:", n.data)
    if res.head == None and tmp >= 10:
        m = Node(1)
        res.append(m)
    res.append(n)
    return res
Ejemplo n.º 2
0
def has_intersection(list1, list2):
    shorter = LinkedList()
    longer = LinkedList()
    list1_size = list_size(list1)
    list2_size = list_size(list2)
    if list1_size > list2_size:
        longer = list1
        shorter = list2
    else:
        longer = list2
        shorter = list1

    ptr_shorter = shorter._head
    ptr_longer = longer._head

    difference_in_size = abs(list1_size - list2_size)
    for i in range(difference_in_size):
        ptr_longer = ptr_longer.next

    while ptr_longer is not None:
        if ptr_shorter == ptr_longer:
            return True, str(ptr_shorter.data.value)
        ptr_shorter = ptr_shorter.next
        ptr_longer = ptr_longer.next
    return False, None
Ejemplo n.º 3
0
def add(LL1, LL2):

    global carry
    print("carry: ", carry)
    if LL1.head == None and LL2.head == None:
        return LinkedList()

    res = add(LinkedList(LL1.head.next), LinkedList(LL2.head.next))
    value = LL1.head.data + LL2.head.data

    if carry == 0:
        print(LL1.head.data, LL2.head.data)
        value += has_carry(LL1, LL2)
    else:
        value += carry

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

    n = Node(value)
    res.prepend(n)
    return res
Ejemplo n.º 4
0
def main():
    list = LinkedList()
    print("Insert Test: expected out 3, 2, 1")
    list.insert(1)
    list.insert(2)
    list.insert(3)
    list.printList()
    print("Remove Test: expected out 3, 1")
    list.delete(2)
    list.printList()
    print("Remove Duplicates: expected out 3, 2, 1")
    list2 = LinkedList()
    list2.insert(1)
    list2.insert(2)
    list2.insert(3)
    list2.insert(1)
    list2.insert(2)
    list2.insert(3)
    list2.insert(1)
    list2.insert(2)
    list2.insert(3)
    list2.removeDups()
    list2.printList()

    print("Return Kth to last test: expected out 4")
    list3 = LinkedList()
    list3.insert(1)
    list3.insert(2)
    list3.insert(3)
    list3.insert(4)
    list3.insert(5)
    temp1 = list3.returnKthtoLast(3)
    print(temp1)
Ejemplo n.º 5
0
def get_levels(t: Tree) -> [LinkedList]:
    """
    Complexity: O(2^depth) or O(nodes) on space and time
    Doing recursive w DFS would be same time but O(d) space!!!
    >>> t = Tree()
    >>> t.bst_from([1, 2, 3])
    >>> get_levels(t)
    [[2], [1, 3]]
    >>> t.bst_from([1, 2, 3, 4, 5, 6, 7, 8, 9])
    >>> get_levels(t)
    [[5], [3, 8], [2, 4, 7, 9], [1, 6]]
    """

    if not t.root:
        return []
    n = t.root
    n.level = 0
    q = deque([n])
    levels = [LinkedList()]
    while q:
        n = q.popleft()
        if n.left:
            n.left.level = n.level + 1
            q.append(n.left)
        if n.right:
            n.right.level = n.level + 1
            q.append(n.right)

        levels[n.level].append_to_tail(n.data)
        if q and n.level != q[0].level:
            levels.append(LinkedList())
    return levels
Ejemplo n.º 6
0
def rec_intersect(LL1, LL2):
    print(LL1.head.data, LL2.head.data)

    if LL1 == None and LL2 == None:
        return None

    elif LL1 == None:
        res = intersect(LL1, LinkedList(LL2.head.next))

    elif LL2 == None:
        res = intersect(LinkedList(LL1.head.next), LL2)

    else:
        res = intersect(LinkedList(LL1.head.next), LinkedList(LL2.head.next))

    if res != None:
        return res

    if LL1.head == LL2.head:
        return None

    else:
        if LL1.head.next == LL2.head.next and LL1.head.next != None:
            return LL1.head.next

    return None
Ejemplo n.º 7
0
def runTest(fp):
    '''
    :param fp: file pointer to read in values
    :return: number of right and the length of the linked list

    creates linked lists and runs merge sort, then checks for correct result
    '''
    s_list = llist.LinkedList()
    count = AddValues(s_list,fp)
    s_list.head = student.MergeSort(s_list.head)


    a_list = llist.LinkedList()
    fp.seek(0,0)
    AddValues(a_list,fp)
    a_list.head = answer.MergeSort(a_list.head)

    right = check(s_list, a_list)


   # right = 0

   # while s_list.head.next:
   #     if s_list.head <= s_list.head.next:
   #         right +=1
   #     s_list.head = s_list.head.next




    return right, count
Ejemplo n.º 8
0
def index():
    if 'id' not in session:
        session['id'] = str(uuid.uuid1())
        savedLists[session['id']] = LinkedList()
    else:
        if session['id'] not in savedLists:
            savedLists[session['id']] = LinkedList()
    array = {'array': savedLists[session['id']].list()}
    return render_template("index.html",
                           myList=json.loads(savedLists[session['id']].json()),
                           array=array)
Ejemplo n.º 9
0
    def test_len(self):
        print('Test: len on an empty list')
        linked_list = LinkedList(None)
        assert_equal(len(linked_list), 0)

        print('Test: len general case')
        linked_list = LinkedList([10])
        linked_list.add_to_front('a')
        linked_list.add_to_front('bc')
        assert_equal(len(linked_list), 3)

        print('Success: test_len\n')
Ejemplo n.º 10
0
    def test_ConvertToBase10(self):
        test1 = ll.LinkedList([1, 1, 1, 0, 0])
        self.assertEqual(28, ll.convertToBase10(test1))

        test2 = ll.LinkedList([0, 1, 0])
        self.assertEqual(2, ll.convertToBase10(test2))

        test3 = ll.LinkedList([0])
        self.assertEqual(0, ll.convertToBase10(test3))

        test4 = ll.LinkedList([1])
        self.assertEqual(1, ll.convertToBase10(test4))
Ejemplo n.º 11
0
 def add(self,node_of_word):
     if self.list_of_words[self.hash_function(node_of_word.data)] == '':
         self.list_of_words[self.hash_function(node_of_word.data)] = LinkedList()
         node = self.list_of_words[self.hash_function(node_of_word.data)].add(node_of_word.data)
         node.refrence = LinkedList()
         node.hash_num = self.hash_function(node_of_word.data)
         node.refrence.SuperAdd(node_of_word,root_tree=self,node_ref=node)
     else:
         element = self.list_of_words[self.hash_function(node_of_word.data)].search(node_of_word.data)
         if element:
             element.refrence.SuperAdd(node_of_word,root_tree=self,node_ref=element)
         else:
             node = self.list_of_words[self.hash_function(node_of_word.data)].add(node_of_word.data)
             node.refrence = LinkedList()
             node.hash_num = self.hash_function(node_of_word.data)
             node.refrence.SuperAdd(node_of_word,root_tree=self,node_ref=node)
Ejemplo n.º 12
0
def input_without_N(lst):
    x = lst
    v = Validation()
    y = LinkedList()
    first_iter = True
    while x.length() != y.length():
        if not first_iter:
            print("Both length must be equal!")
        print("Input Y(double ENTER to stop): ")
        while True:  # while user will not input "ENTER", he enters a list
            i = input()
            if i == "":
                break
            if not v.positive_check(i):
                print(i, "was skipped because it's not a number!")
            else:
                dot = False
                for z in i:
                    if z == ".":
                        dot = True
                        break
                if dot:
                    y.append(float(i))
                else:
                    y.append(int(i))
        first_iter = False
    result = create_z(
        x, y,
        x.length())  #call a function to create list "z" according to task
    return result
Ejemplo n.º 13
0
def main():
    list = LinkedList()
    utility = Utility()
    file_name = "Ordered.txt"
    file = open(file_name, "r")

    if file.mode == 'r':
        contents = file.read()
    print(contents)

    temp_array = contents.split(" ")
    my_array = []

    # for removing spaces
    for x in range(0, len(temp_array)):
        if (temp_array[x] != ""):
            my_array.append(temp_array[x])

    print("please enter a number")
    new_word = utility.input_str_data()

    for x in range(0, len(my_array)):
        list.add(my_array[x])
    flag = list.search(new_word)
    if (flag == False):
        list.add_order(new_word)
    else:
        list.delete(new_word)
    list.display()
    node = list.head
    utility.print_list(file_name, node)

    file.close()
Ejemplo n.º 14
0
    def testRandomArrayEquals(self):
        lst = np.random.randint(sys.maxsize, size=10)
        linked_lst = ll.LinkedList(fromArray=lst)
        ops = ['addFirst', 'addLast', 'removeFirst', 'removeLast']

        for i in range(50):
            op = ops[np.random.randint(len(ops))]
            e = np.random.randint(sys.maxsize)

            if op == 'addFirst':
                lst = [e] + lst
            elif op == 'addLast':
                lst += [e]
            elif op == 'removeFirst':
                lst = lst[1:]
            else:
                lst = lst[:-1]

            if 'add' not in op:
                exec('linked_lst.' + op + '()')
                continue

            exec('linked_lst.' + op + '(' + str(e) + ')')

        print(str(lst))
        print(str(linked_lst.toArray()))
        self.assertEqual(lst, linked_lst.toArray())
Ejemplo n.º 15
0
def pal(lis):
    size = lis.size()
    new_list = LinkedList()
    cur = lis.head
    for i in range(size // 2 - 1):
        cur = cur.get_next()
    tem = cur
    cur = cur.get_next()
    tem.set_next(None)
    if size % 2 == 1:
        cur = cur.get_next()
    new_list.head = cur
    cur = cur.get_next()
    while (cur != None):
        new_list.insert(cur.get_data())
        cur = cur.get_next()

    par1 = lis.head
    par2 = new_list.head
    while (par1 != None):
        if (par1.get_data() != par2.get_data()):
            return False
        par1 = par1.get_next()
        par2 = par2.get_next()
    return True
Ejemplo n.º 16
0
    def testDeleteAtIndex(self):
        test = LinkedList.LinkedList()
        node1 = (1, 'jlw')
        node2 = (2, 'jjj')
        node3 = (3, 'www')
        test.append(node1[0], node1[1])
        test.deleteAtIndex(100)
        self.assertEqual(test.head.score, node1[0])
        self.assertEqual(test.head.name, node1[1])
        self.assertEqual(test.tail.score, node1[0])
        self.assertEqual(test.tail.name, node1[1])
        test.append(node2[0], node2[1])
        test.append(node3[0], node3[1])

        test.deleteAtIndex(0)
        self.assertEqual(test.head.score, node2[0])
        self.assertEqual(test.head.name, node2[1])
        self.assertEqual(test.tail.score, node3[0])
        self.assertEqual(test.tail.name, node3[1])

        test.deleteAtIndex(1)
        self.assertEqual(test.head.score, node2[0])
        self.assertEqual(test.head.name, node2[1])
        self.assertEqual(test.tail.score, node2[0])
        self.assertEqual(test.tail.name, node2[1])
Ejemplo n.º 17
0
def sumlists(num1, num2):
    carry = 0
    n1 = num1.head
    n2 = num2.head
    result = LinkedList()
    while n1.next != None and n2.next != None:
        result.addnode((carry + n1.data + n2.data) % 10)
        carry = (carry + n1.data + n2.data) / 10
        n1 = n1.next
        n2 = n2.next

    result.addnode((carry + n1.data + n2.data) % 10)
    carry = (carry + n1.data + n2.data) / 10

    if n1.next == None:
        n = n2.next
    else:
        n = n1.next

    while n != None:
        result.addnode((carry + n.data) % 10)
        carry = (carry + n.data) / 10
        n = n.next

    if carry != 0:
        result.addnode(carry)

    return result
Ejemplo n.º 18
0
def test_search():
    _print_test_start("test_search")
    passed = True
    l = LinkedList()
    for i in range(50):
        l.insertBack(i)
    # Test #1

    # actual = l.search(25)
    temp = l.search(25)
    actual = [temp[0].value, temp[1]]
    expected = [25, 25]

    if actual != expected:
        print("Test #1")
        print("Actual is not equal to expected: " + " actual = " +
              str(actual) + ", expected = " + str(expected))
        passed = False

    # Test #2
    temp = l.search(100)
    actual = [temp[0], temp[1]]
    expected = [None, -1]

    if actual != expected:
        print("Test #2")
        print("Actual is not equal to expected: actual = " + str(actual) +
              ", expected = " + str(expected))
        passed = False

    _print_test_status(passed, "test_search")
Ejemplo n.º 19
0
    def testInsertInOrder(self):
        test = LinkedList.LinkedList()
        node1 = (1, 'jlw')
        node2 = (2, 'jjj')
        node3 = (3, 'www')

        test.insertInOrder(node2[0], node2[1])
        self.assertEqual(test.head.score, node2[0])
        self.assertEqual(test.head.name, node2[1])
        self.assertEqual(test.tail.score, node2[0])
        self.assertEqual(test.tail.name, node2[1])

        test.insertInOrder(node1[0], node1[1])
        self.assertEqual(test.head.score, node2[0])
        self.assertEqual(test.head.name, node2[1])
        self.assertEqual(test.tail.score, node1[0])
        self.assertEqual(test.tail.name, node1[1])

        test.insertInOrder(node3[0], node3[1])
        self.assertEqual(test.head.score, node3[0])
        self.assertEqual(test.head.name, node3[1])
        output = test.indexOf(node2[0], node2[1])
        self.assertEqual(output, 1)
        self.assertEqual(test.tail.score, node1[0])
        self.assertEqual(test.tail.name, node1[1])
Ejemplo n.º 20
0
    def __init__(self):
        rospy.init_node('FakeBumper', anonymous=False)
        rospy.on_shutdown(self.shutdown)

        self.odom_msg_header = Header()
        self.odom_list = LinkedList.LinkedList(TIME_WINDOW)
        self.odom_filter_counter = 0
        self.bumper_msg = BumperEvent()
        self.bumper_msg.bumper = 1
        self.bumper_msg.state = 1

        try:
            self.odom_sub = rospy.Subscriber("odom", Odometry,
                                             self.odom_callback)
        except Exception as e:
            rospy.loginfo("Couldn't Subscribe to /odom")
            print(e)

        try:
            self.bump_pub = rospy.Publisher("mobile_base/events/bumper",
                                            BumperEvent,
                                            queue_size=10)
        except Exception as e:
            print(e)

        while not rospy.is_shutdown():
            try:
                rospy.spin()
            except Exception as e:
                rospy.loginfo("Error in FakeBumper")
                print(e)
Ejemplo n.º 21
0
def test_reverse_up_to():
    _print_test_start("test_reverse_up_to")
    passed = True

    # Test #1
    l = _create_increasing_ordered_list(20)
    l.printList()
    actual = l.reverseUpTo(10)
    print("Original ll: ")
    l.printList()
    expected = _create_decreasing_ordered_list(10)
    actual_ll = LinkedList(actual)
    actual_ll.printList()

    actualNode = actual_ll.head
    expectedNode = expected.head

    while expectedNode != None and expectedNode.next != None:
        if expectedNode.value != actualNode.value:
            passed = False
            _print_test_result(1, expectedNode.value, actualNode.value)

        expectedNode = expectedNode.next
        actualNode = actualNode.next

    _print_test_status(passed, "test_reverse_up_to")
Ejemplo n.º 22
0
def main():
    array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
    #array = np.array([1, 2, 3]);
    linked_list = lp.LinkedList()
    for i in range(len(array)):
        linked_list.AddElements(array[i])
    linked_list.FirstLastPattern()
Ejemplo n.º 23
0
 def test_to_array_long(self):
     linked_list = LinkedList.LinkedList()
     arr = []
     for x in range(0, 10000):
         arr.append(9999 - x)
         linked_list.add_front(x)
     self.assertEqual(arr, linked_list.to_array())
Ejemplo n.º 24
0
 def test_mystery_length_3(self):
     linked_list = LinkedList.LinkedList()
     linked_list.add_front(3)
     linked_list.add_front(2)
     linked_list.add_front(1)
     linked_list.mystery_operation()
     self.assertEqual([3, 2, 1], linked_list.to_array())
Ejemplo n.º 25
0
def prims_ll(graph, s):

    n = range(len(graph))
    vertex_set = []  # visited vertices
    heap = LinkedList()  # heap
    heap.add(Node(s, 0))  # add s with weight 0

    distances = [100] * len(graph)  # distance array

    distances[s] = 0  # set start distance to 0

    # while there are still elements in the heap
    while not heap.is_empty():
        v = heap.delete_min()  # get index of the minimum weighted edge
        vertex_set.append(v)  # mark as visited

        # loop through neighbors updating distances if not visited
        for w in n:
            if (distances[w] > graph[v][w]) and (w not in vertex_set):
                distances[w] = graph[v][w]
                in_heap = heap.search(w)
                if in_heap is not None:
                    in_heap.weight = distances[w]
                else:
                    heap.add(Node(w, distances[w]))

    # return the sum of the distance array (MST edges)
    return sum(distances)
Ejemplo n.º 26
0
def partitionList(linkedlist, target):
    if linkedlist is None:
        return None

    smallStart = smallEnd = largeStart = largeEnd = None
    node = linkedlist.head

    while node:
        if node.data < target:
            if not smallStart:
                smallStart = smallEnd = node
            else:
                smallEnd.next = node
                smallEnd = smallEnd.next
        else:
            if not largeStart:
                largeStart = largeEnd = node
            else:
                largeEnd.next = node
                largeEnd = largeEnd.next
        node = node.next

    if smallEnd is None:
        return linkedlist(largeStart)

    smallEnd.next = largeStart

    return LinkedList(smallStart)
Ejemplo n.º 27
0
 def test_linked_list_del_single(self):
     test_llist = ll.LinkedList()
     test_llist.add_in_tail(ll.Node(99))
     item_del = 99
     test_llist.delete(item_del, all=False)
     self.assertEqual(None, test_llist.head)
     self.assertEqual(None, test_llist.tail)
Ejemplo n.º 28
0
 def as_LinkedList(encodedDict):
     if '__LinkedList__' in encodedDict:
         newList = LinkedList.LinkedList()
         valueArray = encodedDict['values']
         for element in valueArray:
             newList.insertInOrder(element[0],element[1])
         return newList
Ejemplo n.º 29
0
def sample_linkedlist_function():
    linked_list = LinkedList()
    init_linkedlist(linked_list)
    print(linked_list.to_list_forward())
    print(linked_list._head.data.value)
    print(type(linked_list._head))
    return recursive_linkedlist_to_list_forward(linked_list._head)
Ejemplo n.º 30
0
 def test_linked_list_insert(self):
     temp_list = [12, 23, 34, 45, 56, 67, 78, 89]
     test_llist = ll.LinkedList()
     for i in temp_list:
         test_llist.add_in_tail(ll.Node(i))
     # insert into begin:
     item_insert = 10
     test_llist.insert(None, ll.Node(item_insert))
     temp_list.insert(0, item_insert)
     self.compare_list_llist(temp_list, test_llist)
     self.assertEqual(temp_list[0], test_llist.head.value)
     # insert into middle:
     item_insert = 39
     test_llist.insert(test_llist.find(34), ll.Node(item_insert))
     temp_list.insert(4, item_insert)
     self.compare_list_llist(temp_list, test_llist)
     # insert into end:
     item_insert = 99
     test_llist.insert(test_llist.find(89), ll.Node(item_insert))
     temp_list.append(item_insert)
     self.compare_list_llist(temp_list, test_llist)
     self.assertEqual(temp_list[-1], test_llist.tail.value)
     # insert into empty linked list:
     test_llist.clean()
     test_llist.insert(test_llist.find(89), ll.Node(item_insert))
     self.assertEqual(item_insert, test_llist.head.value)
     self.assertEqual(item_insert, test_llist.tail.value)