Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Can you please help me with this Python remove() method question. The remove() method resizes the array when necessary by removing an item from the

Can you please help me with this Python remove() method question.

The remove() method resizes the array when necessary by removing an item from the array if it exist.

NOTE: Be sure to reuse your solution from Programming Exercise 5.3 as your starter file for the arraybag.py file. ( I will post this file too)

In the arraybag.py file define the remove() method in the ArrayBag class by completing the following:

  1. Check the precondition and raise a KeyError if necessary
    • Precondition: item is in self.
    • Raises: KeyError if item in not in self.
    • Postcondition: item is removed from self.
  2. Search for the index of the target item
  3. Shift items to the left of target up by one position
  4. Decrement logical size
  5. Check array memory here and decrease it if necessary

To test your program run the testResize() method in the testbag.py file.

(This below part was in question too but i'm not sure what is it. Thought it will help on solving.)

Added 100 items, length of bag = 100

Expect 160 as length of array = 160 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99}

Removed 76 items, expect 24 as length of bag: 24

Expect 80 as length of array = 80

Removed remaining items, length of bag = 0

Expect 10 as length of array = 10

So, i will post THREE files. one: arraybag.py. Two: testbag.py ( to test the code) And Three: 5.3 Solution.

File: arraybag.py

"""

Project 5.4

File: arraybag.py

Reuse your solution from Programming Exercise 5.3 as your starter file

"""

from arrays import Array

class ArrayBag(object):

"""An array-based bag implementation."""

# Reuse your solution from Programming Exercise 5.3 as your starter file

# Class variable

DEFAULT_CAPACITY = 10

# Constructor

def __init__(self, sourceCollection = None):

"""Sets the initial state of self, which includes the

contents of sourceCollection, if it's present."""

self.items = Array(ArrayBag.DEFAULT_CAPACITY)

self.size = 0

if sourceCollection:

for item in sourceCollection:

self.add(item)

# Accessor methods

def isEmpty(self):

"""Returns True if len(self) == 0, or False otherwise."""

return len(self) == 0

def __len__(self):

"""Returns the number of items in self."""

return self.size

def __str__(self):

"""Returns the string representation of self."""

return "{" + ", ".join(map(str, self)) + "}"

def __iter__(self):

"""Supports iteration over a view of self."""

cursor = 0

while cursor < len(self):

yield self.items[cursor]

cursor += 1

def __add__(self, other):

"""Returns a new bag containing the contents

of self and other."""

result = ArrayBag(self)

for item in other:

result.add(item)

return result

def __eq__(self, other):

"""Returns True if self equals other,

or False otherwise."""

if self is other: return True

if type(self) != type(other) or \

len(self) != len(other):

return False

for item in self:

if self.count(item) != other.count(item):

return False

return True

def count(self, item):

"""Returns the number of instances of item in self."""

total = 0

for nextItem in self:

if nextItem == item:

total += 1

return total

# Mutator methods

def clear(self):

"""Makes self become empty."""

self.size = 0

self.items = Array(ArrayBag.DEFAULT_CAPACITY)

File: testbag.py

"""

File: testbag.py

A tester program for bag implementations.

"""

from arraybag import ArrayBag

def test(bagType):

"""Expects a bag type as an argument and runs some tests

on objects of that type."""

print("Testing", bagType)

lyst = list(range(1, 11))

print("The list of items added is:", lyst)

b = bagType(lyst)

print("Expect the bag's string:", b)

print("Add 5 more items to test increasing the array size:")

for i in range(11, 16):

b.add(i)

print("Expect the bag's string:", b)

def testResize():

"""Tests the resizing of an array-based bag,

when space is wasted."""

bag = ArrayBag(range(100))

print("Added 100 items, length of bag =", len(bag))

print("Expect 160 as length of array =", len(bag.items))

print(bag)

for item in range(76):

bag.remove(item)

print("Removed 76 items, expect 24 as length of bag:", len(bag))

print("Expect 80 as length of array =", len(bag.items))

for item in range(76, 100):

bag.remove(item)

print("Removed remaining items, length of bag =", len(bag))

print("Expect 10 as length of array =", len(bag.items))

testResize()

5.3 solution

from arrays import Array

class ArrayBag(object):

"""An array-based bag implementation."""

# Class variable

DEFAULT_CAPACITY = 10

# Constructor

def __init__(self, sourceCollection=None):

"""Sets the initial state of self, which includes the

contents of sourceCollection, if it's present."""

self.items = Array(ArrayBag.DEFAULT_CAPACITY)

self.size = 0

if sourceCollection:

for item in sourceCollection:

self.add(item)

# Accessor methods

def isEmpty(self):

"""Returns True if len(self) == 0, or False otherwise."""

return len(self) == 0

def __len__(self):

"""Returns the number of items in self."""

return self.size

def __str__(self):

"""Returns the string representation of self."""

return "{" + ", ".join(map(str, self)) + "}"

def __iter__(self):

"""Supports iteration over a view of self."""

cursor = 0

while cursor < len(self):

yield self.items[cursor]

cursor += 1

def __add__(self, other):

"""Returns a new bag containing the contents

of self and other."""

result = ArrayBag(self)

for item in other:

result.add(item)

return result

def __eq__(self, other):

"""Returns True if self equals other,

or False otherwise."""

if self is other: return True

if type(self) != type(other) or len(self) != len(other):

return False

for item in self:

if self.count(item) != other.count(item):

return False

return True

def count(self, item):

"""Returns the number of instances of item in self."""

total = 0

for nextItem in self:

if nextItem == item:

total += 1

return total

# Mutator methods

def clear(self):

"""Makes self become empty."""

self.size = 0

self.items = Array(ArrayBag.DEFAULT_CAPACITY)

def add(self, item):

"""Adds item to self."""

# checking if size reached the capacity of self.items

if self.size == len(self.items):

# creating a new Array of twice capacity

new_arr = Array(self.size * 2)

# copying all elements from self.items to new_arr

for i in range(self.size):

new_arr[i] = self.items[i]

# replacing self.items with new_arr

self.items = new_arr

# adding item to index=self.size

self.items[self.size] = item

# updating size

self.size += 1

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

Murach's SQL Server 2012 For Developers

Authors: Bryan Syverson, Joel Murach, Mike Murach

1st Edition

1890774693, 9781890774691

More Books

Students also viewed these Databases questions