List Comprehensions Problem: given a list of prices, generate a new list that has a 20% discount to each. Formally: input: list of old prices; output:

Slides:



Advertisements
Similar presentations
F28PL1 Programming Languages Lecture 14: Standard ML 4.
Advertisements

Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 8 Fruitful Functions 05/02/09 Python Mini-Course: Day 2 - Lesson 8 1.
Order of operators: x ** y x * y, x / y, x // y, x % y x + y, x - y
Sorting, Sets, and Selecting - Ed. 2. and 3.: Chapter 10 - Ed. 4.: Chapter 11.
CS 116 Tutorial 2 Functional Abstraction. Reminders Assignment 2 is due this Wednesday at Noon.
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 4. Outline Repeated f Accelerating computations – Fibonacci Let and let* Recursion examples – Palindrome? – Log.
ITERATION CSC 171 FALL 2004 LECTURE 10. Simple Branching If (test){ A;} start end A; test.
Revision Using Recursion1 Recursion. Revision Using Recursion2 Recall the Recursion Pattern Recursion: when a method calls itself Classic example--the.
INTRODUCTION TO PYTHON PART 3 - LOOPS AND CONDITIONAL LOGIC CSC482 Introduction to Text Analytics Thomas Tiahrt, MA, PhD.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Computer Science 209 The Strategy Pattern II: Emulating Higher-Order Functions.
Tuples and Lists Lecture 3, Programmeringsteknik del A.
JavaScript Lecture 6 Rachel A Ober
Solving N-Queens in Clojure
PPT3. Quick function:  Write a function that checks to see if a number is even or not.  What TYPE does this return?
EECS 110: Lec 5: List Comprehensions Aleksandar Kuzmanovic Northwestern University
The building blocks of functional computing data, sequences conditionals recursion CS 121 today List Comprehensions map and applications.
+ 7.2 The Real nth Roots of a Number How many values in the domain of f are paired with the value in the range? That is, how many x values satisfy.
Functional Programming in Scheme and Lisp.
EECS 110: Lec 4: Functions and Recursion Aleksandar Kuzmanovic Northwestern University
Math – What is a Function? 1. 2 input output function.
Higher Order Functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this.
Hossain Shahriar Announcement and reminder! Tentative date for final exam need to be fixed! We have agreed so far that it can.
TUTORIAL 8 Generative Recursion. Reminders  Deadline of midterm remark  Assignment 7 due Wed, Mar 18 th.
Loops ! We've seen variables change in-place before: [ x*6 for x in range(8) ] [ 0, 6, 12, 18, 24, 30, 36, 42 ] remember range ?
EECS 110: Lec 10: Definite Loops and User Input Aleksandar Kuzmanovic Northwestern University
COP 2510 Chapter 6 - Functions. Random function (randint) #import the desired function import random #integer random number in the range of 1 through.
1 CS 177 Week 6 Recitation Slides Review for Midterm Exam.
160 as a product of its prime factors is 2 5 x 5 Use this information to show that 160 has 12 factors.
Math – Introduction to Functions 1. Let’s look at a graph of fuel prices (in $ per liter) over time… 2.
Chapter 1 Review - Get a whiteboard and marker per pair - Take out a blank sheet of paper.
Introduction to Concepts in Functional Programming CS16: Introduction to Data Structures & Algorithms Thursday, April 9,
EECS 110: Lec 10: Definite Loops and User Input
CS314 – Section 5 Recitation 10
Recursive Algorithms ICS 6D Sandy Irani.
Higher Order Functions
Intro2CS Tirgul 11.
Python unit_4 review Tue/Wed, Dec 1-2
Basic Scheme February 8, 2007 Compound expressions Rules of evaluation
Algorithmic complexity: Speed of algorithms
EECS 110: Lec 5: List Comprehensions
EECS 110: Lec 5: List Comprehensions
Be A programmer in Steps
CompSci 101 Introduction to Computer Science
CompSci 101 Introduction to Computer Science
Standard Deviation.
Standard Deviation.
Building Java Programs
EECS 110: Lec 10: Definite Loops and User Input
Lists in Python.
Sharing, mutability, and immutability
MapReduce, Dictionaries, List Comprehensions
Standard Deviation.
It’s a beautiful day, don’t let it get away.
Lecture #8 מבוא מורחב.
Sharing, mutability, and immutability
EECS 110: Lec 4: Functions and Recursion
Algorithmic complexity: Speed of algorithms
© School Improvement Liverpool Limited 2018
Programming Languages
Algorithmic complexity: Speed of algorithms
Numerical Representation of Strings
National Central University, Taiwan
Introduction to the Lab
Standard Deviation.
Recursion Review Spring 2019 CS 1110
Class code for pythonroom.com cchsp2cs
functions are also data! other functions as input!
Standard Deviation.
Lecture 6 - Recursion.
Presentation transcript:

List Comprehensions Problem: given a list of prices, generate a new list that has a 20% discount to each. Formally: input: list of old prices; output: list of new prices Can solve it recursively. Or can use List comprehensions. Syntax for list comprehension: [x*0.8 for x in old_price] >>> price = [10, 20, 30, 100] >>> [x*0.8 for x in price] [8.0, 16.0, 24.0, 80.0] List comprerehsion is a transformation applied to every element of the list. The result of this operation is a list containing transformed elements.

List Comprehensions >>> [ 2*x for x in [0,1,2,3,4,5] ] What is going on here? List Comprehensions >>> [ 2*x for x in [0,1,2,3,4,5] ] [0, 2, 4, 6, 8, 10] >>> [ y**2 for y in range(6) ] [0, 1, 4, 9, 16, 25] >>> [ c == 'a' for c in 'go away!' ] [False, False, False, True, False, True, False, False] Double all prices Give me a square of all numbers from 0 to 6 >>> [x for x in 'go away!’ if x == ‘a’] [‘a’, ‘a’]

List Comprehensions >>> [ 2*x for x in [0,1,2,3,4,5] ] [0, 2, 4, 6, 8, 10]] Any operation you want to apply to each element of the list name that takes on the value of each element in turn the list (or string) any name is OK! >>> [ y**2 for y in range(6) ] [0, 1, 4, 9, 16, 25] >>> [ c == 'a' for c in 'go away!' ] [False, False, False, True, False, True, False, False] >>> [x for x in 'go away!’ if x == ‘a’] [‘a’, ‘a’]

Raw recursion vs. list comprehensions my_len(t) def my_len(t): if t == []: return 0 else: return 1 + my_len(t[1:]) def my_len(t): list_comp = [1 for x in t] return sum(list_comp) listComp = [1 for x in list] return sum(listComp) For every element of the list, we are going to generate a 1, that is, a marker that the element is present. It’s like I am going to put a pebble in a jar for every element that I see. What remains then is to just count the pebbles in the end. ‘’’ or simply ‘’’ def my_len(t): return sum([1 for x in t])

Raw recursion vs. list comprehensions count_vows(s) # of vowels def count_vows(s): if len(s) == 0: return 0 else: if s[0] not in 'aeiou': return count_vows(s[1:]) return 1 + count_vows(s[1:]) Lst= [x in ‘aeiou’ for x in s] The operation is applied to each element of the string. Will generate a list with containing True value for each vowel and False value for each consonant. Interestingly, in Python True value corresponds to integer 1, and False value corresponds to integer 0. So again, I have a one, or a pebble, for each vowel, and it remains to count them. def count_vows(s): return sum([1 for x in s if x in ‘aeiou’])

List comprehension with filtering def only_evens(t): return [x for x in t if is_even(x)] list comprehension with filter >>>only_evens([13, 2, 5, 6, 9]) [2, 6] Note: isEven def isEven(n): return n %2 == 0 The result is also a list but now it’s filtered, only elements that satisfy if condition are making it to the final list

More examples of comprehensions Generate all powers of 2 from 0 to 10 my_list = [2** i for i in range (10) ] # [1 ,2 ,4 ,8 ,16 ,...2^9] Given a list, get a list of square roots of its elements from math import sqrt my_list = [sqrt (x) for x in otherlist ] # produced a squared list Generate a list of odd numbers from 0 to 10 – first let’s generate a list of all numbers Then generate a list of odd numbers If there is time: demonstrate why ‘list’ is not a good name for the list Remind that next class is going to be in the lab Interesting. Generate a list of odd numbers from 0 to 10 list = [x for x in range (10) if x % 2 == 1] # [1, 3, 5, 7, 9]