Computer Science 112 Fundamentals of Programming II Iterators.

Slides:



Advertisements
Similar presentations
Singly linked lists Doubly linked lists
Advertisements

Computer Science 112 Fundamentals of Programming II List Iterators.
COSC 1P03 Data Structures and Abstraction 10.1 The List If A is success in life, then A equals x plus y plus z. Work is x; y is play; and z is keeping.
Stack & Queues COP 3502.
Ceng-112 Data Structures I Chapter 5 Queues.
Computer Science 112 Fundamentals of Programming II Queues and Priority Queues.
Computer Science 112 Fundamentals of Programming II Overview of Collections.
Computer Science 112 Fundamentals of Programming II Array-Based Queues.
Fundamentals of Python: From First Programs Through Data Structures
Chapter 10 Introduction to Arrays
Lecture 12 – ADTs and Stacks.  Modularity  Divide the program into smaller parts  Advantages  Keeps the complexity managable  Isolates errors (parts.
Computer Science 112 Fundamentals of Programming II Lists.
Fundamentals of Programming II Inheritance and Abstract Classes
COMPSCI 105 S Principles of Computer Science Linked Lists 2.
ITERATIVE CONSTRUCTS: DOLIST Dolist is an iterative construct (a loop statement) consisting of a variable declaration and a body The body states what happens.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 17: Linked Lists.
CS 206 Introduction to Computer Science II 10 / 14 / 2009 Instructor: Michael Eckmann.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Chapter 2 Writing Simple Programs
COMPSCI 105 S Principles of Computer Science Linked Lists 1.
Chapter 3: Arrays, Linked Lists, and Recursion
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Computer Science 112 Fundamentals of Programming II Expression Trees.
Computer Science 111 Fundamentals of Programming I Search Algorithms.
A Level Computer Science Topic 9: Data Structures T eaching L ondon C omputing William Marsh School of Electronic Engineering and Computer Science Queen.
Fundamentals of Python: From First Programs Through Data Structures Chapter 14 Linear Collections: Stacks.
Recursion, Complexity, and Searching and Sorting By Andrew Zeng.
Computer Science 112 Fundamentals of Programming II Introduction to Stacks.
ICS 102 Computer Programming University of Hail College of Computer Science & Engineering Computer Science and Software Engineering Department.
Xiaoyan Li, CSC211 Data Structures Lecture 10 The Bag and Sequence Classes with Linked Lists Instructor: Prof. Xiaoyan Li Department of Computer.
Big Java Chapter 16.
Algorithms and Algorithm Analysis The “fun” stuff.
Priority Queues and Binary Heaps Chapter Trees Some animals are more equal than others A queue is a FIFO data structure the first element.
Computer Science 111 Fundamentals of Programming I Model/View/Controller and Data model design.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 18 Linked Lists, Stacks, Queues, and Priority Queues.
Computer Science 112 Fundamentals of Programming II Interfaces and Implementations.
ICOM 4035 – Data Structures Lecture 3 – Bag ADT Manuel Rodriguez Martinez Electrical and Computer Engineering University of Puerto Rico, Mayagüez ©Manuel.
Python iterators and generators. Iterators and generators  Python makes good use of iterators  And has a special kind of generator function that is.
Computer Science 112 Fundamentals of Programming II Binary Search Trees.
Iterators and Generators Thomas Wouters XS4ALL
COMPSCI 105 SS 2015 Principles of Computer Science Linked Lists 1.
Computer Science 112 Fundamentals of Programming II Implementation Strategies for Unordered Collections.
Chapter 17 Q and A Victor Norman, et al. CS104. What is Object-oriented Programming? Q: What is object-oriented programming? A: It means defining classes/objects,
Tirgul 10. What We Will See Today:  Linked lists  Graphs  Trees  Iterators and Generators.
Tutorial 9 Iteration. Reminder Assignment 8 is due Wednesday.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Python Programing: An Introduction to Computer Science
9. ITERATIONS AND LOOP STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Chapter 7: Repetition Structure (Loop) Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 18 List ADT Animated Version.
CPSC 233 Tutorial 5 February 2 th /3 th, Java Loop Statements A portion of a program that repeats a statement or a group of statements is called.
Arrays, Link Lists, and Recursion Chapter 3. Sorting Arrays: Insertion Sort Insertion Sort: Insertion sort is an elementary sorting algorithm that sorts.
Chapter 2 Writing Simple Programs
Fundamentals of Programming II Linked Lists
Fundamentals of Programming II Overview of Collections
Software Development Java Classes and Methods
Python: Control Structures
Fundamentals of Programming II Working with Arrays
Fundamentals of Programming II Binary Search Trees
Fundamentals of Programming II Equality and Multiple Inheritance
Fundamentals of Programming II Interfaces and Implementations
Computer Science 112 Fundamentals of Programming II
The Bag and Sequence Classes with Linked Lists
Top Ten Words that Almost Rhyme with “Peas”
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
CSC 143 Queues [Chapter 7].
Computer Science 210 Computer Organization
Python LinkedLists.
Intro to Computer Science Loops
Fundamentals of Programming II What Is Equality?
Presentation transcript:

Computer Science 112 Fundamentals of Programming II Iterators

The for Loop for value in : Allows the programmer to iterate through all of the values in a collection (or any other iterable object)

The for Loop for value in : list( ) # builds a list from the collection Users:

The for Loop for value in : list( ) # builds a list from the collection sum( ) Users:

The for Loop for value in : list( ) # builds a list from the collection sum( ) min( ) Users:

The for Loop for value in : list( ) # builds a list from the collection sum( ) min( ) map(, ) Users:

The for Loop for value in : list( ) # builds a list from the collection sum( ) min( ) map(, ) filter(, ) Users:

The for Loop for value in : list( ) # builds a list from the collection sum( ) min( ) map(, ) filter(, ) in Users:

The Benefits of a for Loop class ArrayBag(object): DEFAULT_CAPACITY = 10 def __init__(self, sourceCollection = None): self._items = Array(ArrayBag.DEFAULT_CAPACITY) self._size = 0 if sourceCollection: for item in sourceCollection: self.add(item) Here we assume that sourceCollection is iterable s = ArrayBag(range(1, 11))

The Benefits of a for Loop class LinkedBag(object): def __init__(self, sourceCollection = None): self._items = None self._size = 0 if sourceCollection: for item in sourceCollection: self.add(item) Here we assume that sourceCollection is iterable s = LinkedBag(range(1, 11))

The Benefits of a for Loop class ArrayBag(object): 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 Here we assume that self and other are iterable b3 = b1 + b2

The Benefits of a for Loop class ArrayBag(object): def __str__(self): """Returns the string representation of self.""" return "{" + ", ".join(map(str, self)) + "}" Here we assume that self is iterable

Loop Patterns and Iterators for i in range(someInteger): for value in someCollection: When the PVM sees a for loop, it evaluates the second operand of in and then calls the iter function on its value The code in the iter function repeatedly fetches the next value in the second operand and binds it to the first operand After each fetch operation, the code in the loop body is run

Two Loop Patterns Thus, the second operand of in must include an __iter__ method in its class If you want your collection to be iterable, you must define an __iter__ method for i in range(someInteger): for value in someCollection:

Implementing an Iterator class Array(object): def __init__(self, capacity, fillValue = None): self._items = list() for count in range(capacity): self._items.append(fillValue) def __iter__(self): return iter(self._items) The __iter__ method of the Array class simply returns the result of calling iter on its underlying list

ArrayBag Iterator: A Nice Try class ArrayBag(object): DEFAULT_CAPACITY = 10 def __init__(self, sourceCollection = None): self._items = Array(ArrayBag.DEFAULT_CAPACITY) self._size = 0 if sourceCollection: for item in sourceCollection: self.add(item) def __iter__(self): return iter(self._items) What’s wrong with this code?

Designing an Iterator The __iter__ method must initialize and maintain a cursor, which locates the current item __iter__ ’s loop quits when the cursor goes off the end of the collection The body of the loop yields the current item and advances the cursor

Implementing an Iterator class ArrayBag(object): DEFAULT_CAPACITY = 10 def __init__(self, sourceCollection = None): self._items = Array(ArrayBag.DEFAULT_CAPACITY) self._size = 0 if sourceCollection: for item in sourceCollection: self.add(item) def __iter__(self): cursor = 0 while cursor < len(self): yield self._items[cursor] cursor += 1

Running an Iterator DDD collection iterator def __iter__(self): cursor = 0 while cursor < len(self): yield self._items[cursor] cursor += 1

Running an Iterator DDD collection iterator def __iter__(self): cursor = 0 while cursor < len(self): yield self._items[cursor] cursor += 1

Running an Iterator DDD collection iterator def __iter__(self): cursor = 0 while cursor < len(self): yield self._items[cursor] cursor += 1

Running an Iterator DDD collection iterator def __iter__(self): cursor = 0 while cursor < len(self): yield self._items[cursor] cursor += 1

An Iterator for a Linked Structure The cursor would be initialized to the head pointer (like a probe) The loop quits when the cursor equals None The value yielded is in the cursor’s node The cursor is updated by setting it to the next node

Implementing an Iterator class LinkedBag(object): def __init__(self, sourceCollection = None): self._items = None self._size = 0 if sourceCollection: for item in sourceCollection: self.add(item) def __iter__(self): cursor = self._items while cursor != None: yield cursor.data cursor = cursor.next

Iterator Should Be Read-Only for item in bag: bag.remove(item) Mutations in the context of a for loop can cause the state of the underlying collection to become inconsistent with the state of the iterator

Iterator Should Be Read-Only for item in bag: bag.remove(item) # Will raise an exception We can arrange for the collection to track mutations so that the iterator can detect illicit ones and raise exceptions bag.clear() # Preferred method

For Monday Inheritance and Abstract Classes Chapter 6