Built-In Functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work.

Slides:



Advertisements
Similar presentations
Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
Advertisements

2/7/2008. >>> Overview * boolean * while * random * tuples.
CS 100: Roadmap to Computing Fall 2014 Lecture 0.
Week 2 Classes, Objects and lists review Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise.
Week 5 while loops; logic; random numbers; tuples Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except.
Classes Special thanks to Roy McElmurry, Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this.
Week 7 Lists Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed.
Unit 8 Classes and Objects; Inheritance Special thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work. Except.
Unit 5 while loops; logic; random numbers; tuples Special thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work.
Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.
Python Programming Chapter 14: Classes and Methods Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Introduction to Pyrex September 2002 Brian Quinlan
Operators in Python. Arithmetic operators Some operators in Python will look familiar (+, -, *, /) Others are new to you (%, //, **) All of these do work.
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.
Unit 2 Expressions and variables; for loops Special thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work. Except.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Higher Order Functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this.
Week 2 expressions, variables, for loops Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise.
Week 2 expressions, variables, for loops Special thanks to Scott Shawcroft, Ryan Tucker, Paul Beck, Hélène Martin, Kim Todd, John Kurkowski, and Marty.
Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions.
Midterm Review Important control structures Functions Loops Conditionals Important things to review Binary Boolean operators (and, or, not) Libraries (import.
Restrictions Objectives of the Lecture : To consider the algebraic Restrict operator; To consider the Restrict operator and its comparators in SQL.
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.
Rapid GUI Programming with Python and Qt Classes and Modules By Raed S. Rasheed Classes and Modules By Raed S. Rasheed 1.
Built-In Functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work.
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
CMPT 120 Topic: Searching – Part 2 and Intro to Time Complexity (Algorithm Analysis)
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
CS 115 Lecture 5 Math library; building a project Taken from notes by Dr. Neil Moore.
MapReduce, Dictionaries, List Comprehensions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where.
Map, List, Stack, Queue, Set Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted,
Adapted from slides by Marty Stepp and Stuart Reges
Fundamentals of Programming I Higher-Order Functions
Higher Order Functions
Intro2CS Tirgul 11.
Catapult Python Programming Wednesday Morning session
Types CSCE 314 Spring 2016.
Classes and Objects; Inheritance
George Mason University
Week 8 Classes and Objects
Catapult Python Programming Thursday Session
A lightening tour in 45 minutes
Higher-Order Procedures
while loops; file I/O; introduction to lists
Winter 2018 CISC101 11/22/2018 CISC101 Reminders
MapReduce, Dictionaries, List Comprehensions
Chapter 8 More on Strings and Special Methods
Week 7 Lists Special thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work. Except where otherwise noted, this.
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Week 8 Classes and Objects
Adapted from slides by Marty Stepp and Stuart Reges
Classes Special thanks to Roy McElmurry, Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this.
expressions, variables, for loops
expressions, variables, for loops
while loops; logic; random numbers; tuples
CSC1018F: Intermediate Python
Classes, Objects and lists
Topics Sequences Introduction to Lists List Slicing
Computer Science 111 Fundamentals of Programming I
Lambda Functions, MapReduce and List Comprehensions
Recursion Taken from notes by Dr. Neil Moore
Topics Sequences Introduction to Lists List Slicing
Winter 2019 CISC101 4/28/2019 CISC101 Reminders
Functions Functions being objects means functions can be passed into other functions: sort (list, key=str.upper)
CISC101 Reminders Assignment 3 due today.
Functional Programming
Class code for pythonroom.com cchsp2cs
Introduction to Python
Week 2 Classes and Objects
Presentation transcript:

Built-In Functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed under: http://creativecommons.org/licenses/by-nc-sa/3.0

Exceptions raise type(message) raise Exception(message) Exceptions AssertionError TypeError NameError ValueError IndexError SyntaxError ArithmeticError http://docs.python.org/library/exceptions.html#bltin-exceptions

__str__() We already know about the __str__() method that allows a class to convert itself into a string rectangle.py 1 2 3 4 5 6 7 8 9 class Rectangle: def __init__(self, x, y, width, height): self.x = x self.y = y self.width = width def __str__(self): return "(x=" + str(self.x) + ",y=" + str(self.y) + ",w=" + str(self.width) + ",h=" + str(self.height) + ")"

Underscored methods There are many other underscored methods that allow the built-in function of python to work Most of the time the underscored name matches the built-in function name Built-In Class Method str() __str__() len() __len__() abs() __abs__()

First Class Citizens For built-in types like ints and strings we can use operators like + and *. Our classes so far were forced to take back routes and use methods like add() or remove() Python is super cool, in that it allows us to define the usual operators for our class This brings our classes up to first class citizen status just like the built in ones

__truediv__(self, other) Underscored methods There are underscore methods that you can implement in order to define logical operations and arithmetic operations Binary Operators Comparison Operators Operator Class Method - __neg__(self,other) + __pos__(self, other) * __mul__(self, other) / __truediv__(self, other) Operator Class Method == __eq__(self,other) != __ne__(self, other) < __lt__(self, other) > __gt__(self, other) <= __le__(self, other) >= __ge__(self, other) N/A __nonzero__(self) Unary Operators Operator Class Method - __neg__(self) + __pos__(self) http://docs.python.org/reference/datamodel.html#sequence-types

ArrayIntList Operations Lets write a method that we could add to arrayintlist.py that would allow us to apply the /= operation to the list. The operation would simply divide all elements of the list by the argument of the operator Method: __itruediv__(self, num) Example run 1 2 3 4 print(int_list) #[1, 2, 3, 4, 5, 6, 7] int_list /= 2 print(int_list) #[0.0, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5]

Solution arrayintlist.py 1 2 3 4 5 6 7 def __itruediv__(self, num): if num == 0 : raise ArithmeticError(“Can't divide by zero.") for i in list(range(len(self))) : self.elementData[i] /= num return self

Lambda Sometimes you need a simply arithmetic function Its silly to write a method for it, but redundant not too With lambda we can create quick simple functions Facts Lambda functions can only be comprised of a single expression No loops, no calling other methods Lambda functions can take any number of variables Syntax: lambda param1,…,paramn : expression

Lambda Syntax lambda.py 1 2 3 4 5 6 7 8 9 #Example 1 #Example 1 square_func = lambda x : x**2 square_func(4) #return: 16 #Example 2 close_enough = lambda x, y : abs(x – y) < 3 close_enough(2, 4) #return: True #Example 3 def get_func(n) : return lambda x : x * n + x % n my_func = get_func(13) my_func(4) #return: 56

Higher-Order Functions A higher-order function is a function that takes another function as a parameter They are “higher-order” because it’s a function of a function Examples Map Reduce Filter Lambda works great as a parameter to higher-order functions if you can deal with its limitations

Filter filter(function, iterable) The filter runs through each element of iterable (any iterable object such as a List or another collection) It applies function to each element of iterable If function returns True for that element then the element is put into a List This list is returned from filter in versions of python under 3 In python 3, filter returns an iterator which must be cast to type list with list()

Filter Example Example 1 2 3 4 5 6 nums = [0, 4, 7, 2, 1, 0 , 9 , 3, 5, 6, 8, 0, 3] nums = list(filter(lambda x : x != 0, nums)) print(nums) #[4, 7, 2, 1, 9, 3, 5, 6, 8, 3]

Filter Problem NaN = float("nan") scores = [[NaN, 12, .5, 78, math.pi], [2, 13, .5, .7, math.pi / 2], [2, NaN, .5, 78, math.pi], [2, 14, .5, 39, 1 - math.pi]] Goal: given a list of lists containing answers to an algebra exam, filter out those that did not submit a response for one of the questions, denoted by NaN

Filter Problem Solution 1 2 3 4 5 6 7 8 9 NaN = float("nan") NaN = float("nan") scores = [[NaN, 12, .5, 78, pi],[2, 13, .5, .7, pi / 2], [2,NaN, .5, 78, pi],[2, 14, .5, 39, 1 - pi]] #solution 1 - intuitive def has_NaN(answers) : for num in answers : if isnan(float(num)) : return False return True valid = list(filter(has_NaN, scores)) print(valid2) #Solution 2 – sick python solution valid = list(filter(lambda x : NaN not in x, scores)) print(valid)

Map map(function, iterable, ...) Map applies function to each element of iterable and creates a list of the results You can optionally provide more iterables as parameters to map and it will place tuples in the result list Map returns an iterator which can be cast to list

Map Example Example 1 2 3 4 5 6 7 nums = [0, 4, 7, 2, 1, 0 , 9 , 3, 5, 6, 8, 0, 3] nums = list(map(lambda x : x % 5, nums)) print(nums) #[0, 4, 2, 2, 1, 0, 4, 3, 0, 1, 3, 0, 3]

Map Problem Goal: given a list of three dimensional points in the form of tuples, create a new list consisting of the distances of each point from the origin Loop Method: - distance(x, y, z) = sqrt(x**2 + y**2 + z**2) - loop through the list and add results to a new list

Map Problem Solution 1 2 3 4 5 6 7 8 9 from math import sqrt points = [(2, 1, 3), (5, 7, -3), (2, 4, 0), (9, 6, 8)] def distance(point) : x, y, z = point return sqrt(x**2 + y**2 + z**2) distances = list(map(distance, points))

Reduce reduce(function, iterable[,initializer]) Reduce will apply function to each element in iterable along with the sum so far and create a cumulative sum of the results function must take two parameters If initializer is provided, initializer will stand as the first argument in the sum Unfortunately in python 3 reduce() requires an import statement from functools import reduce

Reduce Example Example 1 2 3 4 5 6 7 nums = [1, 2, 3, 4, 5, 6, 7, 8] nums = list(reduce(lambda x, y : (x, y), nums)) Print(nums) #(((((((1, 2), 3), 4), 5), 6), 7), 8)

Reduce Problem Goal: given a list of numbers I want to find the average of those numbers in a few lines using reduce() For Loop Method: - sum up every element of the list - divide the sum by the length of the list

Reduce Problem Solution 1 2 3 4 nums = [92, 27, 63, 43, 88, 8, 38, 91, 47, 74, 18, 16, 29, 21, 60, 27, 62, 59, 86, 56] sum = reduce(lambda x, y : x + y, nums) / len(nums)