Lecture 37: List Comprehensions

Slides:



Advertisements
Similar presentations
Chapter 5 Section 4 The Multiplication Principle.
Advertisements

Activity 1 Activity 2 Index Student Activity 1: Tossing a coin Student Activity 2: Tossing two coins.
Randomisation in Coin Tosses We can’t predict the result of one coin toss with certainty but we have an expectation that with 10 tosses we will get about.
MOM! Phineas and Ferb are … Aims:
 From here to there and back again  Counts steps  Measures distance.
Dependent and Independent Events. Events are said to be independent if the occurrence of one event has no effect on the occurrence of another. For example,
Introduction to Probability © Christine Crisp “Teach A Level Maths” Statistics 1.
Built-in Data Structures in Python An Introduction.
Iterators, Linked Lists, MapReduce, Dictionaries, and List Comprehensions... OH MY! Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their.
Sigma Notation A compact way of defining a series A series is the sum of a sequence.
What is Probability?. The Mathematics of Chance How many possible outcomes are there with a single 6-sided die? What are your “chances” of rolling a 6?
IS2802 Introduction to Multimedia Applications for Business Lecture 3: JavaScript and Functions Rob Gleasure
Computer Science I: Understand how to evaluate expressions with DIV and MOD Random Numbers Reading random code Writing random code Odds/evens/…
Probability Experiments Probability experiment An action, or trial, through which specific results (counts, measurements, or responses) are obtained. Outcome.
Concepts of Algorithmic Thinking Iterations, or Loops Once is not Enough D.A. Clements, Lecturer Information School 2/23/2016 D.A. Clements, MLIS, UW Information.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 6 Arrays.
Random Variables If  is an outcome space with a probability measure and X is a real-valued function defined over the elements of , then X is a random.
Probability Distribution. Probability Distributions: Overview To understand probability distributions, it is important to understand variables and random.
MapReduce, Dictionaries, List Comprehensions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where.
Nested Loops CS303E: Elements of Computers and Programming.
1 What Is Probability?. 2 To discuss probability, let’s begin by defining some terms. An experiment is a process, such as tossing a coin, that gives definite.
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
CSc 110, Autumn 2016 Lecture 26: Sets and Dictionaries
Tutorial 3 Working with Formulas and Functions
Higher Order Functions
What Is Probability?.
Copyright © Cengage Learning. All rights reserved.
Lecture 35: List Comprehensions
CSc 110, Spring 2017 Lecture 29: Sets and Dictionaries
© 2016 Pearson Education, Ltd. All rights reserved.
Adapted from slides by Marty Stepp and Stuart Reges
Arrays: Checkboxes and Textareas
Experimental Probability
Box models Coin toss = Head = Tail 1 1
CSc 110, Autumn 2016 Lecture 27: Sets and Dictionaries
Lecture 34: List Comprehensions
CSC241: Object Oriented Programming
CSc 110, Spring 2017 Lecture 28: Sets and Dictionaries
CSc 110, Spring 2018 Lecture 32: Sets and Dictionaries
CSc 110, Autumn 2017 Lecture 31: Dictionaries
CSc 110, Autumn 2017 Lecture 30: Sets and Dictionaries
The relational operators
Introduction to Python
CSc 110, Spring 2018 Lecture 33: Dictionaries
© Akhilesh Bajaj, All rights reserved.
CSc 110, Spring 2017 Lecture 5: Constants and Parameters
MAT 142 Lecture Video Series
Chapter 5 Arrays Introducing Arrays
CSc 110, Autumn 2016 Lecture 5: Loop Figures and Constants
Java Programming Loops
Chapter 2: Working with Formulas and Functions
Dry run Fix Random Numbers
CSc 110, Spring 2018 Lecture 7: input and Constants
Adapted from slides by Marty Stepp and Stuart Reges
Basic String Operations
Probability Simulations
Looping III (do … while statement)
Chapter 10 Counting Methods 2012 Pearson Education, Inc.
Simulation Discrete Variables.
Put the dots on the shift keys.
Lambda Functions, MapReduce and List Comprehensions
I know my CAPITAL LETTERS.
Chapter 10 Counting Methods.
Programming Logic and Design Fifth Edition, Comprehensive
Entropy is Your Friend.
Matlab Basics.
Computer Science I: Get out your notes.
Ordered Pair – (11 - 2) CS-708.
A drag and drop exercise can be created using Word quite easily using tables, text boxes and ensuring the document is saved properly.
Presentation transcript:

Lecture 37: List Comprehensions CSc 110, Spring 2018 Lecture 37: List Comprehensions

Exercise Write a program that allows a user to ask the distance between two friends. If person 1 and person 2 are friends then they are distance 0 If person 2 is friends with a friend of person 2 they are distance 1 What structure is appropriate for this problem?

List comprehensions [expression for element in list] A compact syntax that can replace loops that alter lists Applies the expression to each element in the list You can have 0 or more for or if statements

List comprehensions vec = [2, 4, 6] result = [3 * x for x in vec] print(result) # [6, 12, 18] result2 = [3 * x for x in vec if x > 3] print(result2) # [12, 18] result3 = [3 * x for x in vec if x < 2] print(result3) # [] Notice the contents of vec do not change

List comprehensions More than one element can be generated from each element in the original list vec = [2, 4, 6] result = [[x, x ** 2] for x in vec] print(result) # [[2, 4], [4, 16], [6, 36]] result2 = [(x, x ** 2) for x in vec] print(result2) # [(2, 4), (4, 16), (6, 36)]

Exercise Given a list a words in any casing, create a new list containing the words with the first letter capitalized and the rest lowercase. [word[0].upper() + word[1:].lower() for word in words]

List comprehensions An if statement can be added to the end to allow selecting only certain elements of the original list [expression for element in list if condition] vec = [2, 3, 4, 5, 6] result = [x for x in vec if x % 2 == 0] print(result) # [2, 4, 6] result2 = [x ** 2 for x in vec if x % 2 == 0 and x < 5] print(result2) # [4, 16]

Exercise Create a list with all words from an original text list that are over 3 letters long [word for word in text if len(word) > 3]

Exercise Count occurrences of "money" in an email text We counted word occurrences earlier this semester using loops Word counts can help us do things like identify spam emails len([1 for word in email if word == 'money'])

Exercise Extend the solution to the last problem to count occurrences of any word that occurs in a list called spam_words len([1 for word in email if word in spam_words])

Exercise Create a list that’s contents simulates a series of 10 coin tosses (generate a 1 to represent heads, 0 for tails) [randint(0, 1) for i in range(0, 10)]

Nested List Comprehension You can write a list comprehension to go over a list of lists matrix = [[0,1,2,3], [4,5,6,7], [8,9,10,11]] flattened = [i for row in matrix for i in row] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

Set Comprehension Set comprehensions work just like list comprehensions except that they are surrounded by {} vec = [2, 4, 6] result = {3 * x for x in vec} print(result) # {6, 12, 18} vec2 = [2, 4, 6, 2, 2, 4, 3] result2 = {3 * x for x in vec2} print(result2) # {6, 12, 18, 9}

Dictionary Comprehension Dictionary comprehensions work similarly to list and set comprehensions except that they are surrounded by {} and generate key, value pairs original = {'two' : 2, 'four' : 4, 'six' : 6} {value: key for key, value in original.items()} What does this comprehension do?