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

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

CONTROL AND ENVIRONMENTS 1

CS 61A Control and Environments Spring 2018 Discussion 1: January 24, 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

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

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

HIGHER-ORDER FUNCTIONS 2

61A Lecture 3. Friday, September 5

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

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

61A Lecture 2. Wednesday, September 4, 2013

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

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

61A Lecture 2. Friday, August 28, 2015

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

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

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

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

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

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

Structure and Interpretation of Computer Programs

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Making Decisions In Python

HIGHER ORDER FUNCTIONS 2

Test #2 October 8, 2015

Structure and Interpretation of Computer Programs Summer 2015 Midterm 1

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

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Problem Solving for Intro to Computer Science

Control Structures 1 / 17

CS1 Lecture 3 Jan. 18, 2019

CSC Software I: Utilities and Internals. Programming in Python

CS1 Lecture 3 Jan. 22, 2018

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

61A Lecture 4. Monday, September 9

Python 1: Intro! Max Dougherty Andrew Schmitt

Structure and Interpretation of Computer Programs

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

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

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

Data 8 Final Review #1

Structure and Interpretation of Computer Programs

CS61A Notes Week 13: Interpreters

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

Conditionals and Recursion. Python Part 4

Delayed Expressions Fall 2017 Discussion 9: November 8, Iterables and Iterators. For Loops. Other Iterable Uses

TAIL RECURSION, SCOPE, AND PROJECT 4 11

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

Structure and Interpretation of Computer Programs Fall 2015 Midterm 1

Structure and Interpretation of Computer Programs

PREPARING FOR PRELIM 1

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:

RACKET BASICS, ORDER OF EVALUATION, RECURSION 1

CSc 520 Principles of Programming Languages

Introduction to Computer Programming for Non-Majors

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

Structure and Interpretation of Computer Programs

CS 1301 CS1 with Robots Summer 2007 Exam 1

Structure and Interpretation of Computer Programs

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

Short Answer Questions (40 points)

Lecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley

Structure and Interpretation of Computer Programs

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

FRAC: Language Reference Manual

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs Fall 2012 Alternate Midterm 1

The SPL Programming Language Reference Manual

Discrete structures - CS Fall 2017 Questions for chapter 2.1 and 2.2

Scheme Quick Reference

Structure and Interpretation of Computer Programs

CS115 - Module 10 - General Trees

ECE 2400 Computer Systems Programming Fall 2018 Topic 1: Introduction to C

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

How Do Robots Find Their Way?

CPSC 3740 Programming Languages University of Lethbridge. Control Structures

Midterm Exam 1 Solutions

Structure and Interpretation of Computer Programs

CS 61A, Fall, 2002, Midterm #2, L. Rowe. 1. (10 points, 1 point each part) Consider the following five box-and-arrow diagrams.

Functional programming with Common Lisp

5. Control Statements

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

Functional Programming. Pure Functional Programming

Outline. Data Definitions and Templates Syntax and Semantics Defensive Programming

CS 1110: Introduction to Computing Using Python Loop Invariants

Python for Informatics

Overview of List Syntax

Control Flow: Branching booleans and selection statements CS GMU

Midterm Exam 2B Answer key

CS 415 Midterm Exam Fall 2003

Transcription:

CS 61A Control and Environments Fall 2017 Discussion 1: August 30, 2017 1 Control Control structures direct the flow of logic in a program. For example, conditionals (if-elif-else) allow a program to skip sections of code, while iteration (while), allows a program to repeat a section. If statements Conditional statements let programs execute different lines of code depending on certain conditions. Let s review the if- elif-else syntax. 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. ˆ 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! Boolean Operators Python also includes the boolean operators and, or, and not. operators are used to combine and manipulate boolean values. These ˆ 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. evaluate to a false value, the last value is returned. If all values

2 Control and Environments 1.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): >>> wears_jacket(90, False) False >>> wears_jacket(40, False) True >>> wears_jacket(100, True) True 1.2 To handle discussion section overflow, TAs may direct students to a more empty section that is happening at the same time. Define handle_overflow, which takes in the number of students in 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.

Control and Environments 3 While loops Iteration lets a program repeat statements multiple times. A common iterative block of code is the while loop. 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. 1.3 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)) 1.4 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):

4 Control and Environments 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.

Control and Environments 5 2.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) 2.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)))

6 Control and Environments 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. 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. 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.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

Control and Environments 7 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: 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. 3.2 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)

8 Control and Environments 3.3 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