Python iterators and generators. Iterators and generators  Python makes good use of iterators  And has a special kind of generator function that is.

Slides:



Advertisements
Similar presentations
Def f(n): if (n == 0): return else: print(“*”) return f(n-1) f(3)
Advertisements

A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
COMPSCI 105 S Principles of Computer Science Linked Lists 2.
Unittest in five minutes Ray Toal How to unit test Not manually, that's for sure You write code that exercises your code Perform assertions.
Python Control of Flow.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Working with Files CSC 161: The Art of Programming Prof. Henry Kautz 11/9/2009.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Introduction to Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
Python: Classes By Matt Wufsus. Scopes and Namespaces A namespace is a mapping from names to objects. ◦Examples: the set of built-in names, such as the.
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
Q and A for Sections 2.6 – 2.8 CS 106 Victor Norman.
By: Chris Harvey Python Classes. Namespaces A mapping from names to objects Different namespaces have different mappings Namespaces have varying lifetimes.
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
Chapter 7 Lists and Tuples. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. Data Structures.
Documentation / References Python Full Documentation – Python Quick Reference –
Built-in Data Structures in Python An Introduction.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
Iterators, Linked Lists, MapReduce, Dictionaries, and List Comprehensions... OH MY! Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their.
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
Iterators and Generators Thomas Wouters XS4ALL
Data Collections: Lists CSC 161: The Art of Programming Prof. Henry Kautz 11/2/2009.
CIT 590 Intro to Programming Files etc. Announcements From HW5 onwards (HW5, HW6,…) You can work alone. You can pick your own partner. You can also stick.
Chapter 14 Advanced Function Topics CSC1310 Fall 2009.
Introduction to OOP OOP = Object-Oriented Programming OOP is very simple in python but also powerful What is an object? data structure, and functions (methods)
Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.
Cem Sahin CS  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Python Let’s get started!.
Tirgul 10. What We Will See Today:  Linked lists  Graphs  Trees  Iterators and Generators.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Computer Science 112 Fundamentals of Programming II Iterators.
PYTHON FOR HIGH PERFORMANCE COMPUTING. OUTLINE  Compiling for performance  Native ways for performance  Generator  Examples.
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
Xi Wang Yang Zhang. 1. Strings 2. Text Files 3. Exceptions 4. Classes  Refer to basics 2.py for the example codes for this section.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
Indentations makes the scope/block Function definition def print_message (): print “hello” Function usages print_message () hubo.move ()// hubo is a class.
Gordon Bell observed: The cheapest, fastest and most reliable components of a computer system are those that aren't there. This has a parallel in data.
Example: Vehicles What attributes do objects of Sedan have?
Algorithmic complexity: Speed of algorithms
CSC 458– Predictive Analytics I, Fall 2017, Intro. To Python
CS-104 Final Exam Review Victor Norman.
COMP280:Introduction to Software Development Week 12, Lecture 34
CS 115 Lecture 8 Structured Programming; for loops
Tutorial Lecture for EE562 Artificial Intelligence for Engineers
Topics Introduction to Repetition Structures
Repeating code We could repeat code we need more than once: i = 1 print (i) i += 1 print (i) #… stop when i == 9 But each line means an extra line we might.
Introduction to Python
Introduction to Python
Python Primer 2: Functions and Control Flow
File Handling Programming Guides.
Python’s Errors and Exceptions
CISC101 Reminders Slides have changed from those posted last night…
Python iterators and generators
CSC 458– Predictive Analytics I, Fall 2018, Intro. To Python
Python LinkedLists.
What does this do? def revList(L): if len(L) < = 1: return L x = L[0] LR = revList(L[1:]) return LR + x.
Algorithmic complexity: Speed of algorithms
Topics Sequences Introduction to Lists List Slicing
Python programming exercise
Advanced Python Concepts: Exceptions
CISC101 Reminders Assignment 2 due today.
Algorithmic complexity: Speed of algorithms
Advanced Python Concepts: Exceptions
Winter 2019 CISC101 4/29/2019 CISC101 Reminders
Topics Sequences Introduction to Lists List Slicing
Lecture 7: Python’s Built-in Types and Basic Statements
Python iterators and generators
Introduction to Computer Science
Presentation transcript:

Python iterators and generators

Iterators and generators  Python makes good use of iterators  And has a special kind of generator function that is powerful and useful  We’ll look at what both are  And why they are useful  See Norman Matloff’s excellent tutorial on python iterators and generators from which some of this material is borrowedtutorial

Files are iterators >>> f = open("myfile.txt") >>> for l in f.readlines(): print len(l) >>> f = open("myfile.txt") >>> for l in f: print len(l) readlines() returns a list of the lines in file A file is a iterator, producing new values as needed

Files are iterators  Iterators are supported wherever you can iterate over collections in containers (e.g., lists, tuples, dictionaries) >>> f = open("myfile.txt") >>> map(len, f.readlines()) [9, 21, 35, 43] >>> f = open("myfile.txt") >>> map(len, f) [9, 21, 35, 43] >>>

Like sequences, but…  Iterators are like sequences (lists, tuples), but…  The entire sequence is not manifested  Items produced one at a time when and as needed  The sequence can be infinite (e.g., all positive integers)  You can create your own iterators if you write a function to generate the next item

Example: fib.py class fibnum: def __init__(self): self.fn2 = 1 self.fn1 = 1 def next(self): # next() is the heart of any iterator # use of the following tuple to not only save lines of # code but insures that only the old values of self.fn1 and # self.fn2 are used in assigning the new values (self.fn1, self.fn2, oldfn2) = (self.fn1+self.fn2, self.fn1, self.fn2) return oldfn2 def __iter__(self): return self next() used to generate successive values Classes with an __iter__() method are iterators

Example: fib.py >>> from fib import * >>> f = fibnum() >>> for i in f:... print i... if I > 100: break … 144 >>>

Stopping an iterator class fibnum20: def __init__(self): self.fn2 = 1 # "f_{n-2}" self.fn1 = 1 # "f_{n-1}" def next(self): (self.fn1,self.fn2,oldfn2) = (self.fn1+self.fn2,self.fn1,self.fn2) if oldfn2 > 20: raise StopIteration return oldfn2 def __iter__(self): return self Raise this error to tell consumer to stop

Stopping an iterator >>> from fib import * >>> for i in fibnum20(): print i >>>

More tricks  The list function materializes an iterator’s values as a list >>> list(fibnum20()) [1, 1, 2, 3, 5, 8, 13  sum(), max(), min() know about iterators >>> sum(fibnum20()) 33 >>> max(fibnum20()) 13 >>> min(fibnum20()) 1

itertools  The itertools library module has some useful tools for working with iterators  islice() is like slice but works with streams produced by iterators >>> from itertools import * >>> list(islice(fibnum(), 6)) [1, 1, 2, 3, 5, 8] >>> list(islice(fibnum(), 6, 10)) [13, 21, 34, 55]  See also imap, ifilter, …

Python generators  Python generators generate iterators  They are more powerful and convenient  Write a regular function and instead of calling return to produce a value, call yield instead  When another value is needed, the generator function picks up where it left off  Raise the StopIteration exception or call return when you are doneStopIteration

Generator example def gy(): x = 2 y = 3 yield x,y,x+y z = 12 yield z/x yield z/y return >>> from gen import * >>> g = gy() >>> g.next() (2, 3, 5) >>> g.next() 6 >>> g.next() 4 >>> g.next() Traceback (most recent call last): File " ", line 1, in StopIteration >>>

Generator example: fib() def fib( ): fn2 = 1 fn1 = 1 while True: (fn1,fn2,oldfn2) = (fn1+fn2,fn1,fn2) yield oldfn2

Generator example: getword() def getword(fl): for line in fl: for word in line.split(): yield word return

Remembers stack, too def inorder(tree): if tree: for x in inorder(tree.left): yield x yield tree.dat for x in inorder(tree.right): yield x