computational concepts toolbox
play

Computational Concepts Toolbox Data type: values, literals, - PDF document

Computational Concepts Toolbox Data type: values, literals, Higher Order Functions operations, Functions as Values Functions with functions as Expressions, Call Generators and Iterators argument expression


  1. Computational Concepts Toolbox • Data type: values, literals, • Higher Order Functions operations, – Functions as Values – Functions with functions as • Expressions, Call Generators and Iterators argument expression – Assignment of function values • Variables • Higher order function patterns • Assignment Statement David E. Culler – Map, Filter, Reduce • Sequences: tuple, list CS8 – Computational Structures in Data Science • Function factories – create and • Dictionaries return functions http://inst.eecs.berkeley.edu/~cs88 • Data structures • Recursion • Tuple assignment • Abstract Data Types Lecture 11 • Function Definition • Mutation Statement November 5, 2018 • Class • Conditional Statement – Object Oriented Programming • Iteration: list comp, for, http://bit.ly/cs88-fa18-L11 – Inheritance while • Exceptions • Lambda function expr. 10/29/18 UCB CS88 Sp18 L10 2 Administrative Issues Today: • Project 2 “Wheel” is out • Review Exceptions – Part I due 11/10 • Sequences vs Iterables • There will be no Project 3 • Using iterators without generating all the data • No lecture 11/12 due to holiday • Generator concept – There will be lab Friday 11/16 – Generating an iterator from iteration with yield • Magic methods – next – Iter • Iterators – the iter protocol • Getitem protocol • Is an object iterable? • Lazy evaluation with iterators 10/29/18 UCB CS88 Sp18 L10 3 10/29/18 UCB CS88 Sp18 L10 4 Summary of last week Key concepts to take forward • Approach creation of a class as a design • Classes embody and allow enforcement of ADT problem methodology – Meaningful behavior => methods [& attributes] • Class definition – ADT methodology • Class namespace – What’s private and hidden? vs What’s public? • Design for inheritance • Methods – Clean general case as foundation for specialized subclasses • Instance attributes (fields) • Use it to streamline development • Class attributes • Inheritance • Anticipate exceptional cases and unforeseen • Superclass reference problems – try … catch – raise / assert 10/29/18 UCB CS88 Sp18 L10 5 10/29/18 UCB CS88 Sp18 L10 6 1

  2. Handling Errors – try / except Exception (read 3.3) • Mechanism in a programming language to • Wrap your code in try – except statements declare and respond to “exceptional conditions” – enable non-local cntinuations of control try: • Often used to handle error conditions <try suite> except <exception class> as <name>: – Unhandled exceptions will cause python to halt and print a <except suite> stack trace ... # continue here if <try suite> succeeds w/o exception – You already saw a non-error exception – end of iterator • Exceptions can be handled by the program • Execution rule instead – <try suite> is executed first – assert, try, except, raise statements – If during this an exception is raised and not handled otherwise • Exceptions are objects! – And if the exception inherits from <exception class> – They have classes with constructors – Then <except suite> is executed with <name> bound to the exception • Control jumps to the except suite of the most recent try that handles the exception 10/29/18 UCB CS88 Sp18 L10 7 10/29/18 UCB CS88 Sp18 L10 8 Types of exceptions Exceptions are Classes • TypeError -- A function was passed the wrong number/type of argument class NoiseyException(Exception): def __init__(self, stuff): • NameError -- A name wasn't found print("Bad stuff happened", stuff) • KeyError -- A key wasn't found in a dictionary • RuntimeError -- Catch-all for troubles during interpretation • . . . try: return fun(x) except: raise NoiseyException((fun, x)) 10/29/18 UCB CS88 Sp18 L10 9 10/29/18 UCB CS88 Sp18 L10 10 Iterators - Notebook Iterable - an object you can iterate over • iterable : An object capable of yielding its members one at a time. • iterator : An object representing a stream of data. http://bit.ly/cs88-fa18-L11 • We have worked with many iterables as if they were sequences 10/29/18 UCB CS88 Sp18 L10 11 10/29/18 UCB CS88 Sp18 L10 12 2

  3. Define objects that behave like Functions that return iterables sequences • map • range • zip • These objects are not sequences. • If we want to see all of the elements at once, we need to explicitly call list() or tuple() on them 10/29/18 UCB CS88 Sp18 L10 13 10/29/18 UCB CS88 Sp18 L10 14 Generators: turning iteration into an Nest iteration interable • Generator functions use iteration (for loops, while loops) and the yield keyword • Generator functions have no return statement, but def all_pairs(x): for item1 in x: they don’t return None for item2 in x: • They implicitly return a generator object yield(item1, item2) • Generator objects are just iterators def squares(n): for i in range(n): yield (i*i) 10/29/18 UCB CS88 Sp18 L10 15 10/29/18 UCB CS88 Sp18 L10 16 Next element in generator iterable Iterators – iter protocol • Iterables work because they have some "magic • In order to be iterable , a class must implement methods" on them. We saw magic methods when the iter protocol we learned about classes, • The iterator objects themselves are required to • e.g., __init__, __repr__ and __str__. support the following two methods, which together form the iterator protocol: • The first one we see for iterables is __next__ – __iter__() : Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements. • iter( ) – transforms a sequence into an iterator – This method returns an iterator object, Iterator can be self – __next__() : Return the next item from the container. If there are no further items, raise the StopIteration exception. • Classes get to define how they are iterated over by defining these methods 10/29/18 UCB CS88 Sp18 L10 17 10/29/18 UCB CS88 Sp18 L10 18 3

  4. Getitem protocol Determining if an object is iterable • Another way an object can behave like a sequence • from collections.abc import Iterable is indexing : Using square brackets “[ ]” to access • isinstance([1,2,3], Iterable) specific items in an object. • Defined by special method: __ getitem__ (self, i) • This is more general than checking for any list of – Method returns the item at a given index particular type, e.g., list, tuple, string... 10/29/18 UCB CS88 Sp18 L10 19 10/29/18 UCB CS88 Sp18 L10 20 Computational Concepts Toolbox • Data type: values, literals, • Higher Order Functions operations, – Functions as Values – Functions with functions as • Expressions, Call argument expression – Assignment of function values • Variables • Higher order function patterns • Assignment Statement, – Map, Filter, Reduce Tuple assignment • Function factories – create and • Sequences: tuple, list return functions • Dictionaries • Recursion • Function Definition • Abstract Data Types Statement • Mutation • Conditional Statement • Class & Inheritance • Iteration: list comp, for, while • Exceptions • Lambda function expr. • Iterators & Generators 10/29/18 UCB CS88 Sp18 L10 21 4

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend