Functions Functions being objects means functions can be passed into other functions: sort (list, key=str.upper)

Slides:



Advertisements
Similar presentations
CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
Advertisements

String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Lists Introduction to Computing Science and Programming I.
CSE (c) S. Tanimoto, 2007 Python Introduction 1 Introduction to Python for Artificial Intelligence Outline: Why Python? Interactive programming,
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
Python Control of Flow.
4. Python - Basic Operators
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
COMPSCI 101 Principles of Programming Lecture 25 – Nested loops, passing mutable objects as parameters.
Hey, Ferb, I know what we’re gonna do today! Aims: Use formatted printing. Use the “while” loop. Understand functions. Objectives: All: Understand and.
Built-in Data Structures in Python An Introduction.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
CONTENTS Processing structures and commands Control structures – Sequence Sequence – Selection Selection – Iteration Iteration Naming conventions – File.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Data Collections: Lists CSC 161: The Art of Programming Prof. Henry Kautz 11/2/2009.
Python Functions.
Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.
List comprehensions (and other shortcuts) UW CSE 160 Spring 2015.
Scope, Aliasing, Tuples & Mutability Intro2CS – week 4a 1.
Python Basics  Functions  Loops  Recursion. Built-in functions >>> type (32) >>> int(‘32’) 32  From math >>>import math >>> degrees = 45 >>> radians.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 3: Built-in functions.
Python Basics 본 자료는 다음의 웹 사이트를 정리 한 내용이니 참조 바랍니다. ythonBasics.
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
MapReduce, Dictionaries, List Comprehensions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where.
String and Lists Dr. José M. Reyes Álamo.
Higher Order Functions
COMPSCI 107 Computer Science Fundamentals
Excel IF Function.
Introduction to Higher Order (Functional Programming) (Python) part 2
Topics Introduction to Repetition Structures
Python: Control Structures
CS 115 Lecture 8 Structured Programming; for loops
Programming for Geographical Information Analysis: Core Skills
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.
Structured Programming; for loops Taken from notes by Dr. Neil Moore
CHAPTER FOUR Functions.
Functional.
Python Primer 2: Functions and Control Flow
File Handling Programming Guides.
Bryan Burlingame Halloween 2018
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
Chapter 10 Lists.
String and Lists Dr. José M. Reyes Álamo.
CSC1018F: Intermediate Python
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Programming for Geographical Information Analysis: Core Skills
G. Pullaiah College of Engineering and Technology
(more) Python.
Lambda Functions, MapReduce and List Comprehensions
CISC101 Reminders All assignments are now posted.
For loops Taken from notes by Dr. Neil Moore
The structure of programming
CHAPTER 4: Lists, Tuples and Dictionaries
Topics Introduction to Repetition Structures
Bryan Burlingame Halloween 2018
Python Review
The structure of programming
Topic: Loops Loops Idea While Loop Introduction to ranges For Loop
Functions So far we've been using functions from the builtin module, which is automatically loaded in most cases. Occasionally we've accessed functions.
Thinking procedurally
Declarative Languages
Class code for pythonroom.com cchsp2cs
Enclosing delimiters Python uses three style of special enclosing delimiters. These are what the Python documentation calls them: {} braces # Sometimes.
LOOP Basics.
© Sangeeta M Chauhan, Gwalior
Presentation transcript:

Functions Functions being objects means functions can be passed into other functions: sort (list, key=str.upper)

Builtins sorted(iterable, key=None, reverse=False) As we've seen, returns a copy of iterable, sorted. The optional arguments must be kwargs. "reverse" will sort in reverse if set to True. "key" should be a function within the data of one argument that generates a value for comparing during sorting. e.g. key = str.lower Will sort as if all strings are lowercase (otherwise all capitals are more important than all lowercase) . Basically, it calls the method and passes in each item, and sorts the returned values.

Builtins: lists map(function, iterable, …) Applies function to iterable as an iterator: for value in map(ord, ["A","B","C"]): # ord returns ACSII numbers print(value)

Lambdas "headless" or "anonymous" functions: i.e. short functions without names. Can only contain expressions, not statements (e.g. variable assignments). for square in map(lambda x: x**2, [1,2,3,4,5]): print(str(square)) # 1, 4, 9, 16, 25 for added in map(lambda x,y: x+y, [1,2,3,4,5],[1,2,3,4,5]): print(str(added)) # 2, 4, 6, 8, 10 b = "fire walk with me".split(" ") for a in map(lambda x: x[::-1], b): print(a) # erif klaw htiw em Beware adding lambdas to sequences as they get added as functions, not the result of functions: https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result

Reduce functools.reduce(function, iterable) Applies function cumulatively, so: def power(a, b): return a ** b import functools c = [2,3,4,5] d = functools.reduce(power, c) # (((2**3)**4)**5) print(d) or reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) # ((((1+2)+3)+4)+5) x is accumulator, y is each subsequent value. functools.update_wrapper: wraps around functions, passing in and returning parameters from another function that wraps around it.

Filter filter(function, sequence) filters out anything in sequence which function says is false. See also various iterators that apply functions to sequences in: https://docs.python.org/3/library/itertools.html

Decorators Enhance functions by wrapping them in code. e.g. Least Recently Used cache: @lru_cache(maxsize=32) def get_lat_long(location): return lookup(location) for c in "Leeds", "Manchester", "Sheffield", "Liverpool", "Leeds": print(get_lat_long(c)) Saves the last 32 runs of this function for quick repeat; "memoizing" For more, see: https://wiki.python.org/moin/PythonDecoratorLibrary https://docs.python.org/3/library/functools.html#functools.lru_cache

List comprehensions Essentially slightly easier and more flexible lambdas for setting up lists: listA = [1,2,3,4] listB = [2*x for x in listA] print(listB) # [2, 4, 6, 8] listB = [2* x for x in range(1:5)] print(listB) # [2, 4, 6, 8] listB = [2*x for x in listA if x % 2 == 0] # Even numbers only print(listB) # [4, 8] Can also be used to apply a function to everything in a list. listB = [ord(x) for x in listA]

Combinatorics List comprehensions can be used to generate combinations of values: listA = [(x, y) for x in [1,2,3] for y in ["a","b","c"]] print(listA) [(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), (3, 'b'), (3, 'c')] Essentially like developing tuples from nested for-each loops. For a tuple, you have to use a parenthesis here or you get a syntax error.

Generator expressions Generator expressions: exactly like list comprehensions, but generate an item at a time, so more memory efficient: listA = [1,2,3,4] notListB = (2* x for x in range(1,5)) for i in notListB : print(i) # Works print(notListB) # Doesn't print contents as don't exist.

Scope The scope of variables created inside lambdas, list comprehensions, and generator expresions is the function outlined, which some people like, as it doesn't create free variables slooping around the code afterwards. You can still use variables created earlier within these constructions, though obviously that would be bad practice if one wanted to isolate this code from side effects. From the docs: “A scope is a textual region of a Python program where a namespace is directly accessible. “Directly accessible” here means that an unqualified reference to a name attempts to find the name in the namespace.” “For example, assume we want to create a list of squares, like: >>>>>> squares = [] >>> for x in range(10): ... squares.append(x**2) ... >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] Note that this creates (or overwrites) a variable named x that still exists after the loop completes. We can calculate the list of squares without any side effects using: squares = list(map(lambda x: x**2, range(10))) or, equivalently: squares = [x**2 for x in range(10)] which is more concise and readable. A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] If the expression is a tuple (e.g. the (x, y) in the previous example), it must be parenthesized." “https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

Generator functions def count(): a = 0 while True: yield a # Returns control and waits next call. a = a + 1 b = count() print (next(b)) Where the condition is just set to True, they will generate infinite sequences. Must be attached to a variable so they are called from the same instance each time and the method level variables aren't wiped; this doesn't work: print (next(count())) Can also be used: for i in count(): print(i) To pass values into these, see: https://www.python.org/dev/peps/pep-0342/