SlideShare a Scribd company logo
Chapter 05/.DS_Store
Chapter 05/arraybag.py
"""
File: arraybag.py
Author: Ken Lambert
"""
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 not item in other:
return False
return True
# Mutator methods
def clear(self):
"""Makes self become empty."""
# Exercise
pass
def add(self, item):
"""Adds item to self."""
# Check array memory here and increase it if necessary
# Exercise
self._items[len(self)] = item
self._size += 1
def remove(self, item):
"""Precondition: item is in self.
Raises: KeyError if item in not in self.
Postcondition: item is removed from self."""
# Check precondition and raise if necessary
if not item in self:
raise KeyError(str(item) + " not in bag")
# Search for the index of the target item
targetIndex = 0
for targetItem in self:
if targetItem == item:
break
targetIndex += 1
# Shift items to the left of target up by one position
for i in range(targetIndex, len(self) - 1):
self._items[i] = self._items[i + 1]
# Decrement logical size
self._size -= 1
# Check array memory here and decrease it if necessary
# Exercise
Chapter 05/arrays.py
"""
File: arrays.py
An Array is a restricted list whose clients can use
only [], len, iter, and str.
To instantiate, use
<variable> = array(<capacity>, <optional fill value>)
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 the array.
fillValue is placed at each position."""
self._items = list()
for count in range(capacity):
self._items.append(fillValue)
def __len__(self):
"""-> The capacity of the array."""
return len(self._items)
def __str__(self):
"""-> The string representation of the array."""
return str(self._items)
def __iter__(self):
"""Supports iteration over a view of an array."""
return iter(self._items)
def __getitem__(self, index):
"""Subscript operator for access at index."""
return self._items[index]
def __setitem__(self, index, newItem):
"""Subscript operator for replacement at index."""
self._items[index] = newItem
Chapter 05/baginterface.py
"""
File: baginterface.py
Author: Ken Lambert
"""
class BagInterface(object):
"""Interface for all bag types."""
# Constructor
def __init__(self, sourceCollection = None):
"""Sets the initial state of self, which includes the
contents of sourceCollection, if it's present."""
pass
# Accessor methods
def isEmpty(self):
"""Returns True if len(self) == 0, or False otherwise."""
return True
def __len__(self):
"""-Returns the number of items in self."""
return 0
def __str__(self):
"""Returns the string representation of self."""
return ""
def __iter__(self):
"""Supports iteration over a view of self."""
return None
def __add__(self, other):
"""Returns a new bag containing the contents
of self and other."""
return None
def __eq__(self, other):
"""Returns True if self equals other,
or False otherwise."""
return False
# Mutator methods
def clear(self):
"""Makes self become empty."""
pass
def add(self, item):
"""Adds item to self."""
pass
def remove(self, item):
"""Precondition: item is in self.
Raises: KeyError if item in not in self.
Postcondition: item is removed from self."""
pass
Chapter 05/linkedbag.py
"""
File: linkedbag.py
Author: Ken Lambert
"""
from node import Node
class LinkedBag(object):
"""A link-based bag implementation."""
# Constructor
def __init__(self, sourceCollection = None):
"""Sets the initial state of self, which includes the
contents of sourceCollection, if it's present."""
self._items = None
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 = self._items
while not cursor is None:
yield cursor.data
cursor = cursor.next
def __add__(self, other):
"""Returns a new bag containing the contents
of self and other."""
result = LinkedBag(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 not item in other:
return False
return True
# Mutator methods
def clear(self):
"""Makes self become empty."""
# Exercise
pass
def add(self, item):
"""Adds item to self."""
self._items = Node(item, self._items)
self._size += 1
def remove(self, item):
"""Precondition: item is in self.
Raises: KeyError if item in not in self.
Postcondition: item is removed from self."""
# Check precondition and raise if necessary
if not item in self:
raise KeyError(str(item) + " not in bag")
# Search for the node containing the target item
# probe will point to the target node, and trailer
# will point to the one before it, if it exists
probe = self._items
trailer = None
for targetItem in self:
if targetItem == item:
break
trailer = probe
probe = probe.next
# Unhook the node to be deleted, either the first one or
one
# thereafter
if probe == self._items:
self._items = self._items.next
else:
trailer.next = probe.next
# Decrement logical size
self._size -= 1
Chapter 05/node.py
"""
File: node.py
Author: Ken Lambert
"""
class Node(object):
"""Represents a singly linked node."""
def __init__(self, data, next = None):
self.data = data
self.next = next
Chapter 05/testbag.py
"""
File: testbag.py
Author: Ken Lambert
A tester program for bag implementations.
"""
from arraybag import ArrayBag
from linkedbag import LinkedBag
def test(bagType):
"""Expects a bag type as an argument and runs some tests
on objects of that type."""
lyst = [2013, 61, 1973]
print("The list of items added is:", lyst)
b1 = bagType(lyst)
print("Expect 3:", len(b1))
print("Expect the bag's string:", b1)
print("Expect True:", 2013 in b1)
print("Expect False:", 2012 in b1)
print("Expect the items on separate lines:")
for item in b1:
print(item)
b1.clear()
print("Expect {}:", b1)
b1.add(25)
b1.remove(25)
print("Expect {}:", b1)
b1 = bagType(lyst)
b2 = bagType(b1)
print("Expect True:", b1 == b2)
print("Expect False:", b1 is b2)
print("Expect two of each item:", b1 + b2)
for item in lyst:
b1.remove(item)
print("Expect {}:", b1)
print("Expect crash with KeyError:")
b2.remove(99)
#test(ArrayBag)
test(LinkedBag)

More Related Content

Similar to Chapter 05.DS_StoreChapter 05arraybag.pyFile array.docx

java I am trying to run my code but it is not letting me .pdf
java    I am trying to run my code but it is not letting me .pdfjava    I am trying to run my code but it is not letting me .pdf
java I am trying to run my code but it is not letting me .pdf
adinathassociates
 
please please modify the code and update with whole code with modifi.pdf
please please modify the code and update with whole code with modifi.pdfplease please modify the code and update with whole code with modifi.pdf
please please modify the code and update with whole code with modifi.pdf
rmwaterlife
 
class LinkedList(object)    class _StackNode(object) .pdf
 class LinkedList(object)    class _StackNode(object) .pdf class LinkedList(object)    class _StackNode(object) .pdf
class LinkedList(object)    class _StackNode(object) .pdf
sooryasalini
 
Adding methods to the ListBag classIn the file ListBag.py, add the.pdf
Adding methods to the ListBag classIn the file ListBag.py, add the.pdfAdding methods to the ListBag classIn the file ListBag.py, add the.pdf
Adding methods to the ListBag classIn the file ListBag.py, add the.pdf
mohammedfootwear
 
Character.cpphpp givenCharacter.cpp#include Character.hp.pdf
Character.cpphpp givenCharacter.cpp#include Character.hp.pdfCharacter.cpphpp givenCharacter.cpp#include Character.hp.pdf
Character.cpphpp givenCharacter.cpp#include Character.hp.pdf
txkev
 

Similar to Chapter 05.DS_StoreChapter 05arraybag.pyFile array.docx (20)

Javascript Objects Deep Dive
Javascript Objects Deep DiveJavascript Objects Deep Dive
Javascript Objects Deep Dive
 
Pyimproved again
Pyimproved againPyimproved again
Pyimproved again
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
java I am trying to run my code but it is not letting me .pdf
java    I am trying to run my code but it is not letting me .pdfjava    I am trying to run my code but it is not letting me .pdf
java I am trying to run my code but it is not letting me .pdf
 
please please modify the code and update with whole code with modifi.pdf
please please modify the code and update with whole code with modifi.pdfplease please modify the code and update with whole code with modifi.pdf
please please modify the code and update with whole code with modifi.pdf
 
ECET 370 HELPS Education Counseling--ecet370helps.com
ECET 370 HELPS  Education Counseling--ecet370helps.comECET 370 HELPS  Education Counseling--ecet370helps.com
ECET 370 HELPS Education Counseling--ecet370helps.com
 
A JIT Smalltalk VM written in itself
A JIT Smalltalk VM written in itselfA JIT Smalltalk VM written in itself
A JIT Smalltalk VM written in itself
 
Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
 
class LinkedList(object)    class _StackNode(object) .pdf
 class LinkedList(object)    class _StackNode(object) .pdf class LinkedList(object)    class _StackNode(object) .pdf
class LinkedList(object)    class _StackNode(object) .pdf
 
Adding methods to the ListBag classIn the file ListBag.py, add the.pdf
Adding methods to the ListBag classIn the file ListBag.py, add the.pdfAdding methods to the ListBag classIn the file ListBag.py, add the.pdf
Adding methods to the ListBag classIn the file ListBag.py, add the.pdf
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
ECET 370 HELPS Redefined Education--ecet370helps.com
ECET 370 HELPS Redefined Education--ecet370helps.comECET 370 HELPS Redefined Education--ecet370helps.com
ECET 370 HELPS Redefined Education--ecet370helps.com
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming Language
 
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesA linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
 
Character.cpphpp givenCharacter.cpp#include Character.hp.pdf
Character.cpphpp givenCharacter.cpp#include Character.hp.pdfCharacter.cpphpp givenCharacter.cpp#include Character.hp.pdf
Character.cpphpp givenCharacter.cpp#include Character.hp.pdf
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
 
The Ring programming language version 1.5.4 book - Part 38 of 185
The Ring programming language version 1.5.4 book - Part 38 of 185The Ring programming language version 1.5.4 book - Part 38 of 185
The Ring programming language version 1.5.4 book - Part 38 of 185
 
Constructors_this keyword_garbage.pptx
Constructors_this keyword_garbage.pptxConstructors_this keyword_garbage.pptx
Constructors_this keyword_garbage.pptx
 
Python Metaclasses
Python MetaclassesPython Metaclasses
Python Metaclasses
 

More from tidwellveronique

EDUC 742EDUC 742Reading Summary and Reflective Comments .docx
EDUC 742EDUC 742Reading Summary and Reflective Comments .docxEDUC 742EDUC 742Reading Summary and Reflective Comments .docx
EDUC 742EDUC 742Reading Summary and Reflective Comments .docx
tidwellveronique
 
EDUC 380 Blog Post Samples Module 1 The Brain Below .docx
EDUC 380 Blog Post Samples Module 1 The Brain  Below .docxEDUC 380 Blog Post Samples Module 1 The Brain  Below .docx
EDUC 380 Blog Post Samples Module 1 The Brain Below .docx
tidwellveronique
 
EDUC 741Course Project Part 1 Grading RubricCriteriaLevels .docx
EDUC 741Course Project Part 1 Grading RubricCriteriaLevels .docxEDUC 741Course Project Part 1 Grading RubricCriteriaLevels .docx
EDUC 741Course Project Part 1 Grading RubricCriteriaLevels .docx
tidwellveronique
 
EDUC 740Prayer Reflection Report Grading RubricCriteriaLev.docx
EDUC 740Prayer Reflection Report Grading RubricCriteriaLev.docxEDUC 740Prayer Reflection Report Grading RubricCriteriaLev.docx
EDUC 740Prayer Reflection Report Grading RubricCriteriaLev.docx
tidwellveronique
 
EDUC 6733 Action Research for EducatorsReading LiteracyDraft.docx
EDUC 6733 Action Research for EducatorsReading LiteracyDraft.docxEDUC 6733 Action Research for EducatorsReading LiteracyDraft.docx
EDUC 6733 Action Research for EducatorsReading LiteracyDraft.docx
tidwellveronique
 
EDUC 637Technology Portfolio InstructionsGeneral OverviewF.docx
EDUC 637Technology Portfolio InstructionsGeneral OverviewF.docxEDUC 637Technology Portfolio InstructionsGeneral OverviewF.docx
EDUC 637Technology Portfolio InstructionsGeneral OverviewF.docx
tidwellveronique
 
EDUC 364 The Role of Cultural Diversity in Schooling A dialecti.docx
EDUC 364 The Role of Cultural Diversity in Schooling A dialecti.docxEDUC 364 The Role of Cultural Diversity in Schooling A dialecti.docx
EDUC 364 The Role of Cultural Diversity in Schooling A dialecti.docx
tidwellveronique
 
EDUC 144 Writing Tips The writing assignments in this cla.docx
EDUC 144 Writing Tips  The writing assignments in this cla.docxEDUC 144 Writing Tips  The writing assignments in this cla.docx
EDUC 144 Writing Tips The writing assignments in this cla.docx
tidwellveronique
 
EDUC 1300- LEARNING FRAMEWORK Portfolio Page Prompts .docx
EDUC 1300- LEARNING FRAMEWORK Portfolio Page Prompts .docxEDUC 1300- LEARNING FRAMEWORK Portfolio Page Prompts .docx
EDUC 1300- LEARNING FRAMEWORK Portfolio Page Prompts .docx
tidwellveronique
 
EDU734 Teaching and Learning Environment Week 5.docx
EDU734 Teaching and  Learning Environment Week 5.docxEDU734 Teaching and  Learning Environment Week 5.docx
EDU734 Teaching and Learning Environment Week 5.docx
tidwellveronique
 
EDU 505 – Contemporary Issues in EducationCOURSE DESCRIPTION.docx
EDU 505 – Contemporary Issues in EducationCOURSE DESCRIPTION.docxEDU 505 – Contemporary Issues in EducationCOURSE DESCRIPTION.docx
EDU 505 – Contemporary Issues in EducationCOURSE DESCRIPTION.docx
tidwellveronique
 
EDU 3338 Lesson Plan TemplateCandidate NameCooperatin.docx
EDU 3338 Lesson Plan TemplateCandidate NameCooperatin.docxEDU 3338 Lesson Plan TemplateCandidate NameCooperatin.docx
EDU 3338 Lesson Plan TemplateCandidate NameCooperatin.docx
tidwellveronique
 
EDU 3215 Lesson Plan Template & Elements Name Andres Rod.docx
EDU 3215 Lesson Plan Template & Elements  Name Andres Rod.docxEDU 3215 Lesson Plan Template & Elements  Name Andres Rod.docx
EDU 3215 Lesson Plan Template & Elements Name Andres Rod.docx
tidwellveronique
 
EDST 1100R SITUATED LEARNING EDST 1100 N Situated Learning .docx
EDST 1100R SITUATED LEARNING  EDST 1100 N Situated Learning .docxEDST 1100R SITUATED LEARNING  EDST 1100 N Situated Learning .docx
EDST 1100R SITUATED LEARNING EDST 1100 N Situated Learning .docx
tidwellveronique
 
EDU 151 Thematic Unit Required ComponentsThematic Unit Requireme.docx
EDU 151 Thematic Unit Required ComponentsThematic Unit Requireme.docxEDU 151 Thematic Unit Required ComponentsThematic Unit Requireme.docx
EDU 151 Thematic Unit Required ComponentsThematic Unit Requireme.docx
tidwellveronique
 
EDSP 429Differentiated Instruction PowerPoint InstructionsThe .docx
EDSP 429Differentiated Instruction PowerPoint InstructionsThe .docxEDSP 429Differentiated Instruction PowerPoint InstructionsThe .docx
EDSP 429Differentiated Instruction PowerPoint InstructionsThe .docx
tidwellveronique
 
EDSP 429Fact Sheet on Disability Categories InstructionsThe pu.docx
EDSP 429Fact Sheet on Disability Categories InstructionsThe pu.docxEDSP 429Fact Sheet on Disability Categories InstructionsThe pu.docx
EDSP 429Fact Sheet on Disability Categories InstructionsThe pu.docx
tidwellveronique
 
EDSP 370Individualized Education Plan (IEP) InstructionsThe .docx
EDSP 370Individualized Education Plan (IEP) InstructionsThe .docxEDSP 370Individualized Education Plan (IEP) InstructionsThe .docx
EDSP 370Individualized Education Plan (IEP) InstructionsThe .docx
tidwellveronique
 
EDSP 377Scenario InstructionsScenario 2 Teaching communicatio.docx
EDSP 377Scenario InstructionsScenario 2 Teaching communicatio.docxEDSP 377Scenario InstructionsScenario 2 Teaching communicatio.docx
EDSP 377Scenario InstructionsScenario 2 Teaching communicatio.docx
tidwellveronique
 
EDSP 377Autism Interventions1. Applied Behavior Analysis (ABA).docx
EDSP 377Autism Interventions1. Applied Behavior Analysis (ABA).docxEDSP 377Autism Interventions1. Applied Behavior Analysis (ABA).docx
EDSP 377Autism Interventions1. Applied Behavior Analysis (ABA).docx
tidwellveronique
 

More from tidwellveronique (20)

EDUC 742EDUC 742Reading Summary and Reflective Comments .docx
EDUC 742EDUC 742Reading Summary and Reflective Comments .docxEDUC 742EDUC 742Reading Summary and Reflective Comments .docx
EDUC 742EDUC 742Reading Summary and Reflective Comments .docx
 
EDUC 380 Blog Post Samples Module 1 The Brain Below .docx
EDUC 380 Blog Post Samples Module 1 The Brain  Below .docxEDUC 380 Blog Post Samples Module 1 The Brain  Below .docx
EDUC 380 Blog Post Samples Module 1 The Brain Below .docx
 
EDUC 741Course Project Part 1 Grading RubricCriteriaLevels .docx
EDUC 741Course Project Part 1 Grading RubricCriteriaLevels .docxEDUC 741Course Project Part 1 Grading RubricCriteriaLevels .docx
EDUC 741Course Project Part 1 Grading RubricCriteriaLevels .docx
 
EDUC 740Prayer Reflection Report Grading RubricCriteriaLev.docx
EDUC 740Prayer Reflection Report Grading RubricCriteriaLev.docxEDUC 740Prayer Reflection Report Grading RubricCriteriaLev.docx
EDUC 740Prayer Reflection Report Grading RubricCriteriaLev.docx
 
EDUC 6733 Action Research for EducatorsReading LiteracyDraft.docx
EDUC 6733 Action Research for EducatorsReading LiteracyDraft.docxEDUC 6733 Action Research for EducatorsReading LiteracyDraft.docx
EDUC 6733 Action Research for EducatorsReading LiteracyDraft.docx
 
EDUC 637Technology Portfolio InstructionsGeneral OverviewF.docx
EDUC 637Technology Portfolio InstructionsGeneral OverviewF.docxEDUC 637Technology Portfolio InstructionsGeneral OverviewF.docx
EDUC 637Technology Portfolio InstructionsGeneral OverviewF.docx
 
EDUC 364 The Role of Cultural Diversity in Schooling A dialecti.docx
EDUC 364 The Role of Cultural Diversity in Schooling A dialecti.docxEDUC 364 The Role of Cultural Diversity in Schooling A dialecti.docx
EDUC 364 The Role of Cultural Diversity in Schooling A dialecti.docx
 
EDUC 144 Writing Tips The writing assignments in this cla.docx
EDUC 144 Writing Tips  The writing assignments in this cla.docxEDUC 144 Writing Tips  The writing assignments in this cla.docx
EDUC 144 Writing Tips The writing assignments in this cla.docx
 
EDUC 1300- LEARNING FRAMEWORK Portfolio Page Prompts .docx
EDUC 1300- LEARNING FRAMEWORK Portfolio Page Prompts .docxEDUC 1300- LEARNING FRAMEWORK Portfolio Page Prompts .docx
EDUC 1300- LEARNING FRAMEWORK Portfolio Page Prompts .docx
 
EDU734 Teaching and Learning Environment Week 5.docx
EDU734 Teaching and  Learning Environment Week 5.docxEDU734 Teaching and  Learning Environment Week 5.docx
EDU734 Teaching and Learning Environment Week 5.docx
 
EDU 505 – Contemporary Issues in EducationCOURSE DESCRIPTION.docx
EDU 505 – Contemporary Issues in EducationCOURSE DESCRIPTION.docxEDU 505 – Contemporary Issues in EducationCOURSE DESCRIPTION.docx
EDU 505 – Contemporary Issues in EducationCOURSE DESCRIPTION.docx
 
EDU 3338 Lesson Plan TemplateCandidate NameCooperatin.docx
EDU 3338 Lesson Plan TemplateCandidate NameCooperatin.docxEDU 3338 Lesson Plan TemplateCandidate NameCooperatin.docx
EDU 3338 Lesson Plan TemplateCandidate NameCooperatin.docx
 
EDU 3215 Lesson Plan Template & Elements Name Andres Rod.docx
EDU 3215 Lesson Plan Template & Elements  Name Andres Rod.docxEDU 3215 Lesson Plan Template & Elements  Name Andres Rod.docx
EDU 3215 Lesson Plan Template & Elements Name Andres Rod.docx
 
EDST 1100R SITUATED LEARNING EDST 1100 N Situated Learning .docx
EDST 1100R SITUATED LEARNING  EDST 1100 N Situated Learning .docxEDST 1100R SITUATED LEARNING  EDST 1100 N Situated Learning .docx
EDST 1100R SITUATED LEARNING EDST 1100 N Situated Learning .docx
 
EDU 151 Thematic Unit Required ComponentsThematic Unit Requireme.docx
EDU 151 Thematic Unit Required ComponentsThematic Unit Requireme.docxEDU 151 Thematic Unit Required ComponentsThematic Unit Requireme.docx
EDU 151 Thematic Unit Required ComponentsThematic Unit Requireme.docx
 
EDSP 429Differentiated Instruction PowerPoint InstructionsThe .docx
EDSP 429Differentiated Instruction PowerPoint InstructionsThe .docxEDSP 429Differentiated Instruction PowerPoint InstructionsThe .docx
EDSP 429Differentiated Instruction PowerPoint InstructionsThe .docx
 
EDSP 429Fact Sheet on Disability Categories InstructionsThe pu.docx
EDSP 429Fact Sheet on Disability Categories InstructionsThe pu.docxEDSP 429Fact Sheet on Disability Categories InstructionsThe pu.docx
EDSP 429Fact Sheet on Disability Categories InstructionsThe pu.docx
 
EDSP 370Individualized Education Plan (IEP) InstructionsThe .docx
EDSP 370Individualized Education Plan (IEP) InstructionsThe .docxEDSP 370Individualized Education Plan (IEP) InstructionsThe .docx
EDSP 370Individualized Education Plan (IEP) InstructionsThe .docx
 
EDSP 377Scenario InstructionsScenario 2 Teaching communicatio.docx
EDSP 377Scenario InstructionsScenario 2 Teaching communicatio.docxEDSP 377Scenario InstructionsScenario 2 Teaching communicatio.docx
EDSP 377Scenario InstructionsScenario 2 Teaching communicatio.docx
 
EDSP 377Autism Interventions1. Applied Behavior Analysis (ABA).docx
EDSP 377Autism Interventions1. Applied Behavior Analysis (ABA).docxEDSP 377Autism Interventions1. Applied Behavior Analysis (ABA).docx
EDSP 377Autism Interventions1. Applied Behavior Analysis (ABA).docx
 

Recently uploaded

Recently uploaded (20)

Morse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptxMorse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptx
 
Open Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPointOpen Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPoint
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
The Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational ResourcesThe Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational Resources
 
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptxMatatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
 
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
 
NCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdfNCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdf
 
Gyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptxGyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptx
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
Operations Management - Book1.p  - Dr. Abdulfatah A. SalemOperations Management - Book1.p  - Dr. Abdulfatah A. Salem
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
 
2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
How to Manage Notification Preferences in the Odoo 17
How to Manage Notification Preferences in the Odoo 17How to Manage Notification Preferences in the Odoo 17
How to Manage Notification Preferences in the Odoo 17
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 

Chapter 05.DS_StoreChapter 05arraybag.pyFile array.docx

  • 1. Chapter 05/.DS_Store Chapter 05/arraybag.py """ File: arraybag.py Author: Ken Lambert """ 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."""
  • 2. 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 not item in other: return False return True # Mutator methods def clear(self): """Makes self become empty."""
  • 3. # Exercise pass def add(self, item): """Adds item to self.""" # Check array memory here and increase it if necessary # Exercise self._items[len(self)] = item self._size += 1 def remove(self, item): """Precondition: item is in self. Raises: KeyError if item in not in self. Postcondition: item is removed from self.""" # Check precondition and raise if necessary if not item in self: raise KeyError(str(item) + " not in bag") # Search for the index of the target item targetIndex = 0 for targetItem in self: if targetItem == item: break targetIndex += 1 # Shift items to the left of target up by one position for i in range(targetIndex, len(self) - 1): self._items[i] = self._items[i + 1] # Decrement logical size self._size -= 1 # Check array memory here and decrease it if necessary # Exercise Chapter 05/arrays.py """
  • 4. File: arrays.py An Array is a restricted list whose clients can use only [], len, iter, and str. To instantiate, use <variable> = array(<capacity>, <optional fill value>) 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 the array. fillValue is placed at each position.""" self._items = list() for count in range(capacity): self._items.append(fillValue) def __len__(self): """-> The capacity of the array.""" return len(self._items) def __str__(self): """-> The string representation of the array.""" return str(self._items) def __iter__(self): """Supports iteration over a view of an array.""" return iter(self._items) def __getitem__(self, index): """Subscript operator for access at index."""
  • 5. return self._items[index] def __setitem__(self, index, newItem): """Subscript operator for replacement at index.""" self._items[index] = newItem Chapter 05/baginterface.py """ File: baginterface.py Author: Ken Lambert """ class BagInterface(object): """Interface for all bag types.""" # Constructor def __init__(self, sourceCollection = None): """Sets the initial state of self, which includes the contents of sourceCollection, if it's present.""" pass # Accessor methods def isEmpty(self): """Returns True if len(self) == 0, or False otherwise.""" return True def __len__(self): """-Returns the number of items in self.""" return 0 def __str__(self): """Returns the string representation of self.""" return "" def __iter__(self):
  • 6. """Supports iteration over a view of self.""" return None def __add__(self, other): """Returns a new bag containing the contents of self and other.""" return None def __eq__(self, other): """Returns True if self equals other, or False otherwise.""" return False # Mutator methods def clear(self): """Makes self become empty.""" pass def add(self, item): """Adds item to self.""" pass def remove(self, item): """Precondition: item is in self. Raises: KeyError if item in not in self. Postcondition: item is removed from self.""" pass Chapter 05/linkedbag.py """ File: linkedbag.py Author: Ken Lambert """ from node import Node
  • 7. class LinkedBag(object): """A link-based bag implementation.""" # Constructor def __init__(self, sourceCollection = None): """Sets the initial state of self, which includes the contents of sourceCollection, if it's present.""" self._items = None 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 = self._items while not cursor is None: yield cursor.data cursor = cursor.next def __add__(self, other): """Returns a new bag containing the contents
  • 8. of self and other.""" result = LinkedBag(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 not item in other: return False return True # Mutator methods def clear(self): """Makes self become empty.""" # Exercise pass def add(self, item): """Adds item to self.""" self._items = Node(item, self._items) self._size += 1 def remove(self, item): """Precondition: item is in self. Raises: KeyError if item in not in self. Postcondition: item is removed from self.""" # Check precondition and raise if necessary if not item in self: raise KeyError(str(item) + " not in bag")
  • 9. # Search for the node containing the target item # probe will point to the target node, and trailer # will point to the one before it, if it exists probe = self._items trailer = None for targetItem in self: if targetItem == item: break trailer = probe probe = probe.next # Unhook the node to be deleted, either the first one or one # thereafter if probe == self._items: self._items = self._items.next else: trailer.next = probe.next # Decrement logical size self._size -= 1 Chapter 05/node.py """ File: node.py Author: Ken Lambert """ class Node(object): """Represents a singly linked node.""" def __init__(self, data, next = None): self.data = data self.next = next
  • 10. Chapter 05/testbag.py """ File: testbag.py Author: Ken Lambert A tester program for bag implementations. """ from arraybag import ArrayBag from linkedbag import LinkedBag def test(bagType): """Expects a bag type as an argument and runs some tests on objects of that type.""" lyst = [2013, 61, 1973] print("The list of items added is:", lyst) b1 = bagType(lyst) print("Expect 3:", len(b1)) print("Expect the bag's string:", b1) print("Expect True:", 2013 in b1) print("Expect False:", 2012 in b1) print("Expect the items on separate lines:") for item in b1: print(item) b1.clear() print("Expect {}:", b1) b1.add(25) b1.remove(25) print("Expect {}:", b1) b1 = bagType(lyst) b2 = bagType(b1) print("Expect True:", b1 == b2) print("Expect False:", b1 is b2) print("Expect two of each item:", b1 + b2) for item in lyst: b1.remove(item)
  • 11. print("Expect {}:", b1) print("Expect crash with KeyError:") b2.remove(99) #test(ArrayBag) test(LinkedBag)