Write a Python method sort () to sort a LinkedList object in descending order of the...
Fantastic news! We've Found the answer you've been seeking!
Question:
Transcribed Image Text:
Write a Python method sort () to sort a LinkedList object in descending order of the attribute_value. The code for the LinkedList class is shown below. Restriction: You must use the algorithm described in the link. Your solution must NOT use a Python list to sort the list. Given a LinkedList object 11ist, the execution of the code llist.sort() print (llist) should cause the sorted list to be printed out. The code for the LinkedList class is as follows: class Node: definit__(self, value): self._value = value self._next = None #getter for the value attribute def value (self): return self._value # getter for the next attribute def next (self): return self._next def_str_(self): return str(self._value) + class LinkedList: definit_(self): self._head None # add a node to the head of the list. def add(self, node): node. next = self._head self._head node # remove a node from the head of the list and return the node def remove(self): assert self._head != None _node= self._head self._head_node._next _node. next = None return _node. 1. Examples 2. #insert node2 after nodel def insert (self, nodel, node2): assert nodel != None node2. next = nodel. next nodel._next = node2 3. def _str_(self): string 'List[' curr node = self. head while curr node != None: Code: string += ']' return string Code: = 11 = LinkedList () 11.add (Node (1)) 11.add (Node (3)) 11.add (Node (2)) 11.sort() print (11) Result: (this is the string returned by the List[ 3; 2; 1; ] Result: Code: string + str (curr_node) curr_node curr_node.next() 11 = LinkedList() 11.sort() print (11) = List[ ] Result: 11 = 11 = 11.add (Node (1)) 11.add (Node (1)) 11.add(Node (1)) 11.sort() print (11) LinkedList() LinkedList() List[ 1; 1; 1; ] str () method for the LinkedList class) CSc 120: Sorting Linked Lists We will use an intuitively simple algorithm to sort linked lists. The essential idea is the following. Given a linked list to_be_sorted to sort, the algorithm repeatedly moves nodes from the original list to_be_sorted to a new list sorted, maintaining the invariant that sorted is always kept in sorted order (i.e., for the purposes of this assignment, in descending order by by the value attribute in the short problem and the _count attribute in the long problem). Data structures The algorithm has a linked list, sorted, which contains all of the nodes that have been sorted so far. Initially, sorted is empty (i.e., sorted._head has the value None). Each iteration of the algorithm (step 2 below) adds a node to this linked list. The algorithm maintains the invariant that this list is always kept in sorted order. Algorithm The algorithm repeatedly performs the following steps: 1. Remove a node, call it curr_element, from the head of to_be_sorted. 2. Iterate down the list sorted to find the position where curr_element should be inserted such that, after curr_element has been inserted, sorted remains in sorted order. 3. Insert curr_element at that position in sorted. This results in one more element being placed in sorted order in the sorted list. The iteration stops when all elements have been moved from to_be_sorted to sorted. At that point, to_be_sorted will have the value None and sorted will have all of the nodes in sorted order. The algorithm then copies the list sorted to the head of to_be_sorted. The key step in the algorithm above is step 2. The logic for this step is as follows. Here, we follow the requirement for this assignment that the list should be sorted in descending order. We say that an element A is "smaller than" an element B if A's count is less than B's count. a. If sorted is empty: add curr_element to the head of sorted. b. Otherwise, if the first element of sorted is smaller than curr_element: add curr_element at the head of sorted (So curr_element becomes the new first element). c. Otherwise, iterate down sorted to find an element E satisfying the following: i. E ≥ curr_element; and ii. either E._next < curr_element, or E._next is None. (The simplest way I can think of to do this uses two loops one after another: first, iterate down sorted to find the first node whose count is smaller than curr_element, call this node E1; second, iterate down sorted again to find the node E just before E1.) Insert curr_element immediately after E. Write a Python method sort () to sort a LinkedList object in descending order of the attribute_value. The code for the LinkedList class is shown below. Restriction: You must use the algorithm described in the link. Your solution must NOT use a Python list to sort the list. Given a LinkedList object 11ist, the execution of the code llist.sort() print (llist) should cause the sorted list to be printed out. The code for the LinkedList class is as follows: class Node: definit__(self, value): self._value = value self._next = None #getter for the value attribute def value (self): return self._value # getter for the next attribute def next (self): return self._next def_str_(self): return str(self._value) + class LinkedList: definit_(self): self._head None # add a node to the head of the list. def add(self, node): node. next = self._head self._head node # remove a node from the head of the list and return the node def remove(self): assert self._head != None _node= self._head self._head_node._next _node. next = None return _node. 1. Examples 2. #insert node2 after nodel def insert (self, nodel, node2): assert nodel != None node2. next = nodel. next nodel._next = node2 3. def _str_(self): string 'List[' curr node = self. head while curr node != None: Code: string += ']' return string Code: = 11 = LinkedList () 11.add (Node (1)) 11.add (Node (3)) 11.add (Node (2)) 11.sort() print (11) Result: (this is the string returned by the List[ 3; 2; 1; ] Result: Code: string + str (curr_node) curr_node curr_node.next() 11 = LinkedList() 11.sort() print (11) = List[ ] Result: 11 = 11 = 11.add (Node (1)) 11.add (Node (1)) 11.add(Node (1)) 11.sort() print (11) LinkedList() LinkedList() List[ 1; 1; 1; ] str () method for the LinkedList class) CSc 120: Sorting Linked Lists We will use an intuitively simple algorithm to sort linked lists. The essential idea is the following. Given a linked list to_be_sorted to sort, the algorithm repeatedly moves nodes from the original list to_be_sorted to a new list sorted, maintaining the invariant that sorted is always kept in sorted order (i.e., for the purposes of this assignment, in descending order by by the value attribute in the short problem and the _count attribute in the long problem). Data structures The algorithm has a linked list, sorted, which contains all of the nodes that have been sorted so far. Initially, sorted is empty (i.e., sorted._head has the value None). Each iteration of the algorithm (step 2 below) adds a node to this linked list. The algorithm maintains the invariant that this list is always kept in sorted order. Algorithm The algorithm repeatedly performs the following steps: 1. Remove a node, call it curr_element, from the head of to_be_sorted. 2. Iterate down the list sorted to find the position where curr_element should be inserted such that, after curr_element has been inserted, sorted remains in sorted order. 3. Insert curr_element at that position in sorted. This results in one more element being placed in sorted order in the sorted list. The iteration stops when all elements have been moved from to_be_sorted to sorted. At that point, to_be_sorted will have the value None and sorted will have all of the nodes in sorted order. The algorithm then copies the list sorted to the head of to_be_sorted. The key step in the algorithm above is step 2. The logic for this step is as follows. Here, we follow the requirement for this assignment that the list should be sorted in descending order. We say that an element A is "smaller than" an element B if A's count is less than B's count. a. If sorted is empty: add curr_element to the head of sorted. b. Otherwise, if the first element of sorted is smaller than curr_element: add curr_element at the head of sorted (So curr_element becomes the new first element). c. Otherwise, iterate down sorted to find an element E satisfying the following: i. E ≥ curr_element; and ii. either E._next < curr_element, or E._next is None. (The simplest way I can think of to do this uses two loops one after another: first, iterate down sorted to find the first node whose count is smaller than curr_element, call this node E1; second, iterate down sorted again to find the node E just before E1.) Insert curr_element immediately after E.
Expert Answer:
Answer rating: 100% (QA)
heres a table simulating 10 spins of a roulette wheel where you bet one dol... View the full answer
Related Book For
Income Tax Fundamentals 2013
ISBN: 9781285586618
31st Edition
Authors: Gerald E. Whittenburg, Martha Altus Buller, Steven L Gill
Posted Date:
Students also viewed these programming questions
-
The network topology in Figure Q2 is given the network address 200.20.20.0/24. 200.20.20.0/24 Net K LAN D 50 hosts WAN 1 RTD WAN 3 K WAN 2 RTC RTA RTB LAN C LAN A 120 hosts 10 hosts LAN B 12 hosts
-
ConAir (CA) commercial airlines company requires you experience in database design and have approached you to assist in the design of their new airline database system. They urgently need to have...
-
Planning is one of the most important management functions in any business. A front office managers first step in planning should involve determine the departments goals. Planning also includes...
-
Starting one month from now, you need to withdraw $210 per month from your bank account to help cover the costs of your university education. You will continue the monthly withdrawals for the next...
-
How many neutrons are there in the hundredth generation if the fission process starts with No = 1000 neutrons and takes place in a medium with multiplication constant k = 1.05?
-
Cove s Cakes is a local bakery. Price and cost information follows: Price per cake $ 1 3 . 8 1 Variable cost per cake Ingredients 2 . 1 6 Direct labor 1 . 1 0 Overhead ( box , etc. ) 0 . 1 9 Fixed...
-
In Section 2.3, 20 patients for Example 2.5 were randomly selected from a population of 25,000 . a. Explain why the probability of choosing a random sample of 20 from 25,000 is...
-
A company preparing for a Chapter 7 liquidation has the following liabilities: Note payable A of $90,000 secured by land having a book value of $50,000 and a fair value of $70,000. Note payable B...
-
Expected return - D 0 = $3.00, P 0 = $45, g = 2.0% Required Return - r rf = 2%, r m = = 10%, b= 0.9 With that background in mind, address the following questions. a) Is this stock in equilibrium?...
-
7.32. An asteroid is at a distance of 2 106 km from Earth and is moving with a speed of 10 km/s. With- out gravitational pull, the asteroid would miss Earth by a perpendicular distance of 25,000 km...
-
Budget sheet for Pete and Sara Smith Monthly Living Expenses Monthly Fixed Expenses Food/Grocery Bill $320.00 Rent/Mortgage Payment Car Payment $528.64 $219.45 Household Expenses Other Installments...
-
Explain in terms of integers and divisors the effect of the following Euclidlike function: public static boolean gcdlike(int p, int q) { if (q == 0) return (p == 1); return gcdlike(q, p % q); }
-
Give the sequence of integers printed by a call to ex233(6): public static void ex233 (int n) { } if (n
-
Prove by induction that the minimum possible number of moves needed to solve the towers of Hanoi satisfies the same recurrence as the number of moves used by our recursive solution.
-
Write a recursive function that takes an integer \(n\) as its argument and returns \(\ln (n !)\).
-
Criticize the following recursive function: pub7ic static String ex235(int \(n\) ) \{String \(s=\operatorname{ex235(n-3)}+n+\operatorname{ex235(n-2)}+n\); if \((n
-
Question 12 Which is subject to VAT? O Distribution of ordinary assets to stockholders by a corporation. O Personal consumption of capital assets. Donation of capital assets O Transfer of ordinary...
-
Suppose that you could invest in the following projects but have only $30,000 to invest. How would you make your decision and which projects would you invest in? Project Cost $ 8,000 11,000 9,000...
-
John Fuji (age 37) moved from California to Washington in December 2011. He lives at 468 Cameo Street, Yakima, WA 98901. John's Social Security number is 571-78-5974 and he is single. His earnings...
-
David and Darlene Jasper have one child, Sam, who is 6 years old. The Jaspers reside at 4639 Honeysuckle Lane, Los Angeles, CA 90248. David's Social Security number is 577-11-3311, Darlene's is...
-
Ken paid the following amounts for interest during 2012: Qualified interest on home mortgage...........................................$4,700 Auto loan...
-
That financial ratios are most valuable when viewed in comparison to the organizations historical ratio values and competitors values. Why is this context valuable when examining financial ratio...
-
What are the five forms of financing, and how is each used within sport?
-
For many years, womens professional basketball struggled for consistency in the United States. Since 1978, when the Womens Professional Basketball League (WBL) was formed, leagues have had difficulty...
Study smarter with the SolutionInn App