Overview of List Syntax

Similar documents
Review 4. Lists and Sequences

Mini-Lecture 16. Nested Lists

Lecture 14. Nested Lists and Dictionaries

CS 1110 Final, December 17th, Question Points Score Total: 100

Last Name: First: Netid: Section. CS 1110 Final, December 17th, 2014

CS 1110 Final, December 8th, Question Points Score Total: 100

CS 1110 Final, December 8th, Question Points Score Total: 100

PREPARING FOR PRELIM 1

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

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Part III Appendices 165

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

Types, lists & functions

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

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

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

Student Number: Comments are not required except where indicated, although they may help us mark your answers.

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

ENGR 101 Engineering Design Workshop

CS 1110 Prelim 2 November 13th, 2014

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

CS 1110 Prelim 2 November 14th, 2013

Beyond Blocks: Python Session #1

Programming to Python

(f) d={ alchemist :( a, t ), shaman : ( s, n ), wizard : ( w, z )} d[ shaman ][1]

Babu Madhav Institute of Information Technology, UTU 2015

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Comp Exam 1 Overview.

Arrays and Strings

CS 1110 Prelim 2 April 22, 2014

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python

Strings and Testing string methods, formatting testing approaches CS GMU

Python Programming: Lecture 2 Data Types

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Advanced Algorithms and Computational Models (module A)

CS 1110 Prelim 1 October 4th, 2012

CPSC 217 Midterm (Python 3 version)

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

DaMPL. Language Reference Manual. Henrique Grando

CS 1110 Prelim 1 October 15th, 2015

CS115 - Module 9 - filter, map, and friends

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

CS Prelim 2 Review Fall 2018

ECS15, Lecture 14. Reminder: how to learn Python. Today is the final day to request a regrade of the midterm. Topic 4: Programming in Python, cont.

Array. Prepared By - Rifat Shahriyar

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

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

Slicing. Open pizza_slicer.py

First name (printed): a. DO NOT OPEN YOUR EXAM BOOKLET UNTIL YOU HAVE BEEN TOLD TO BEGIN.

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

CS1 Lecture 3 Jan. 18, 2019

Review. Input, Processing and Output. Review. Review. Designing a Program. Typical Software Development cycle. Bonita Sharif

CS 1110 Prelim 1 October 17th, 2013

Script language: Python Data structures

CS1 Lecture 3 Jan. 22, 2018

Advanced Python. Executive Summary, Session 1

CS Exam 2 Name: Your Grading TA: This exam has 7 pages including the title page. Please check to make sure all pages are included.

Teaching London Computing

Lists, loops and decisions

[CHAPTER] 1 INTRODUCTION 1

Visualize ComplexCities

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

egrapher Language Reference Manual

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Python for Non-programmers

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

Lecture 10: Lists and Sequences

CS 1301 Exam 2 Fall 2010

COMP519 Web Programming Lecture 17: Python (Part 1) Handouts

Introduction to Python

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

About the Final. Saturday, 7-10pm in Science Center 101. Closed book, closed notes. Not on the final: graphics, file I/O, vim, unix

CS 1301 Exam 1 Fall 2010

Issue with Implementing PrimeSieve() in Go

CIS192: Python Programming

CSCA20 Worksheet Strings

Topic 7: Lists, Dictionaries and Strings

Scheme as implemented by Racket

CS115 - Module 8 - Binary trees

NOTE: All references to Python on this exam mean Python 3, so you should answer accordingly.

ENGR 102 Engineering Lab I - Computation

TUPLES AND RECURSIVE LISTS 5

CS 1110 Final Exam Solutions May 15th, 2014

EXAM Computer Science 1 Part 1

CS 11 python track: lecture 3. n Today: Useful coding idioms

Question 1. Part (a) Part (b) December 2013 Final Examination Marking Scheme CSC 108 H1F. [13 marks] [4 marks] Consider this program:

CMPSCI 119 Fall 2018 Wednesday, November 14, 2018 Midterm #2 Solution Key Professor William T. Verts

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

THE AUSTRALIAN NATIONAL UNIVERSITY Mid Semester Examination September COMP1730 / COMP6730 Programming for Scientists

Final Exam CS 152, Computer Programming Fundamentals December 9, 2016

CS 2316 Exam 1 Spring 2014

python 01 September 16, 2016

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

Variable and Data Type I

Collections. Lists, Tuples, Sets, Dictionaries

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

Transcription:

Lists and Sequences

Overview of List Syntax x = [0, 0, 0, 0] Create list of length 4 with all zeroes x 4300112 x.append(2) 3 in x x[2] = 5 x[0] = 4 k = 3 Append 2 to end of list x (now length 5) Evaluates to False (3 not in x) Assign 5 to element 2 and 4 to element 0 0 1 2 3 4 4300112 0-4 0 6 0 5 0-8 2 x[k] = 2 * x[0] x[k 2] = 6 Assign -8 to x[3] and 6 to x[1] k 3

Lists vs. Tuples vs. Strings Creation x = [a1, a2, a3, ] Can contain anything len(x) is length Supports slicing Example: x[1:2] x[i] is anelement Can concatenate y = x + [1, 2] Makes a new list Is mutable x.append(5) Creation x = (a1, a2, a3, ) Can contain anything len(x) is length Supports slicing Example: x[1:2] x[i] is anelement Can concatenate y = x + (1, 2) Makes a new tuple Is not mutable Creation x = 'Hello' Only contains chars len(x) is length Supports slicing Example: x[1:2] x[i] is asubstring Can concatenate y = x + ' World' Makes a new string Is not mutable

Lists vs. Tuples vs. Strings Creation x = [a1, a2, a3, ] Can contain anything len(x) is length Supports slicing Example: x[1:2] x[i] is anelement Can concatenate y = x + [1, 2] Makes a new list Is mutable x.append(5) Creation Did x = (a1, a2, a3, s ) emester, not use this x b = u semester ' t H w ell o o r but works ' k Can contain anyth a in lm almost g ost lik like O e nl l lists y is c t o s do n d ta oiṅschars len(x) is length len(x) is length Supports slicing Supports slicing Example: x[1:2] Example: x[1:2] x[i] is anelement x[i] is asubstring Can Can concatenate concatenate y = y = x + ' World' x + (1, 2) Makes a Makes a new string new tuple Is not mutable Is not mutable

Quick for loop review Basic Structure: for <placeholder variable> in <list to loop through>: do something... Two general forms: thelist = [ a, b, c, d ] for foo in thelist: print foo Loops through the elements of thelist thelist = [ a, b, c, d ] for index in range(len(thelist)): print thelist[index] Loops through the indicies of thelist Think about what range really returns! range(4) >> [0,1,2,3] range(1) >> [0]

Modified Question 4 from Fall 2011 Each elements in the list scores contains the number of students who received score i on a test. For example, if 30 students got 85, then scores[85] is 30.Write the body of function histogram, which returns a histogram as a list of strings. (You need not write loop invariants.) For example, if scores = [7, 0, 4, 3, 2, 0, ] then the first elementsof the resulting string list are: '00 *******' '01 ' '02 ****' '03 ***' '04 *' '05 '

Modified Question 4 from Fall 2011 def histogram(scores): """Return a list of Strings (call it s) in which each s[i] contains: (1) i, as a two-digit integer (with leading zeros if necessary) (2) a blank, (3) n asterisks '*', where n is scores[i]. Precondition: scores is a list of nonnegative integers, len(scores) < 100""" # IMPLEMENT ME

Modified Question 4 from Fall 2011 def histogram(scores): """Return a list of Strings (call it s) in which each s[i] contains: (1) i, as a two-digit integer (with leading zeros if necessary) (2) a blank, (3) n asterisks '*', where n is scores[i]. Precondition: scores is a list of nonnegative integers, len(scores) < 100""" s = [] # List to contain the result. for i in range(len(scores)): if scores[i] < 10: else: row = str(scores[i]) + row = 0 + str(scores[i]) + for n in range(scores[i]): row = row + * s.append(row) return s # Need the value i, not the elements of scores # Add a 0 for double digits # Append scores[i] number of asterisks

Overview of Two-Dimensional Lists Access value at row 3, col 2: d[3][2] Assign value at row 3, col 2: d[3][2] = 8 An odd symmetry Number of rows of d: Number of cols in row r of d: len(d) len(d[r]) 0 1 2 3 d 0 5 4 7 3 1 4 8 9 7 2 5 1 2 3 3 4 1 2 9 4 6 7 8 0

How Multidimensional Lists are Stored b = [[9, 6, 4], [5, 7, 7]] b 9 6 4 5 7 7 23457811 23457811 82799054 43001122 82799054 9 6 4 43001122 5 7 7 b holds name of a one-dimensional list Has len(b) elements Its elements are (the names of) 1D lists b[i] holds the name of a one-dimensional list (of ints) Has len(b[i]) elements

Modified Question 4 from Fall 2010 Recall drawing GRectangles in A7. Write method placesquares, whose requirements appear below. It draws square bricks as shown to the right and returns them as a 2d list of GRectangle def placesquares(self, m): """Create a list of m x m squares (GRectangle), as specified below, adding the squares to the GUI, and return the list.""" Method Requirements: There are m columns and rows of squares; precondition: 0 < m. Each square has side length BRICK_SIDE; there is no space between them. The bottom-left square is at the bottom-left corner (0,0) of the GUI. Squares in columns and rows 0 and m-1 have color colormodel.pink Inner squares have checkerboard pattern of colormodel.red and colormodel.green, as shown (bottom-left one is green; one next to it, red).

Modified Question 4 from Fall 2010 Recall drawing GRectangles in A7. Write method placesquares, whose requirements appear below. It draws square bricks as shown to the right and returns them as a 2d list of GRectangle def placesquares(self, m): """Create a list of m x m squares (GRectangle), as specified on last slide, adding them to the GUI, and return the list.""" API Reminders: GRectangle has attributes pos (a 2 element tuple), size (a 2 element tuple), fillcolor, and linecolor You construct a GRectangle with keyword arguments: GRectangle(pos=(0,0),size=(10,10)) You add to the GUI with self.view.add( )

def placesquares(self, m): """Place the m x m Bricks, as requested on the exam and return the list""" bricks = []; r = 0 while r < m: row = []; c = 0 while c < m: # Make a new list to represent the whole grid # Place col c of bricks # Make a new list to represent rows color = colormodel.red if r == 0 or r == m-1 or c == 0 or c == m-1: color = colormodel.pink elif r+c % 2 == 0: color = colormodel.green brick=grectangle(pos=(r*brick_side,c*brick_side), fillcolor=color size=(brick_side,brick_side), linecolor=color) row.append(brick) self.view.add(brick) c = c+1 bricks.append(row) r = r+1 return bricks

Ragged Lists: Rows w/ Different Length b = [[17,13,19],[28,95]] b 23457811 23457811 0 82799054 1 43001122 0 1 2 82799054 17 13 19 0 1 43001122 28 95 To create a ragged list Create b as an empty list (b =[]) Create each row as a list (r1 = [17,13,19]; r2 = [28,95]) Append lists to b (b.append(r1); b.append(r2))

Modified Question 4 from Fall 2011 Someone messed up a method to create certain arrays for us. For example (and this is only an example), they produced the array: 3 1 2 1 2 3 2 1 7 8 5 instead of 1 7 8 5 2 5 the array 5 6 8 8 6 Thus, they put the last value of each row at the beginning instead of the end. Write a procedure that fixes this by rotating each row one position to the left; each element is moved one position earlier, and the first element is placed in the last position. Do not use recursion. DO NOT RETURN A VALUE. def rotate(b): """Rotate each row one position to the left, as explained above. Precondition: b is a list, might be ragged, and each row has >= 1 value"""

Modified Question 4 from Fall 2011 def rotate(b): """Rotate each row one position to the left, as explained on the previous slide. Precondition: b is a list, might be ragged, and each row has >= 1 value""" # invariant: rows 0..r 1 of b have been rotated r = 0 while r < len(b): first = b[r][0] # Rotate row r one position to the left; # inv: b[r][1..c 1] moved to b[r][0..c 2] c = 1 while c < len(b[r]) b[r][c-1]= b[r][c]; c= c+1 # post: b[r][1..] has been moved to b[r][0..] b[r][len(b[r]) 1]= first r = r+1 # post: rows 0..b.length 1 of b has been rotated

Dictionaries

Overview of Dictionary Syntax Creation d = dict() d = {} Insertion d[ new_key ] = new_value Modification d[ new_key ] = even_newer_value These two do the exact same thing! Creates an empty dictionary Adds new_value to d with the key of new_key Changes the value at new_key to even_newer_value Note: Insertion and Modification has the same syntax! Whether it modifies or not depends on if the key is already in the dictionary

Overview of Dictionary Syntax Creation d = dict() d = {} Insertion Modification Search d[ new_key ] = new_value d[ new_key ] = even_newer_value Deletion These two do the exact same thing! Creates an empty dictionary new_key in d >> returns True random_key in d >> returns False del d[ new_key ] Adds new_value to d with the key of new_key Deletes key-value pair: new_key is removed along with its value, even_newer_value Changes the value at new_key to even_newer_value Use the in keyword to check if a key is in the dictionary

Histograms Revisited (Dictionaries) def histogram(scores): """Return a histogram where the key value pair is: (score, number of occurrences) so that every score in scores is represented. If there a score is not in scores, then it does not need to be reflected in the dictionary with (score, 0). Precondition: scores is a list of nonnegative integers, len(scores) < 100""" # IMPLEMENT ME

Histograms Revisited (Dictionaries) def histogram(scores): """Return a histogram where the key value pair is: (score, number of occurrences) so that every score in scores is represented. If there a score is not in scores, then it does not need to be reflected in the dictionary with (score, 0). Precondition: scores is a list of nonnegative integers, len(scores) < 100"" histogram = dict() # Could have also written histogram = {} for score in scores: if score in histogram: else: histogram[score] += 1 histogram[score] = 1 return histogram # Check if this score is already in histogram

Histograms Revisited (Dictionaries) def histogram(scores): """Return a histogram where the key value pair is: (score, number of occurrences) so that every score in scores is represented. If there a score is not in scores, then it does not need to be reflected in the dictionary with (score, 0). Precondition: scores is a list of nonnegative integers, len(scores) < 100"" histogram = dict() # Could have also written histogram = {} for score in scores: if score in histogram: else: histogram[score] += 1 histogram[score] = 1 return histogram # Check if this score is already in histogram Very common idiom. Make sure you re familiar with it!

Python Basics

Basic Types Strings (str) Literals surrounded in quotes: Hello World! Booleans (bool) Two possible values: True or False Integers (int) Represents whole numbers: -1, 0, 1, 2, 3 Floats (float) Represents decimals: -0.1, 1.4445, 2.48935,

Booleans (bool) Represents logical statements! Operators: not, and, or not b: True if b is false and False if b is true (negation) a and b: True if both a and b are true and False otherwise. a or b: True if a is true or b is true and False otherwise. Often are results of comparisons: Order comparison: a < b; a <=b; a >= b; a > b Equality comparison: a == b; a!= b Short Circuiting: (False and x / 0) vs (x / 0 and False) (True or x / 0) vs (x / 0 or True)

Strings (str) Used to represent text. Anything surrounded in either single quotes or double quotes is a string. Operators: + (concatenation) Hello + World! >> Hello World! Don t forget about string methods! A few common ones: find() and index(); know the difference and what the second optional argument does count() split() join() String indexing and splicing: You access specific indexes using s[i] where s is the str and i is an int Splice substrings using s[i:j]. i is inclusive while j is exclusive

If-statements Basic Structure: if <boolean expression>: do something else: do something This lets you control the flow of your code, directing it down branches depending on certain variables! Common style problem: if x == True: # Think about what the type of x is! do something else: do something

Questions