CP164 Final: The Array

73 views2 pages
13 Jun 2018
School
Course
Professor
The Array-Based Stack Implementation
Pushing Items Onto an Array-Based Stack
def push(self, value):
"""
-------------------------------------------------------
Pushes a copy of value onto the top of the stack.
Use: stack.push(value)
-------------------------------------------------------
Parameters:
value - value to be added to stack (?)
Returns:
None
-------------------------------------------------------
"""
self._values.append(deepcopy(value))
return
push simply uses the Python list method append to add value to the end of the _values list.
Note, however, the use of the deepcopy method. copy is a Python library, and deepcopy is
one of its methods. deepcopy returns a complete copy of whatever is passed to it. (Using
the copy library requires an import copy statement at the top of the module.) It is
important to understand what happens if we don't use it. The following code shows the
creation of a student object:
student = Student("013412060", "Brown", "David", ...)
This object is then pushed onto a stack:
stack.push(student)
Unlock document

This preview shows half of the first page of the document.
Unlock all 2 pages and 3 million more documents.

Already have an account? Log in

Document Summary

Pushing items onto an array-based stack def push(self, value): Pushes a copy of value onto the top of the stack. Parameters: value - value to be added to stack (?) None self. _values. append(deepcopy(value)) return push simply uses the python list method append to add value to the end of the _values list. It is important to understand what happens if we don"t use it. The following code shows the creation of a student object: student = student(013412060, brown, david, ) This object is then pushed onto a stack: stack. push(student) Changing the contents of student then changes the contents of the student object stored in the stack, because both student and the stack object point to the same location in memory. Using deepcopy makes a copy of the student object in the stack, so that student and the object in the stack point to different memory locations, as in this diagram:

Get access

Grade+20% off
$8 USD/m$10 USD/m
Billed $96 USD annually
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
40 Verified Answers

Related Documents