CONTROL AND ENVIRONMENTS 1

Similar documents
CS 61A Control and Environments Spring 2018 Discussion 1: January 24, Control. If statements. Boolean Operators

Control and Environments Fall 2017 Discussion 1: August 30, Control. If statements. Boolean Operators

Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions. 1 Control. If statements. Boolean Operators

C ONTROL AND H IGHER O RDER F UNCTIONS

CONTROL AND HIGHER ORDER FUNCTIONS 1

CONTROL AND HIGHER ORDER FUNCTIONS 1

HIGHER ORDER FUNCTIONS AND ENVIRONMENT DIAGRAMS 2

CONTROL AND HIGHER ORDER FUNCTIONS 2

HIGHER-ORDER FUNCTIONS 2

ENVIRONMENT DIAGRAMS AND RECURSION 2

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

CS 61A Higher Order Functions and Recursion Fall 2018 Discussion 2: June 26, Higher Order Functions. HOFs in Environment Diagrams

61A Lecture 3. Friday, September 5

CS 61A Higher Order Functions and Recursion Fall 2018 Discussion 2: June 26, 2018 Solutions. 1 Higher Order Functions. HOFs in Environment Diagrams

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

61A Lecture 2. Wednesday, September 4, 2013

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

61A Lecture 2. Friday, August 28, 2015

Intro. Scheme Basics. scm> 5 5. scm>

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Control Structures 1 / 17

Structure and Interpretation of Computer Programs

Flow Control. So Far: Writing simple statements that get executed one after another.

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Making Decisions In Python

61A Lecture 4. Monday, September 9

HIGHER ORDER FUNCTIONS 2

Test #2 October 8, 2015

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Statements 2. a operator= b a = a operator b

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

CS1 Lecture 3 Jan. 18, 2019

CSC Software I: Utilities and Internals. Programming in Python

CS1 Lecture 3 Jan. 22, 2018

Structure and Interpretation of Computer Programs Summer 2015 Midterm 1

Structure and Interpretation of Computer Programs

Problem Solving for Intro to Computer Science

Structure and Interpretation of Computer Programs

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Python 1: Intro! Max Dougherty Andrew Schmitt

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

CS 31: Intro to Systems C Programming. Kevin Webb Swarthmore College September 13, 2018

FRAC: Language Reference Manual

CS61A Notes Week 13: Interpreters

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

The SPL Programming Language Reference Manual

Lecture 1 Contracts : Principles of Imperative Computation (Fall 2018) Frank Pfenning

Conditionals and Recursion. Python Part 4

Functional Programming. Pure Functional Programming

CS 31: Intro to Systems Binary Arithmetic. Martin Gagné Swarthmore College January 24, 2016

TAIL RECURSION, SCOPE, AND PROJECT 4 11

Lecture 1 Contracts. 1 A Mysterious Program : Principles of Imperative Computation (Spring 2018) Frank Pfenning

Organization of Programming Languages CS3200/5200N. Lecture 11

5. Control Statements

Structure and Interpretation of Computer Programs

PREPARING FOR PRELIM 1

DRAWING ENVIRONMENT DIAGRAMS

RACKET BASICS, ORDER OF EVALUATION, RECURSION 1

Lecture #12: Immutable and Mutable Data. Last modified: Mon Feb 22 16:33: CS61A: Lecture #12 1

Structure and Interpretation of Computer Programs

Data 8 Final Review #1

The PCAT Programming Language Reference Manual

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Structure and Interpretation of Computer Programs

Introduction to Python (All the Basic Stuff)

Structure and Interpretation of Computer Programs Fall 2012 Alternate Midterm 1

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

Control Flow: Loop Statements

Midterm Exam 1 Solutions

How Do Robots Find Their Way?

Lists, loops and decisions

2. Explain the difference between read(), readline(), and readlines(). Give an example of when you might use each.

CS 1110: Introduction to Computing Using Python Loop Invariants

Outline. Data Definitions and Templates Syntax and Semantics Defensive Programming

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Introduction to Computer Programming for Non-Majors

Score score < score < score < 65 Score < 50

CSCE 110: Programming I

Structure and Interpretation of Computer Programs

Overview of List Syntax

CSc 372. Comparative Programming Languages. 36 : Scheme Conditional Expressions. Department of Computer Science University of Arizona

MORE SCHEME. 1 What Would Scheme Print? COMPUTER SCIENCE MENTORS 61A. October 30 to November 3, Solution: Solutions begin on the following page.

CS 1301 CS1 with Robots Summer 2007 Exam 1

4. Write a sum-of-products representation of the following circuit. Y = (A + B + C) (A + B + C)

CSE 115. Introduction to Computer Science I

Key Differences Between Python and Java

Structure and Interpretation of Computer Programs

1. Suppose you are given a magic black box that somehow answers the following decision problem in polynomial time:

PROGRAMMING FUNDAMENTALS

Python for Informatics

Transcription:

CONTROL AND ENVIRONMENTS 1 COMPUTER SCIENCE 61A September 1, 2016 1 Control Control structures direct the flow of logic in a program. For example, conditionals (ifelif-else) allow a program to skip sections of code, while iteration (while), allows a program to repeat a section. 1.1 If statements Conditional statements let programs execute different lines of code depending on certain conditions. Let s review the if- elif-else syntax: if <conditional expression>: <suite of statements> elif <conditional expression>: <suite of statements> else: <suite of statements> Recall the following points: The else and elif clauses are optional, and you can have any number of elif clauses. A conditional expression is a expression that evaluates to either a true value (True, a non-zero integer, etc.) or a false value (False, 0, None, "", [], etc.). Only the suite that is indented under the first if/elif with a conditional expression evaluating to a true value will be executed.

DISCUSSION 1: CONTROL AND ENVIRONMENTS Page 2 If none of the conditional expressions evaluate to a true value, then the else suite is executed. There can only be one else clause in a conditional statement! 1.2 Boolean Operators Python also includes the boolean operators and, or, and not. These operators are used to combine and manipulate boolean values. not returns the opposite truth value of the following expression. and stops evaluating any more expressions (short-circuits) once it reaches the first false value and returns it. If all values evaluate to a true value, the last value is returned. or short-circuits at the first true value and returns it. If all values evaluate to a false value, the last value is returned. >>> not None True >>> not True False >>> -1 and 0 and 1 0 >>> False or 9999 or 1/0 9999 1.3 Questions 1. Alfonso will only wear a jacket outside if it is below 60 degrees or it is raining. Fill in the function wears jacket which takes in the current temperature and a Boolean value telling if it is raining and returns True if Alfonso will wear a jacket and False otherwise. This should only take one line of code! def wears_jacket(temp, raining): >>> rain = False >>> wears_jacket(90, rain) False >>> wears_jacket(40, rain) True >>> wears_jacket(100, True) True

DISCUSSION 1: CONTROL AND ENVIRONMENTS Page 3 2. To handle discussion section overflow, TAs may direct students to a more empty section that is happening at the same time. Write the function handle overflow, which takes in the number of students at two sections and prints out what to do if either section exceeds 30 students. Note: Don t worry about printing spot for singular values and spots for multiple values. def handle_overflow(s1, s2): >>> handle_overflow(27, 15) No overflow. >>> handle_overflow(35, 29) 1 spot left in Section 2. >>> handle_overflow(20, 32) 10 spots left in Section 1. >>> handle_overflow(35, 30) No space left in either section. 1.4 While loops Iteration lets a program repeat statements multiple times. A common iterative block of code is the while loop: while <conditional clause>: <body of statements> As long as <conditional clause> evaluates to a true value, <body of statements> will continue to be executed. The conditional clause gets evaluated each time the body finishes executing.

DISCUSSION 1: CONTROL AND ENVIRONMENTS Page 4 1.5 Questions 1. What is the result of evaluating the following code? def square(x): return x * x def so_slow(num): x = num while x > 0: x = x + 1 return x / 0 square(so_slow(5)) 2. Fill in the is prime function, which returns True if n is a prime number and False otherwise. After you have a working solution, think about potential ways to make your solution more efficient. Hint: use the % operator: x % y returns the remainder of x when divided by y. def is_prime(n):

DISCUSSION 1: CONTROL AND ENVIRONMENTS Page 5 2 Environment Diagrams An environment diagram keeps track of all the variables that have been defined and the values they are bound to. x = 3 def square(x): return x ** 2 square(2) When you execute assignment statements in an environment diagram (like x = 3), you need to record the variable name and the value: 1. Evaluate the expression on the right side of the = sign 2. Write the variable name and the expression s value in the current frame. When you execute def statements, you need to record the function name and bind the function object to the name. 1. Write the function name (e.g., square) in the frame and point it to a function object (e.g., func square(x) [parent=global]). The [parent=global] denotes the frame in which the function was defined. When you execute a call expression (like square(2)), you need to create a new frame to keep track of local variables. 1. Draw a new frame. a Label it with a unique index (f1, f2, f3 and so on) the intrinsic name of the function (square), which is the name of the function object itself. For example, if the function object is func square(x) [parent=global], the intrinsic name is square. the parent frame ([parent=global]) 2. Bind the formal parameters to the arguments passed in (e.g. bind x to 3). 3. Evaluate the body of the function. If a function does not have a return value, it implicitly returns None. Thus, the Return value box should contain None. a Since we do not know how built-in functions like add(...) or min(...) are implemented, we do not draw a new frame when we call built-in functions.

DISCUSSION 1: CONTROL AND ENVIRONMENTS Page 6 2.1 Environment Diagram Questions 1. Draw the environment diagram that results from running the following code. a = 1 def b(b): return a + b a = b(a) a = b(a)

DISCUSSION 1: CONTROL AND ENVIRONMENTS Page 7 2. Draw the environment diagram so we can visualize exactly how Python evaluates the code. What is the output of running this code in the interpreter? >>> from operator import add >>> def sub(a, b):... sub = add... return a - b >>> add = sub >>> sub = min >>> print(add(2, sub(2, 3)))

DISCUSSION 1: CONTROL AND ENVIRONMENTS Page 8 3 Higher Order Functions A higher order function (HOF) is a function that manipulates other functions by taking in functions as arguments, returning a function, or both. 3.1 Functions as Arguments One way a higher order function can manipulate other functions is by taking functions as input (an argument). Consider this higher order function called negate. def negate(f, x): return -f(x) negate takes in a function f and a number x. It doesn t care what exactly f does, as long as f is a function, takes in a number and returns a number. Its job is simple: call f on x and return the negation of that value. 3.2 Questions 1. Implement a function keep ints, which takes in a function cond and a number n, and only prints a number from 1 to n if calling cond on that number returns True: def keep_ints(cond, n): Print out all integers 1..i..n where cond(i) is true >>> def is_even(x):... # Even numbers have remainder 0 when divided by 2.... return x % 2 == 0 >>> keep_ints(is_even, 5) 2 4

DISCUSSION 1: CONTROL AND ENVIRONMENTS Page 9 3.3 Functions as Return Values Often, we will need to write a function that returns another function. One way to do this is to define a function inside of a function: def outer(x): def inner(y):... return inner The return value of outer is the function inner. This is a case of a function returning a function. In this example, inner is defined inside of outer. Although this is a common pattern, we can also define inner outside of outer and still use the same return statement. However, note that in this second example (unlike the first example), inner doesn t have access to variables defined within the outer function, like x. def inner(y):... def outer(x): return inner 3.4 Questions 1. Use this definition of outer to fill in what Python would display when the following lines are evaluated. def outer(n): def inner(m): return n - m return inner >>> outer(61) >>> f = outer(10) >>> f(4) >>> outer(5)(4)

DISCUSSION 1: CONTROL AND ENVIRONMENTS Page 10 2. Implement a function keep ints like before, but now it takes in a number n and returns a function that has one parameter cond. The returned function prints out all numbers from 1..i..n where calling cond(i) returns True. def keep_ints(n): Returns a function which takes one parameter cond and prints out all integers 1..i..n where calling cond(i) returns True. >>> def is_even(x):... # Even numbers have remainder 0 when divided by 2.... return x % 2 == 0 >>> keep_ints(5)(is_even) 2 4