C10552: Intro to Computation. Lecture 2 July 17, 2016

Similar documents
Python for loops. Girls Programming Network School of Information Technologies University of Sydney. Mini-lecture 7

CS 100: Computability, Python Lists

At full speed with Python

CS1 Lecture 9 Feb. 5, 2018

Problem Solving for Intro to Computer Science

Python: common syntax

Python. Tutorial Lecture for EE562 Artificial Intelligence for Engineers

CS1 Lecture 3 Jan. 18, 2019

Modular Arithmetic. Marizza Bailey. December 14, 2015

61A Lecture 2. Friday, August 28, 2015

Semester 2, 2018: Lab 5

CMSC201 Computer Science I for Majors

OR, you can download the file nltk_data.zip from the class web site, using a URL given in class.

Iteration. Chapter 7. Prof. Mauro Gaspari: Mauro Gaspari - University of Bologna -

Introduction to Computation for the Humanities and Social Sciences. CS 3 Chris Tanner

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

Lecture Notes, CSE 232, Fall 2014 Semester

Teaching London Computing

CS1 Lecture 3 Jan. 22, 2018

What is a Fraction? Fractions. One Way To Remember Numerator = North / 16. Example. What Fraction is Shaded? 9/16/16. Fraction = Part of a Whole

CMSC201 Computer Science I for Majors

Strings in Python 1 Midterm#1 Exam Review CS 8: Introduction to Computer Science Lecture #6

Exercise 6 - Addressing a Message

CS1 Lecture 12 Feb. 11, 2019

Cryptography Worksheet

Python Intro GIS Week 1. Jake K. Carr

Strings, Lists, and Sequences

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

CMSC201 Computer Science I for Majors

Python for Non-programmers

Programming in Python

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

Variables, expressions and statements

Basic Data Types and Operators CS 8: Introduction to Computer Science, Winter 2019 Lecture #2

6.189 Project 1. Readings. What to hand in. Project 1: The Game of Hangman. Get caught up on all the readings from this week!

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

MITOCW watch?v=flgjisf3l78

CS116 - Module 5 - Accumulative Recursion

ENGR 101 Engineering Design Workshop

Unit E Step-by-Step: Programming with Python

Introduction to Python Code Quality

Divisibility Rules and Their Explanations

Python lab session 1

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

COMP 204: Sets, Commenting & Exceptions

The little book of programming challenges

CS1 Lecture 4 Jan. 23, 2019

Organizing Data. Reminders. A Flood of Data. The Power of Structure...

CMSC201 Computer Science I for Majors

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

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment

Section 1.1 Definitions and Properties

COMP 204: Sets, Commenting & Exceptions

Hello, World! An Easy Intro to Python & Programming. Jack Rosenthal

CS 115 Lecture 8. Selection: the if statement. Neil Moore

Ch.2: Loops and lists

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

CMSC201 Computer Science I for Majors

CS1004: Intro to CS in Java, Spring 2005

Intro to Python & Programming. C-START Python PD Workshop

Algorithms and Programming I. Lecture#12 Spring 2015

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

Fundamentals of Programming (Python) Getting Started with Programming

CS101 Lecture 24: Thinking in Python: Input and Output Variables and Arithmetic. Aaron Stevens 28 March Overview/Questions

Expressions and Variables

CSE : Python Programming

The Caesar Cipher Informatics 1 Functional Programming: Tutorial 3

Computing with Strings. Learning Outcomes. Python s String Type 9/23/2012

Introduction to Computer Programming for Non-Majors

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

CS1 Lecture 11 Feb. 9, 2018

Lecture 5 8/24/18. Writing larger programs. Comments. What are we going to cover today? Using Comments. Comments in Python. Writing larger programs

STSCI Python Introduction. Class URL

CMSC201 Computer Science I for Majors

Senior Math Circles Cryptography and Number Theory Week 1

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

Text Input and Conditionals

CMPSCI 250: Introduction to Computation. Lecture #1: Things, Sets and Strings David Mix Barrington 22 January 2014

File Input/Output. Learning Outcomes 10/8/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01. Discussion Sections 02-08, 16, 17

Programming in C++ PART 2

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion

Excerpt from "Art of Problem Solving Volume 1: the Basics" 2014 AoPS Inc.

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

CSC148, Lab #4. General rules. Overview. Tracing recursion. Greatest Common Denominator GCD

Getting Started with Python

Jarek Szlichta

p x i 1 i n x, y, z = 2 x 3 y 5 z

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

CSCA08 Winter 2018 Week 2: Variables & Functions. Marzieh Ahmadzadeh, Brian Harrington University of Toronto Scarborough

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Python 1: Intro! Max Dougherty Andrew Schmitt

Types, lists & functions

SAMS Programming A/B. Lecture #1 Introductions July 3, Mark Stehlik

15-110: Principles of Computing, Spring 2018

[301] Objects/References. Tyler Caraza-Harter

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Data Structures. Lists, Tuples, Sets, Dictionaries

University of Washington CSE 140 Introduction to Data Programming Winter Midterm exam. February 6, 2013

Transcription:

C10552: Intro to Computation Lecture 2 July 17, 2016

Lecture 1 Recap Loops are useful for repeating code for i in range(10): print i If statements are useful for conditional code if current_temp > 80: print It s really hot out there!

Lecture 2 Overview HW solutions One more type of loop: while Run while condition is true Lists Functions Live coding

Homework: finding prime divisors The following paragraph is an excerpt from a book published in 1874: Can the reader say what two numbers multiplied together will produce the number 8,616,460,799? I think it unlikely that anyone but myself will ever know; for they are two large prime numbers, and can only be rediscovered by trying in succession a long series of prime divisors until the right one be fallen upon. Find these two numbers.

Homework: finding prime divisors Plan for the code: Use the writer s suggestion: try every possible number!

Homework: finding prime divisors Plan for the code: Use the writer s suggestion: try every possible number! If any number less than 8,616,460,799 divides it evenly, print it.

Homework: finding prime divisors Plan for the code: Use the writer s suggestion: try every possible number! If any number less than 8,616,460,799 divides it evenly, print it. We ll need

Homework: finding prime divisors Plan for the code: Use the writer s suggestion: try every possible number! If any number less than 8,616,460,799 divides it evenly, print it. We ll need a for loop, an if statement, and the modulo operator

Live coding! Plan for the code: Use the writer s suggestion: try every possible number! If any number less than 8,616,460,799 divides it evenly, print it. We ll need a for loop, an if statement, and the modulo operator

Live coding! for i in xrange(1, 8616460799):... if 8616460799 % i is 0:... print i... 1 89681 96079

The while loop

The while loop Run while condition is true Condition is checked before each iteration. red_sox = 2; yankees = 1 while red_sox > yankees: print go sox # runs forever!

The while loop Run while condition is true Anything after # is a comment. It is for your own eyes. The computer will ignore it. red_sox = 2; yankees = 1 while red_sox > yankees: print go sox # runs forever!

The while loop Run while condition is true Anything after # is a comment. It is for your own eyes. The computer will ignore it. red_sox = 2; yankees = 1 while red_sox > yankees: print go sox # runs forever! While loops do not have a predetermined number of iterations. (unlike for loops)

The while loop: example What is the output of the following code? n = 10 while n < 100: n = n * 2 print n

The while loop: example What is the output of the following code? n = 10 while n < 100: n = n * 2 print n 20 40 80 160

The while loop: example What is the output of the following code? n = 10 while n < 100: n = n * 2 print n 20 40 80 160 what?

The while loop: example What is the output of the following code? n = 10 while n < 100: Remember that the n = n * 2 condition is print n checked before each iteration! 20 40 80 160 what?

Lists One of the most important tools in programming Simple syntax in Python: my_list = [1,2,3,4,5] range(...) is actually a list! print range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] You can iterate over lists

Lists You can iterate over lists my_friends = ["jim", "al", "mary"] for friend in my_friends:... print "hello", friend... hello jim hello al hello mary

Lists You can iterate over lists my_friends = ["jim", "al", "mary"] for friend in my_friends: If you are not... print "hello", friend iterating over... range(...), use a descriptive hello jim name instead of hello al i hello mary

Lists You can access list elements my_friends = ["jim", "al", "mary"] print my_friends[0] Note that numbering starts from 0 jim print my_friends[1] al print my_friends[2] mary

Modifying lists You can modify elements inplace my_friends = ["jim", "al", "mary"] my_friends[0] = joe my_friends ['joe', 'al', 'mary']

Modifying lists You can append to lists my_friends = ["jim", "al", "mary"] my_friends.append("alice") my_friends ['jim', 'al', 'mary', 'alice'] You can add two lists to each other your_friends = ["jack", "mary", "jessica"] my_friends + your_friends ['jim', 'al', 'mary', 'alice', 'jack', 'mary', 'jessica']

Modifying lists You can append to lists my_friends = ["jim", "al", "mary"] my_friends.append("alice") my_friends ['jim', 'al', 'mary', 'alice'] You can add two lists to each other your_friends = ["jack", "mary", "jessica"] my_friends + your_friends ['jim', 'al', 'mary', 'alice', 'jack', 'mary', 'jessica'] Repetitions are allowed!

Lists are flexible! They can include any type of data my_favorite_numbers = ["one", 2, 42.0] even other lists your_fav_numbers = [5, 100, 65536] our_fav_numbers = [my_fav_numbers, your_fav_numbers] our_fav_numbers [['one', 2, 42.0], [5, 100, 65536]] even themselves! my_favorite_numbers.append(my_favorite_numbers) my_favorite_numbers ['one', 2, 42.0, [...]] my_favorite_numbers[3] is my_favorite_numbers True

Lists are flexible! They can include any type of data my_favorite_numbers = ["one", 2, 42.0] even other lists your_fav_numbers = [5, 100, 65536] our_fav_numbers = [my_fav_numbers, your_fav_numbers] our_fav_numbers [['one', 2, 42.0], [5, 100, 65536]] even themselves! my_favorite_numbers.append(my_favorite_numbers) my_favorite_numbers ['one', 2, 42.0, [...]] my_favorite_numbers[3] is my_favorite_numbers True

Lists are flexible! They can include any type of data my_favorite_numbers = ["one", 2, 42.0] even other lists your_fav_numbers = [5, 100, 65536] our_fav_numbers = [my_fav_numbers, your_fav_numbers] our_fav_numbers [['one', 2, 42.0], [5, 100, 65536]] even themselves! my_favorite_numbers.append(my_favorite_numbers) my_favorite_numbers ['one', 2, 42.0, [...]] my_favorite_numbers[3] is my_favorite_numbers True

Strings: pretty much like lists Time to formally define strings! You have seen a string before: print hello world Most of the operations are the same as lists my_string = "hello world" my_string[0] 'h' your_string = 123 my_string + your_string 'hello world123' but a string only contains characters, and it cannot be modified inplace my_string[0] = 'a' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment

Strings: pretty much like lists Time to formally define strings! You have seen a string before: print hello world Most of the operations are the same as lists my_string = "hello world" my_string[0] 'h' your_string = 123 my_string + your_string 'hello world123' but a string only contains characters, and it cannot be modified inplace my_string[0] = 'a' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment i.e. string variable

Strings: pretty much like lists A string only contains characters, and it cannot be modified inplace my_string[0] = 'a' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment You need to build a new string if you want to modify it english_word = "hello" german_word = "" for letter in english_word:... if letter is 'e':... german_word = german_word + "a"... else:... german_word = german_word + letter... german_word 'hallo'

Functions We sometimes have to do the same set of things over, and over, and over again Functions are a great way to pack your code def my_function(input_value): # Multiplies input_value by 2. return input_value * 2

Functions We sometimes have to do the same set of things over, and over, and over again Functions are a great way to pack your code def my_function(input_value): # Multiplies input_value by 2. return input_value * 2 Treat this as a black box.

Functions Abstraction: very important concept in coding don t reinvent the wheel! def shift_letter(letter): # Given a letter, returns the next # letter in the alphabet. return chr(ord(letter)+1)

Functions Abstraction: very important concept in coding don t reinvent the wheel! def shift_letter(letter): # Given a letter, returns the next # letter in the alphabet. return chr(ord(letter)+1) You may have no idea what the red outlined text means. That is fine. You only need to know what this function does.

Functions Abstraction: very important concept in coding don t reinvent the wheel! def shift_letter(letter): # Given a letter, returns the next # letter in the alphabet. return chr(ord(letter)+1) You may have no idea what the red outlined text means. That is fine. You only need to know what this function does.

Functions Let s test our black box 'b' 'w' '{' 'e' 'n' shift_letter('a') shift_letter('v') shift_letter('z') shift_letter('d') shift_letter('m')

Functions Let s test our black box 'b' 'w' '{' 'e' 'n' shift_letter('a') shift_letter('v') shift_letter('z') shift_letter('d') shift_letter('m')

Functions Let s test our black box 'b' 'w' '{' 'e' 'n' shift_letter('a') shift_letter('v') shift_letter('z') shift_letter('d') shift_letter('m') Issue: Function does not return a letter for z

Functions Let s test our black box 'b' 'w' '{' 'e' 'n' shift_letter('a') shift_letter('v') shift_letter('z') Issue: Function does not return a letter for z shift_letter('d') Solution: Modify function so that z maps to a shift_letter('m')

Functions def shift_letter(letter): # Given a letter, returns the next # letter in the alphabet. return chr(ord(letter)+1)

Functions def shift_letter(letter): # Given a letter, returns the next # letter in the alphabet. return chr(ord(letter)+1) def shift_letter(letter): # Given a letter, returns the next # letter in the alphabet. return chr((ord(letter)97+1)%26+97) Exercise: understand how this function works. Hint: ord( a ) is equal to 97. Solution at the end.

Functions 'b' 'c' 'a' 'x' 'y' shift_letter('a') shift_letter('b') shift_letter('z') shift_letter('w') shift_letter('x')

Functions 'b' 'c' 'a' 'x' 'y' shift_letter('a') shift_letter('b') shift_letter('z') shift_letter('w') shift_letter('x') All set!

Live coding! Using shift_letter, write a simple encryption algorithm that shifts each letter by a given number (not necessarily 1). Assume the input text is lowercase. def encrypt(input_text, shift): # Shifts each letter in input_text # by the given shift value. # Returns the new string.

We re done! See you next week!

Solution to Exercise def shift_letter(letter): # ord(...) returns 97 for a. # Subtract that from letter # to get the alphabetical rank of letter. # Note that this will be using zeroindexing # (i.e. a will be 0) alpha_rank = ord(letter) 97 # shift by 1 new_alpha_rank = alpha_rank + 1 # use the modulo operator so 26 maps to 0 new_alpha_rank = new_alpha_rank % 26 # ord() and chr() are inverses of each other. # Add the subtracted 97 back and return using chr. return chr(new_alpha_rank + 97)