Review 4 Lists and Sequences.

Slides:



Advertisements
Similar presentations
A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
Advertisements

Arrays.
Container Types in Python
RAPTOR Syntax and Semantics By Lt Col Schorsch
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.
Lists/Tuples. Example Write a program to keep track of all students’ scores on exam 1. Need a list of everyone’s score Use 14 doubles What about next.
Lecture 5 Arrays A way to organize data © MIT AITI 2003.
2/28/2008. >>> Overview Arrays in Python – a.k.a. Lists Ranges are Lists Strings vs. Lists Tuples vs. Lists Map-Reduce Lambda Review: Printing to a file.
CS 106 Introduction to Computer Science I 02 / 19 / 2007 Instructor: Michael Eckmann.
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
Java Unit 9: Arrays Declaring and Processing Arrays.
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
Unit 3: Java Data Types Math class and String class.
Arrays Chapter 7. 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores : Inspecting.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Built-in Data Structures in Python An Introduction.
Operations on Strings. 8/8/2005 Copyright 2006, by the authors of these slides, and Ateneo de Manila University. All rights reserved L: String Manipulation.
C++ String Class nalhareqi©2012. string u The string is any sequence of characters u To use strings, you need to include the header u The string is one.
1 Arrays and Strings Lecture: Design Problem l Consider a program to calculate class average Why?? ?
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.
1 Arrays of Arrays An array can represent a collection of any type of object - including other arrays! The world is filled with examples Monthly magazine:
1 CS Nov 2011 Ragged arrays Reading for today: sec Reading for next time: Interfaces: Sec and corresponding ProgramLive material. Also,
CSCI 130 More on Arrays. Multi-dimensional Arrays Multi - Dimensional arrays: –have more than one subscript –can be directly initialized –can be initialized.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
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.
Mr. Crone.  Use print() to print to the terminal window  print() is equivalent to println() in Java Example) print(“Hello1”) print(“Hello2”) # Prints:
Windows Programming Lecture 03. Pointers and Arrays.
Today… Loops and Drawing, Cont. –Two slightly more advanced demos. Collections Overview. Winter 2016CISC101 - Prof. McLeod1.
Arrays Chapter 7.
String and Lists Dr. José M. Reyes Álamo.
Arrays Chapter 7.
Two-Dimensional Arrays
© 2016 Pearson Education, Ltd. All rights reserved.
Array, Strings and Vectors
CMSC201 Computer Science I for Majors Lecture 12 – Lists (cont)
CS-104 Final Exam Review Victor Norman.
2.5 Another Java Application: Adding Integers
Shell Scripting March 1st, 2004 Class Meeting 7.
2-D Lists Taken from notes by Dr. Neil Moore
Intro to PHP & Variables
Agenda Control Flow Statements Purpose test statement
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Lists Part 1 Taken from notes by Dr. Neil Moore
Developing Loops from Invariants
Flooding © 2018.
CS190/295 Programming in Python for Life Sciences: Lecture 6
Multidimensional Arrays
String and Lists Dr. José M. Reyes Álamo.
Introduction to Programming
MSIS 655 Advanced Business Applications Programming
Arrays Chapter 7.
Topics Sequences Introduction to Lists List Slicing
Lists Part 1 Taken from notes by Dr. Neil Moore
Building Java Programs
CS1110 Today: collections.
Introduction to Computer Science
Topics Sequences Introduction to Lists List Slicing
Introduction to Programming
C++ Array 1.
CS31 Discussion 1H Fall18: week 6
Review 4 Lists and Sequences.
String Class.
2-D Lists Taken from notes by Dr. Neil Moore
CS100J 10 April 2005 Rectangular arrays and ragged arrays. Secs. 9
Developing Loops from Invariants
Dr. Khizar Hayat Associate Prof. of Computer Science
Arrays.
Introduction to Computer Science
Presentation transcript:

Review 4 Lists and Sequences

Overview of List Syntax Create list of length 4 with all zeroes x = [0, 0, 0, 0] x.append(2) 3 in x x[2] = 5 x[0] = –4 k = 3 x[k] = 2 * x[0] x[k–2] = 6 x 4300112 Append 2 to end of list x (now length 5) 4300112 Evaluates to False (3 not in x) ✗ -4 ✗ 1 6 Assign 5 to element 2 and –4 to element 0 ✗ 2 5 ✗ 3 -8 4 2 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 an element 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 an element 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 a substring Can concatenate y = x + ' World' Makes a new string Is not mutable

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 elements of 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)): # Need the value i, not the elements of scores # Inv: `row` is the string for this printout line # Conditional expression version: # row = (str(i)+' ') if scores[0] > 10 else ('0'+str(i)+' ') if scores[i] > 10: row = str(i)+' ' else: row = '0'+str(i)+' ' for n in range(scores[i]): # Loop over number of elements in scores[i] row = row+'*' # Add another * to the row s.append(row) # Add row to the list return s

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: len(d) Number of cols in row r of d: len(d[r]) 5 4 7 3 4 8 9 7 5 1 2 3 4 1 2 9 6 7 8 0 d 0 1 2 3 1 4 2 3

How Multidimensional Lists are Stored b = [[9, 6, 4], [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 9 6 4 5 7 7 82799054 9 6 4 43001122 5 7 23457811 82799054 43001122 b 23457811

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 n Bricks, as requested on the exam and return the list""" bricks = []; c = 0 # Make a new list to represent columns while c < m: # Place col c of bricks row = []; r = 0 # Make a new list to represent rows while r < m: 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); r = r+1 bricks.append(row) c= c+1 return bricks

Ragged Lists: Rows w/ Different Length b = [[17,13,19],[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)) 82799054 17 13 19 23457811 43001122 28 95 b 23457811 82799054 1 1 43001122 1 2

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""" # Process each row for r in rang(len(b)): # Remember the first element so we can put it at the end first = b[r][0] # Start at second element and shift each to the left for c in range(1,len(b[r])): b[r][c-1]= b[r][c]; # Put the first element at the end b[r][len(b[r])–1]= first