python programming Add the methods grow and shrink tothe Array class. These methods should use the strategiesdiscussed
Question:
python programming
Add the methods grow and shrink tothe Array class. These methods should use the strategiesdiscussed in this chapter to increase or decrease the length of thelist contained in the array. Each call to .grow() shoulddouble the physical size. Make sure that the physical size of thearray does not shrink below the user-specified capacity and thatthe array’s cells use the fill value when the array’s size isincreased. A main() has been provided to test theimplementation of grow and shrink.
"""
File: arrays.py
Project 4.3
Adds methods grow and shrink to increase or decrease thecapacity
of the array if necessary.
An Array is a restricted list whose clients can use
only [], len, iter, and str.
To instantiate, use
= array(, )
The fill value is None by default.
"""
class Array(object):
"""Represents an array."""
def __init__(self, capacity, fillValue =None):
"""Capacity is the static size of thearray.
fillValue is placed at eachposition."""
self.items = list()
self.logicalSize = 0
# Track the capacity and fill value foradjustments later
self.capacity = capacity
self.fillValue = fillValue
for count in range(capacity):
self.items.append(fillValue)
def __len__(self):
"""-> The capacity of thearray."""
return len(self.items)
def __str__(self):
"""-> The string representation ofthe array."""
return str(self.items)
def __iter__(self):
"""Supports traversal with a forloop."""
return iter(self.items)
def __getitem__(self, index):
"""Subscript operator for access atindex.
Precondition: 0 <= index if index < 0 or index >=self.size():
raise IndexError("Arrayindex out of bounds")
return self.items[index]
def __setitem__(self, index, newItem):
"""Subscript operator for replacementat index.
Precondition: 0 <= index if index < 0 or index >=self.size():
raise IndexError("Arrayindex out of bounds")
self.items[index] = newItem
def size(self):
"""-> The number of items in thearray."""
return self.logicalSize
def grow(self):
"""Increases the physical size of thearray if necessary."""
# Double the physical size if no moreroom for items
# and add the fillValue to the newcells in the underlying list
# your code here
def shrink(self):
"""Decreases the physical size of thearray if necessary."""
# Shrink the size by half but not belowthe default capacity
# and remove those garbage cells fromthe underlying list
# your code here
def main():
"""Test code for modified Array class."""
a = Array(5)
print("Physical size:", len(a))
print("Logical size:", a.size())
print("Items:", a)
a.grow()
print("Items:", a)
a.grow()
print("Items:", a)
a.shrink()
print("Items:", a)
a.shrink()
print("Items:", a)
a.shrink()
print("Items:", a)
if __name__ == "__main__":
main()
Essentials of Business Analytics
ISBN: 978-1285187273
1st edition
Authors: Jeffrey Camm, James Cochran, Michael Fry, Jeffrey Ohlmann, David Anderson, Dennis Sweeney, Thomas Williams