 1 Loop and Set operations. Creating a loop Loops are used to repeat a computation. Let’s see the example of factorial computation. Let’s compute 10!

Slides:



Advertisements
Similar presentations
2.1 Program Construction In Java
Advertisements

CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Some non-recursive tricks. The Lambda expression. More on Let, Let*, apply and funcall.
Static Single Assignment CS 540. Spring Efficient Representations for Reachability Efficiency is measured in terms of the size of the representation.
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.
Programming Logic and Design, Third Edition Comprehensive
Grouping Objects Arrays and for loops. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Fixed-Size Collections.
ITERATIVE CONSTRUCTS: DOLIST Dolist is an iterative construct (a loop statement) consisting of a variable declaration and a body The body states what happens.
Imperative programming public int factorial (int N){ int F = 1; for(X=N; X>1; X-- ){ F= F*X; } return F; } Functional programming (defun factorial(N) (cond.
CS150 Introduction to Computer Science 1
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
1 Python Chapter 4 Branching statements and loops © Samuel Marateck 2010.
Fibonacci Problem Solving and Thinking in Engineering Programming H. James de St. Germain.
 1 String and Data Processing. Sequential Processing Processing each element in a sequence for e in [1,2,3,4]: print e for c in “hello”: print c for.
Chapter 4 MATLAB Programming Combining Loops and Logic Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Fruitful functions. Return values The built-in functions we have used, such as abs, pow, int, max, and range, have produced results. Calling each of these.
Python November 28, Unit 9+. Local and Global Variables There are two main types of variables in Python: local and global –The explanation of local and.
Fall Week 3 CSCI-141 Scott C. Johnson.  Say we want to draw the following figure ◦ How would we go about doing this?
Haskell. 2 GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using.
Functional Programming in Scheme and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
Python Programming Chapter 6: Iteration Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
CS1315: Introduction to Media Computation Referencing pixels directly by index number.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
Solving N-Queens in Clojure
 Expression Tree and Objects 1. Elements of Python  Literals, Strings, Tuples, Lists, …  The order of file reading  The order of execution 2.
Built-in Data Structures in Python An Introduction.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
David Stotts Computer Science Department UNC Chapel Hill.
Ch. 10 For Statement Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2012.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
© Kenneth C. Louden, Chapter 11 - Functional Programming, Part III: Theory Programming Languages: Principles and Practice, 2nd Ed. Kenneth C. Louden.
C++ / G4MICE Course Session 2 Basic C++ types. Control and Looping Functions in C Function/method signatures and scope.
Python 101 Dr. Bernard Chen University of Central Arkansas PyArkansas.
Copyright © Curt Hill The IF Revisited If part 4 Style and Testing.
CSE Winter 2008 Introduction to Program Verification January 15 tautology checking.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Conditionals Opening Discussion zWhat did we talk about last class? zDo you have any questions about the assignment? zPass by value limitations.
CPSC 217 T03 Week VI Part #1: A2 Post-Mortem and Functions Hubert (Sathaporn) Hu.
Repetition Intro to Computer Science CS1510 Dr. Sarah Diesburg.
CIT 590 Intro to Programming Lecture 4. How are assignments evaluated Pay attention to what the HW says it is trying to teach you about ‘modular programming’
Whole numbers and numeration Math 123. Manipulatives I am going to let you play with base blocks. Each group will get a different base to work with, but.
Control flow Ruth Anderson UW CSE 160 Spring
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Revision on Matrices Finding the order of, Addition, Subtraction and the Inverse of Matices.
CISC105 – General Computer Science Class 4 – 06/14/2006.
CSC 4630 Meeting 17 March 21, Exam/Quiz Schedule Due to ice, travel, research and other commitments that we all have: –Quiz 2, scheduled for Monday.
CS162 - Topic #12 Lecture: –Arrays with Structured Elements defining and using arrays of arrays remember pointer arithmetic Programming Project –Any questions?
Control flow Ruth Anderson UW CSE 160 Winter
CSC 4630 Perl 3 adapted from R. E. Beck. Problem But we worked on it first: Input: Read from a text file named in a command line argument Output: List.
Arithmetic Sequences. Arithmetic sequence Before talking about arithmetic sequence, in math, a sequence is a set of numbers that follow a pattern. We.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
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.
String and Lists Dr. José M. Reyes Álamo.
UMBC CMSC 104 – Section 01, Fall 2016
Python Loops and Iteration
Haskell.
Miscellaneous Items Loop control, block labels, unless/until, backwards syntax for “if” statements, split, join, substring, length, logical operators,
While Loops in Python.
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.
Control Structure Senior Lecturer
Coding Concepts (Basics)
String and Lists Dr. José M. Reyes Álamo.
Conditional and iterative statements
Recursion Taken from notes by Dr. Neil Moore
For loops Taken from notes by Dr. Neil Moore
Functions Functions being objects means functions can be passed into other functions: sort (list, key=str.upper)
While Loops in Python.
Presentation transcript:

 1 Loop and Set operations

Creating a loop Loops are used to repeat a computation. Let’s see the example of factorial computation. Let’s compute 10! = 10*9*8*…*1 2

Creating a loop 1) Make a list of evaluation step by step 10 10*9 (10*9)*8 ((10*9)*8)*7 … 3

Creating a loop 2) Assign intermediate results into variables f10 = 10 f9 = 10*9 f8 = (10*9)*8 f7 = ((10*9)*8)*7 … f1 = ((10*9)*8)*7* … *1 4

Creating a loop 3) Replace an expression with an equivalent variable. f10 = 10 f9 = f10*9 f8 = f9*8 f7 = f8*7 … f1 = f2*1 5 f10 = 10 f9 = 10*9 f8 = (10*9)*8 f7 = ((10*9)*8)*7 … f1 = ((10*9)*8)*7* … *1

Creating a loop 4) Check if variables can be reduced into a single variable. f10 = 10 f10 = f10*9 f10 = f10*8 f10 = f10*7 … f10 = f10*1 6 f = 10 f = f*9 f = f*8 f = f*7 … f = f*1 If possible, use a meaningful variable name

Creating a loop 5) Identify numbers or values which changes. factorial = 10 factorial = factorial*9 factorial = factorial*8 factorial = factorial*7 … factorial = factorial*1 7

Creating a loop 6) Find a general formula or sequence to generate those values. factorial = 10 factorial = factorial*9 factorial = factorial*8 factorial = factorial*7 … factorial = factorial*1 8

Creating a loop 7) In this example, the changing sequence is [10,9,8,…,1] factorial = 10 factorial = factorial*9 factorial = factorial*8 factorial = factorial*7 … factorial = factorial*1 9

Creating a loop 8) Replace values with a variable; L = [10,9,8,…,1] factorial = L[0] factorial = factorial*L[1] factorial = factorial*L[2] factorial = factorial*L[3] … factorial = factorial*L[9] 10

Creating a loop 9) Initialize the output variable and make the recurring formula as general as possible factorial = 1 factorial = factorial*L[0] factorial = factorial*L[1] factorial = factorial*L[2] factorial = factorial*L[3] … factorial = factorial*L[9] 11

Creating a loop 10) Introduce for or while statement to make a loop for recurrences L = [10,9, …,1] factorial = 1 for e in L: factorial = factorial * e 12

Understanding a loop L = [10,9, …,1] factorial = 1 for e in L: factorial = factorial * e Identify counter variables 13

Understanding a loop L = [10,9, …,1] factorial = 1 for e in L: factorial = factorial * e Here, the counter variable is e; [10, 9, …, 1] 14

Understanding a loop L = [10,9, …,1] factorial = 1 for e in L: factorial = factorial * e Expand the repeated block with examples of counter variables 15

Understanding a loop L = [10,9, …,1] factorial = 1 factorial = factorial * 10 factorial = factorial * 9 factorial = factorial * 8 … Expand the repeated block with examples of counter variables 16

Understanding a loop L = [10,9, …,1] factorial = 1 factorial = factorial * 10 factorial = factorial * 9 factorial = factorial * 8 … Replace the overwritten variable with actual expressions 17

Understanding a loop L = [10,9, …,1] factorial = 1 factorial = 1 * 10 factorial = (1 * 10) * 9 factorial = ((1 * 10) * 9) * 8 … Find out the last expression! 18

Understanding a loop L = [10,9, …,1] factorial = 1 factorial = 1 * 10 … factorial = 1*10*9*8*7* … *2*1 = 10! If possible, think an equivalent mathematical expression 19

Example: conditional counting Count 2 from [2,3,1,0,2,1,0,4,2] Devise a function which works with one or two arguments. Sometimes, it is not obvious at first. Then, start from the end some_func(, 2) = 3; (for this case) Guess the signature of some_func: some_func(, ) = 20

Example: conditional counting The signature is … some_func(, ) = Guess/Imagine what will happen with specific examples some_func(,2) = + 1; why? some_func(,1) = ; why? Find out the missing type ; 21

Example: conditional counting Now, the signature is complete some_func(, ) = Let’s try to draw specific exemplar cases: some_func(,2) = + 1 some_func(,1) = Introduce a variable, namely, count, to replace the type 22

Example: conditional counting Concrete exemplar cases are: some_func(count,2) = count + 1 some_func(count,1) = count Wire exemplar cases with if statement some_func(count, n) = count + 1 # if n equals to 2 count # if n is not 2 23

Example: conditional counting Define a function based on the previous analysis def count_2(count, n): if n == 2: return count + 1 return count 24

Example: conditional counting Test if it can be applied with an example list as we did at the beginning of this class. L = [1,2,0] count_2(0,1) = 0 ; note the initial counter 0 count_2(0,2) = 1 ; this zero is different from the above count_2(1,0) = 1 ;  count_2(count_2(count_2(0,1),2),0) 25

Example: conditional counting L = [1,2,0] count_2(0,1) = 0 # note the initial counter 0 count_2(0,2) = 1 # this zero is different from the above count_2(1,0) = 1 # Identify changing variable; 1, 2, 0 Identify accumulated values (or production values): 0,1,1 26

Example: conditional counting L = [1,2,0] count = count_2(0,L[0]) = 0 count = count_2(0,L[1]) = 1 count = count_2(1,L[2]) = 1 Replace changing values with a loop variable. Replace the accumulating value with a variable. 27

Example: conditional counting L = [1,2,0] count = 0 for e in L: count = count_2(count, e) Introduce a for or while statement. However, sometimes, the function is not necessary. Try to expand the function within the loop 28

Example: conditional counting Do you remember? def count_2(count, n): if n == 2: return count + 1 return count 29

Example: conditional counting L = [1,2,0] count = 0 for e in L: if e == 2: count = count + 1 Maybe this is more comprehensive than before. Loops and function calls are essentially identical. Loops are successive function calls! 30

Example: conditional counting How to generalize this example? What is the base operation? ‘x == 2’ Replace the base operation with a function def test_2(x): return x==2 31

Example: conditional counting Make a big function; count_if(L, func) The signature of the function is … count_if(, )  Counting 2 is calling count_if(L, test_2) def test_2(x): return x==2 32

Example: conditional counting The complete version of count_if(L,cond) def count_if(L, cond): count = 0 for e in L: if cond(e): count = count + 1 return count count_if(L, test_2) # will count 2s in L 33

Example: conditional counting See some demo! 34

Example: conditional collection The variation of count_if(L,cond) def collect_if(L, cond): collection = [] for e in L: if cond(e): collection = collection + [e] return collection 35

Lambda Function Anonymous function lambda x: x + 2 Equivalent to def plus2(x): return x+2 Just a short form of a function without name and return 36

Example: conditional collection Collecting 2 or 3’s multiples: collect_if(range(1,100), \ lambda x: x%2==0 or x%3==0) Intersection of two lists L1 and L2: collect_if(L1, \ lambda x: x in L2) 37

Example: conditional collection Sometimes, we need [ f(x0), f(x1), …, f(xn) ] from [x0,x1,…,xn] Let’s tweak collect_if(L, cond) def collect_mapping_if(L,mapping,cond=None): out = [] for e in L: if cond and cond(e): out.append(mapping(e)) return out 38

Example: conditional collection See some demo 39

List Comprehension List comprehension is nothing but a collect_mapping_if. [ x for x in L ] is equivalent to collect_mapping_if(L,lambda x: x,None) [ x*x for x in L ] is equivalent to collect_mapping_if(L,lambda x:x*x) [ x for x in range(0,10) if x==2 ] is equivalent to collect_mapping_if(L,lambda x:x, lambda x:x==2) 40

List Comprehension See some demo List comprehensions could be nested 41

Can you? Can you reduce an expression into a variable? Can you expand a variable or a function into an embedded form? Then, you are free! 42

Revisiting Set operations What’s the definition of the intersection? As seen before, (but watch out for duplicates!) collect_if(L1, lambda x: x in L2)  for e in L1: if e in L2: o.append(e) 43

Revisiting Set operations What’s the definition of the subtraction? As seen before, subtract(L1,L2)  collect_if(L1, lambda x: x not in L2)  for e in L1: if (e not in L1) : o.append(e) 44

Revisiting Set operations What’s the definition of the union? The union is somewhat different because of duplicates. union(L1,L2) = L1 + subtract(L2,L1) or union(L1,L2) = L1+L2 – intersect(L1,L2) 45

Revisiting Set operations Using the list comprehension, intersection(L1,L2)  collect_if(L1, lambda x: x in L2)  [ e for e in L1 if x in L2 ] subtract(L1,L2)  collect_if(L1, lambda x: x not in L2)  [ e for e in L1 if x not in L2 ] 46

Revisiting the unique operation Finding the unique elements in a list L. Let’s define a function to determine an element’s uniqueness. For example, L = [ 1, 2, 1 ]; unique(L)  [1, 2] is_unique(, 1)  [ 1 ] is_unique(, 2)  [ 1, 2 ] is_unique(, 1)  [ 1, 2 ] 47

Revisiting the unique operation is_unique(, 1)  [ 1 ] is_unique(, 2)  [ 1, 2 ] is_unique(, 1)  [ 1, 2 ] Replace with previous results; is_unique(, 1)  [1] is_unique([1], 2)  [1, 2] is_unique([1,2], 2)  [1, 2] There is a pattern. Can you wire the above with if- statement? 48

Revisiting the unique operation is_unique(, 1)  [1] # don’t know is_unique([1], 2)  [1, 2] # 2 was added because 2 is not in [1] is_unique([1, 2], 2)  [1, 2] # 2 was not added because 2 is in [1,2] It’s somewhat complicated though is_unique(, 1)  [1] is_unique(, 2)  add 2 if has no 2 is_unique(, 2)  don’t add 2 if has 2 Do you see what I am seeing? 49

Revisiting the unique operation is_unique(, 1)  [1] is_unique(, 2)  add 2 if has no 2 is_unique(, 2)  don’t add 2 if has 2 We can code the above analysis as … def is_unique(L, e): if e not in L: return L + [e] # or L.append(e) Let’s expand with some examples: is_unique(is_unique(is_unique(?,1),2),2) 50

Revisiting the unique operation is_unique(is_unique(is_unique(?,1),2),2)  [1,2] I believe that you can make a loop from the above uniques = [] for e in L: uniques = is_unique(uniques, e) Let’s expand with the is_unique function uniques = [] for e in L: if e not in uniques: uniques.append(e) 51

Loops and Set operations Are these make sense to you? 52

One more thing! 53 List indexing An element of a list or a part of a list can be easily accessed by indexing [] operator. For example L = [1,2,3] print L[0], L[1], L[-1], L[-3] # will print 1, 2, 3, 1 print L[0:2], L[1:], L[:2], L[0:3:2], L[::-1] >>> [1,2], [2,3], [1,2], [1,3], [3,2,1]

54 Be prepared! Indexing is an evil… Sometimes there is no way to escape or avoid, unfortunately…

55 Next week, We will learn about sorting, searching, and files