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

Javascript Objects Deep Dive
Javascript Objects Deep DiveJavascript Objects Deep Dive
Javascript Objects Deep Dive
Manish Jangir
 
Pyimproved again
Pyimproved againPyimproved again
Pyimproved again
rik0
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
dreampuf
 
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
 
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
claric64
 
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
ESUG
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
Maxim Kulsha
 
Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.
Python Meetup
 
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
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
Dragos Ionita
 
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
GVlaxmi7
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming Language
Duda Dornelles
 
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
Tchelinux
 
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
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
Damian T. Gordon
 
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
Mahmoud Samir Fayed
 
Constructors_this keyword_garbage.pptx
Constructors_this keyword_garbage.pptxConstructors_this keyword_garbage.pptx
Constructors_this keyword_garbage.pptx
revathi s
 
Python Metaclasses
Python MetaclassesPython Metaclasses
Python Metaclasses
Nikunj Parekh
 

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

BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
สมใจ จันสุกสี
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
iammrhaywood
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
TechSoup
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
Nguyen Thanh Tu Collection
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
paigestewart1632
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 

Recently uploaded (20)

BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 

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)