Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

PYTHON. My assignment is to modify a given program such that it can do several new functions.? Code is below class Student: # class (static)

PYTHON. My assignment is to modify a given program such that it can do several new functions.? Code is below

class Student: # class ("static") members and intended constants DEFAULT_NAME = "zz-error" DEFAULT_POINTS = 0 MAX_POINTS = 30 # initializer ("constructor") method ------------------- def __init__(self, last = DEFAULT_NAME, first = DEFAULT_NAME, points = DEFAULT_POINTS): # instance attributes if (not self.set_last_name(last)): self.last_name = Student.DEFAULT_NAME if (not self.set_first_name(first)): self.first_name = Student.DEFAULT_NAME if (not self.set_points(points)): self.total_points = Student.DEFAULT_POINTS # mutator ("set") methods ------------------------------- def set_last_name(self, last): if not self.valid_string(last): return False # else self.last_name = last return True def set_first_name(self, first): if not self.valid_string(first): return False # else self.first_name = first return True def set_points(self, points): if not self.valid_points(points): return False # else self.total_points = points return True # accessor ("get") methods ------------------------------- def get_last_name(self): return self.last_name def get_first_name(self): return self.first_name def get_total_points(self): return self.total_points # output method ---------------------------------------- def display(self, client_intro_str = "--- STUDENT DATA ---"): print( client_intro_str + str(self) ) # standard python stringizer ------------------------ def __str__(self): return self.to_string() # instance helpers ------------------------------- def to_string(self, optional_title = " ---------- "): ret_str = ( (optional_title + " name: {}, {}" + " total points: {}."). format(self.last_name , self.first_name, self.total_points) ) return ret_str # static/class methods ----------------------------------- @staticmethod def valid_string(test_str): if (len(test_str) > 0) and test_str[0].isalpha(): return True; return False @classmethod def valid_points(cls, test_points): if 0 <= test_points <= cls.MAX_POINTS: return False else: return True @staticmethod def compare_strings_ignore_case(first_string, second_string): """ returns -1 if first < second, lexicographically, +1 if first > second, and 0 if same this particular version based on last name only (case insensitive) """ fst_upper = first_string.upper() scnd_upper = second_string.upper() if fst_upper < scnd_upper: return -1 # else if if fst_upper > scnd_upper: return 1 # else return 0 # beginning of class StudentArrayUtilities definition --------------- class StudentArrayUtilities: @classmethod def print_array(cls, stud_array, optional_title = "--- The Students -----------: "): print( cls.to_string(stud_array, optional_title) ) @classmethod def array_sort(cls, data, array_size): for k in range(array_size): if not cls.float_largest_to_top(data, array_size - k): return # class stringizers ---------------------------------- @staticmethod def to_string(stud_array, optional_title = "--- The Students -----------: "): ret_val = optional_title + " " for student in stud_array: ret_val = ret_val + str(student) + " " return ret_val @staticmethod def float_largest_to_top(data, array_size): changed = False # notice we stop at array_size - 2 because of expr. k + 1 in loop for k in range(array_size - 1): if Student.compare_strings_ignore_case( data[k].get_last_name(), data[k + 1].get_last_name() ) > 0: data[k], data[k+1] = data[k + 1], data[k] changed = True return changed # client -------------------------------------------- # instantiate some students, one with and illegal name ... my_students = \ [ Student("smith","fred", 95), Student("bauer","jack",123), Student("jacobs","carrie", 195), Student("renquist","abe",148), Student("3ackson","trevor", 108), Student("perry","fred",225), Student("lewis","frank", 44), Student("stollings","pamela",452) ] array_size = len(my_students) StudentArrayUtilities.print_array(my_students, "Before: ") StudentArrayUtilities.array_sort(my_students, array_size) StudentArrayUtilities.print_array(my_students, "After: ") 

ASSIGNMENT:

Understand the Application

Sort Flexibility (Student class)

In week 8, we saw an example of a Student class that provided a staticcompare_strings_ignore_case()method. We needed to define such a method because our sort algorithm(which was in theStudentArrayUtilities (SAU) class) had to have a basis for comparing two Student objects, the foundation of SAUs sorting algorithm. Since a Student is a compound data type, not a float or a string, there was no pre-defined less-than, <, operation available, so we created our owncompare_strings_ignore_case(), which was based on the spelling of the last name. You can review those notes to see its definition.

We want to make the sort more flexible in this assignment. Sometimes we want to sort on last name, as we did in the lectures, but other times we may choose to sort on the first name (useful for informal communication) or total points (useful for analyzing statistics). We could go into thecompare_strings_ignore_case() method and change its definition to work on first name. Or, we could rename it to compare_two_numbers() and base it on total points (or for that possibility just changeSAU'sfloat_largest_to_top() so that compare the points itself < or <=, no method call needed. But, such "solutions" only replace the inflexibility of last name with the inflexibility of some other criteria.

So here's the plan: we will provide class Student with a new class method set_sort_key() which will establish a new sort criteria. A client will invoke it whenever it wants to switch to a new basis for comparison. The client will pass an argument to set_sort_key() telling it which one of the threeStudentattributes it wants future sort algorithms to use. The Student class will keep itscompare_strings_ignore_case() static method, but add a new class method calledcompare_two_students() (which can use the older method as a helper). This name doesn't commit tostring vs. number, plus it gives the SAU class a unified method to invoke,Student.compare_two_students(), inside its float_largest_to_top(). The current sort key will informcompare_two_students() how to make the comparison.

No Output (SAU class)

Another change we'll make affects the output modality. Rather than displaying the array directly in the SAU class, we want to make the class "U.I. neutral." So we will replace SAU's print_array() method with ato_string() method and let the client choose how to use that. In our example main program we will be sending the string array to the console.

Median (SAU class)

We'll add one more class method to SAU: double get_median_destructive( cls, array, array_size). This method will return the median of the total_toints values in an array. Look up median. It is defined as the "middle-value" and is easily computed, but you first have to sort the array in order to find it. Fortunately, you already have the sort method.

Client

Our client will declare three Student arrays to make sure our median works: one array that has an odd number of students (15), one that has an even number of students (16) and one that has a single student.

We'll test the sort_key and sort algorithm only on the even numbered array, and then we will test our median computation on all three arrays.

The Program Spec

These changes should not be complicated as long as you read carefully and follow directions. New and modified members/methods are all very short, so stay focused and apply what you learned back in week 8.

Additions to the Student Class

We will add the following static members to the class in the modules.

static int consts:

SORT_BY_FIRST = 88

SORT_BY_LAST = 98

SORT_BY_POINTS = 108

These are the three sort keys that will be used by the client and the class, alike, to keep track of, or set, the sort key. If the client wants to establish a new sort key, it will pass one of these tokens (sayStudent.SORT_BY_FIRST) to the setter described next. I have intentionally made the literal values non-contiguous so you would not rely on their particular values in your logic. You should be able to change the values without breaking your program (but you don't have to change them; use the three values above).

static int:

sort_key - this will always have one of the three constants above as its value. Make sure it initially hasSORT_BY_LAST in it, but after the client changes it, it could be any of the above constants.

You should supply the following simple static methods:

def set_sort_key(cls, key): -- a mutator for the member sortKey.

def get_sort_key(cls): -- an accessor for sortKey.

A new class comparison method:

def compare_two_students(cls, first_stud, second_stud):-- This method has to look at the sort_key and compare the two Students based on the currently activesort_key. It will return a number as follows:

If sort_key is SORT_BY_FIRST it will use the two students' first members to make the comparison. It will do this by passing those two values to compare_strings_ignore_case(), and "passing up" the returned value directly to the client.

If sort_key is SORT_BY_LAST it will use the two students' last members to make the comparison. It will do this by passing those two values to compare_strings_ignore_case(), and "passing up" the returned value directly to the client.

If sort_key is SORT_BY_POINTS it will use the two students' total_points members to make the comparison. It will do this by subtracting the second student's points from the first student's points and returning that number.

Notice that whatever value the current Student.sort_key has, Student.compare_two_students() returns a value value that's negative if first_stud "comes before" second_stud, positive if first_stud "comesafter"second_stud and 0 if they are the same -- interpreted through the current value of sort_key. (It doesn't matter what the the exact value returned besides its being +, - or 0.)

Change to the StudentArrayUtilities Class

Replace print_array() with to_string(). Generate the same kind of string, but instead of sending it to the screen, return it to the client.

Adjust float_largest_to_top() to call compare_two_students() rather thancompare_strings_ignore_case(). Make adjustments required by this change.

Add a class method get_median_destructive(cls, array, array_size): - This computes and returns the median of the total scores of all the students in the array The details are simple, but you have to take them each carefully:

Dispose of the case of a one-element array. A one-element array returns its one and onlyStudent'stotal_points. (This case can actually be skipped if you handle the next cases correctly, but it doesn't hurt to do it separately, here.)

Even-numbered arrays >= 2 elements: find the two middle elements and return their average of their total points.

Odd-numbered arrays >= 3 elements: return the total points of the exact middle element.

Special Note: This method has to do the following. It must sort the array according to total_points in order to get the medians, and that's easy since we already have the sort method. Then it has to find the middle-student's score (e.g., if the array is size 21, the middle element is the score in array[10], after the sort). But, before doing the sort, it also has to change the sort_key of the Student class to SORT_BY_POINTS. One detail, that you may not have thought of, is that, at the very start of the method, it needs to save the client's sort key. Then, before returning, restore the client's sort key. This method doesn't know what that sort key might be, but there is an accessor get_sort_key() that will answer that question.

This method has the word "Destructive" in its name to remind the client that it may (and usually will) modify the order of the array, since it is going to sort the array by total points in the process of computing the median. However, it will not destroy or modify the client's sort_key when the method returns to client (see previous bullet).

If the user passes in a bad arraySize (< 1) return a 0.

The Main Program

Our client will declare three Student arrays: using direct initialization, as in the modules: no user input. The array sizes should be 15, 16 and 1. The second array can be the same as the first with one extraStudenttagged onto the end. Each array should be initialized in no particular order: unsorted in all fields.

Using the largest, even numbered, array:

display the array immediately before calling a sort method,

sort the array using the default (initial) sort key and display,

change the sort key to first name, sort and display,

change the sort key to total score, sort and display,

set_sort_key() to first name, call the get_median_destructive() method and display the median score. and finally

call get_sort_key() to make sure that the get_median_destructive() method preserved the client's sort_key value of first name that was just set prior to the get_median_destructive() call.

Using each of the two other arrays:

get the median of each array and display. No other testing needed in this part.

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Systems Design Implementation And Management

Authors: Peter Robb,Carlos Coronel

5th Edition

061906269X, 9780619062699

More Books

Students also viewed these Databases questions