Question

PYTHON 3 node Node ADT Question.

Question 3 (18 points): Purpose: To practice working with node chains created using the Node ADT to implement slightly harder

This function should not create any nodes, and should retum a tuple of references to the two halves of the chain The tricky p

print (chain1 after: to_string (chain 1)) print (chain2 after:, to_string (chain2 )) print (merged_chain after:\n, to.str

Question 3 (18 points): Purpose: To practice working with node chains created using the Node ADT to implement slightly harder functionality Degree of Difficulty: Moderate to Tricky In this question you'll implement merge sort for node chains! Recall, merge sort is a divide-and-conquer technique that uses recursion to sort a given sequence (in this case a node chain). A overview of the algorithm is given below. Algorithm mergeSort (NC) Borts node chain NC using merge sort a node chain of data items NC sorted node chain of NC # return nev if NC contains 0 or 1 data items NC return divide = first half of NC NC1 NC2 second half of NC recursively sort NC1 and NC2 mergeSort (NC1) mergeSort (NC2) NC1 NC2 conquer !!! NC merge (NC1, NC2) return NC In order to implement merge sort, you are going to write three functions that will make your job easier. On Moodle, you can find a starter file call ed a5q3. py, with all the functions and doc-strings in place, your job is to write the bodies of the functions. You will also find a test script named a5q3_testing . py. It has a bunch of test cases pre-witten for you. Read it carefully! Use to string) from Q1 to help you test and debug your functions. (a) (5 points) Implement the function aplit_chain (). The interface for the function is: def split chain ( node_chain) : Purpose Splits the given node chain in half, returning the second half. the extra node is part of If the given chain has an odd length, the second half of the chain. Pre-conditiona: param node_chain: a node -chain, possibly empty Post-conditions: the original node chain is cut in half! Return : return: A tuple (nc1, nc2) where nc1 and nc2 are node- chains each containing about half of the nodes in node- chain
This function should not create any nodes, and should retum a tuple of references to the two halves of the chain The tricky part of this is only to remember to put a None at the right place. to terminate the original node-chain about half way through A demonstration of the application of the function is as follows chain5 node . create (3 , node. create (1, node. create (4, node. create (1, node. create (5) )) )) print ('chain5 Before: to.string (chain5 )) a, b split. chain ( ch ain 5 ) print ('chain5 After: to_string (a) print ('Second half: tostring (b )) The output from the demonstration is as follows: chain5 Before: [ 3 I]t 1 1--> 4 3 -> 1/ 4 1 | 5I 1 I s/ chain5 After: Second half Notice how the second half of the list is a little bit larger Hint You may use count_chain() from A5Q2, and integer division (b) (5 points) Implement the function merge (). The interface for the function is def merge (nc1, nc2): Purpose: a single Combine the tvo sorted node-chains ncl and nc2 into Borted node- chain. Pre-conditions: : param nc1: a node-chain, possi bly empty. containing values sorted in ascending order. param nc2: a node-ch ain, possi bly empty containing values sorted in ascending order Post-condition: None Return: : return: a sorted node chain (nc) that contains the values from nc1 and nc2. If both node-chains are empty an empty node - chain will be returned This one is tricky. as there are a few special cases A demonstration of the application of the function is as follows no de. create (1. node. create (1 node. create (9))) no de. create (2, node. create (7, node. create ( 15))) print ('chain 1 before : ', to_atring (chain1 ) print ('chain2 before:. to.string (chain2)) merged.chainmerge (chaini, chain 2) chaini chain2
print ('chain1 after: to_string (chain 1)) print ('chain2 after:, to_string (chain2 )) print ('merged_chain after:\n', to.string (mer ged_ chain)) The output from the demonstration is as follows: chaini before: 1 > 1 1 9 chain2 before: [ 2 -] 7 -- 15 I 1 chainl after: 1 -] -> 1 -] >[ 9 /1 chain2 after: 2 --> 7 I--> 15I1 merged_chain after: (11 1-1 2 -] - > 7 1->[91-1- 15 (c) (3 points) Imple ment the function mer ge_sort (). The interface for the function is def merge sort (node_ chain) : www Purpose: Sorts the given node chain in ascending order using the merge sort algorithm . Pre-conditions: param node_chain: a no de - chain, possibly empty, containing only numbers Post condition: the node - cha in will be sorted in ascending order Return return: the node - chain sorted in ascend ing order Ex: 45->1->21->5. Becomes 1->5->21->45 This one might be a little difficult, since it uses recursion. A demonstration of the application of the function is as follows chain node. create (10 node. create (9 , node.create (12, node. create (7. node. create (11 node. create (8) )) )) ) print ('chain before :\n, to_string ( chain) sorted_node_chain mer ge _s or t ( chain) print ('merge_sort results :\n ' , to_string ( sorted_node_chain)) The output from the demonstration is as follows: chain before: [10 I- >[91-->[ 12 I-]- > 7 -->[ 11|-]--> 8 I merge_sort results 71.-1 8 -1 9] > 10 --> 11 1 12 I d) (5 points) Before you submit your work, review it, and edit it for programm ing style. Make sure your variables are named well, and that you have appropriate (not excessive) internal documentation (do not change the doc-string which we have given you.
0 0
Add a comment Improve this question Transcribed image text
Answer #1
# CMPT 145: Assignment 5 Question 3

import node as node
import a5q2 as a5q2


def split_chain(node_chain):
        """
        Purpose:
                Splits the given node chain in half, returning the second half.
                If the given chain has an odd length, the extra node is part of
                the second half of the chain.
        Pre-conditions:
                :param node_chain: a node-chain, possibly empty
        Post-conditions:
                the original node chain is cut in half!
        Return:
                :return: A tuple (nc1, nc2) where nc1 and nc2 are node-chains
                 each containing about half of the nodes in node-chain
        """
        size = a5q2.count_chain(node_chain)
        
        # if the chain is empty
        if size == 0:
                return (None, None)
                
        # if there is just one node, then second list contain more elements
        if size == 1:
                return (None, node_chain)
        
        ###
        # Algorithm: We will run 2 walkers parallely, but in each iteration
        # first walker moves 1 step, while the second walker moves 2 steps.
        # When second walker reach to the end of the list, then we will stop
        # this process. At that time, first walker will be pointing to the 
        # node after which we should split the list
        ####
        # in case chain has odd number of nodes, we will put a blank node
        # at the start, so that we get to see the list length as even number
        # and then we will do our regular algorithm as stated above
        # So if, List is: 1 -> 2 -> 3 -> 4 -> 5-> 6 -> 7 -> 8
        # walker1 start from node 1, and walker 2 starts from node 2
        # when walker2 reaches to node 8, then walker1 will be at node 4.
        # we will stop at this point and break complete chain after
        # node 4.
        start = node_chain
        if size % 2 != 0:
                start = node.create(None, node_chain)
        
        walker1 = start
        walker2 = node.get_next(start)
        
        # keep moving till walker2 reaches last node
        while node.get_next(walker2) is not None:
                # move walker1 1 step at a time
                walker1 = node.get_next(walker1)
                
                # walker2 will walk 2 step at a time
                walker2 = node.get_next(node.get_next(walker2))
        
        # now break the list after walker1
        second_list = node.get_next(walker1)
        node.set_next(walker1, None)
                
        return (node_chain, second_list)

Answered first part.. Please ask separate questions for each part.. also, give the copyable code.. because we can not write everything after seeing the image.. i tried to help you to the max extent, which i could do in the given time limit. Thanks!

Add a comment
Know the answer?
Add Answer to:
PYTHON 3 node Node ADT Question. Question 3 (18 points): Purpose: To practice working with node chains created using...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • The language is python thr language is python I Expert Q&A Done The language is python....

    The language is python thr language is python I Expert Q&A Done The language is python. 10. The following is the algorithm for Merge Sort, one of the best sorting algorithms and one hat is recursive. Wine the merge sort function and draw the stack and heap dagrams for execution on the list |5, 8,9,1,4. 10 Algorithm: Mergesort Ingut an unsorted list b 1. If there is only one iten L. It is sorted, return L 2, Split L Sn...

  • Finish each function python 3 LList.py class node(object): """ A version of the Node class with...

    Finish each function python 3 LList.py class node(object): """ A version of the Node class with public attributes. This makes the use of node objects a bit more convenient for implementing LList class.    Since there are no setters and getters, we use the attributes directly.    This is safe because the node class is defined in this module. No one else will use this version of the class. ''' def __init__(self, data, next=None): """ Create a new node for...

  • Language C++ (Please include a short description & Screenshot of output) Implement a Priority...

    Language C++ (Please include a short description & Screenshot of output) Implement a Priority queue using a SORTED list. Use Quick sort after adding a new node. Example of quick sort below. Adopt to your program the code below. #include <iostream> void quickSort(int a[ ], int first, int last); int pivot(int a[], int first, int last); void swap(int& a, int& b); void swapNoTemp(int& a, int& b); void print(int array[], const int& N); using namespace std; int main() { int test[]...

  • Interfaces 1. What is inside an interface definition? What does a class do to an interface...

    Interfaces 1. What is inside an interface definition? What does a class do to an interface and what keyword is involved? How does a class do this to an interface (what should we find in the class)? Can an interface have a generic parameter? How do you instantiate an interface as an object? What methods can’t you use on an interface type? Abstract Data Types 2. What does an ADT define? Does an ADT specify programming language and/or data structures...

  • Must be in Python 3 exercise_2.py # Define the Student class class Student():    # Ini...

    Must be in Python 3 exercise_2.py # Define the Student class class Student():    # Initialize the object properties def __init__(self, id, name, mark): # TODO # Print the object as an string def __str__(self): return ' - {}, {}, {}'.format(self.id, self.name, self.mark) # Check if the mark of the input student is greater than the student object # The output is either True or False def is_greater_than(self, another_student): # TODO # Sort the student_list # The output is the sorted...

  • Trying to figure out what needs to be in the headers.h file. I have written the...

    Trying to figure out what needs to be in the headers.h file. I have written the print function. Qualities in header file main() needs insertionSort() and mergeSortWrapper() Both insertionSort() and mergeSortWrapper() need print(). Please copy-and-paste the following files (0 Points): insertionSort.c /*--------------------------------------------------------------------------* *---- ----* *---- insertionSort.c ----* *---- ----* *---- This file defines a function that implements insertion ----* *---- sort on a linked-list of integers. ----* *---- ----* *---- ---- ---- ---- ---- ---- ---- ---- ---- ----* *----...

  • Objective: GUI Layout manager Download one of the sample GUI layout program. Use any GUI layout...

    Objective: GUI Layout manager Download one of the sample GUI layout program. Use any GUI layout to add buttons to start each sort and display the System.nanoTime in common TextArea panel. The question is a bit confusing so i will try to simplify it. Using the GUI ( I made a unclick able one so you have to make it clickable), allow a user to sort the text file based on what they click on. example: if i click merge...

  • C programming language Purpose The purpose of this assignment is to help you to practice working...

    C programming language Purpose The purpose of this assignment is to help you to practice working with functions, arrays, and design simple algorithms Learning Outcomes ● Develop skills with multidimensional arrays ● Learn how to traverse multidimensional arrays ● Passing arrays to functions ● Develop algorithm design skills (e.g. recursion) Problem Overview Problem Overview Tic-Tac-Toe (also known as noughts and crosses or Xs and Os) is a paper-and-pencil game for two players, X and O, who take turns marking the...

  • Using Merge Sort: (In Java) (Please screenshot or copy your output file in the answer) In...

    Using Merge Sort: (In Java) (Please screenshot or copy your output file in the answer) In this project, we combine the concepts of Recursion and Merge Sorting. Please note that the focus of this project is on Merging and don't forget the following constraint: Programming Steps: 1) Create a class called Art that implements Comparable interface. 2) Read part of the file and use Merge Sort to sort the array of Art and then write them to a file. 3)...

  • Given list.h, main.cpp, i need to write list.cpp. having a lot of problems. please help. list.h:...

    Given list.h, main.cpp, i need to write list.cpp. having a lot of problems. please help. list.h: ////////////////////////////////////////////////////////////////////////// #ifndef LIST_H #define LIST_H ////////////////////////////////////////////////////////////////////////// namespace CS170 { struct node { int value; node *next; }; class list { public: // Constructor for list. Creates an empty list list(); /* Destructor for list. Empty the list and release the allocated memory */ ~list(); // Prints out the values contained in the list void print_list() const; // Returns the current size of the list...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT