2-D Lists Taken from notes by Dr. Neil Moore

Slides:



Advertisements
Similar presentations
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
Advertisements

CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Nested Loops. Nesting Control Structures One if statement inside another one An if statement inside a loop A loop inside an if statement Control structures.
Table of Contents Matrices - Multiplication Assume that matrix A is of order m  n and matrix B is of order p  q. To determine whether or not A can be.
11 Chapter 8 ARRAYS Continued. 22 MULTI-DIMENSIONAL ARRAYS A one-dimensional array is useful for storing/processing a list of values. For example: –The.
Lists in Python.
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
Multidimensional Arrays CIT 336. The Basics Explaining Multidimensional Arrays.
MATLAB for Engineers 4E, by Holly Moore. © 2014 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected by Copyright.
Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!
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.
Control flow Ruth Anderson UW CSE 160 Spring
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.
The Accumulator Pattern Summing: Add up (“accumulate”), e.g. 1 2 plus 2 2 plus 3 2 plus … plus Variation: Form a product (instead of sum), e.g.
Control flow Ruth Anderson UW CSE 160 Winter
CS 115 Lecture 17 2-D Lists Taken from notes by Dr. Neil Moore.
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.
String and Lists Dr. José M. Reyes Álamo.
Lecture 5 of Computer Science II
Introduction to Analysis of Algorithms
EGR 2261 Unit 10 Two-dimensional Arrays
Loops BIS1523 – Lecture 10.
Repetition Structures Chapter 9
multi-dimensional arrays
Two-dimensional arrays
Topics Introduction to Repetition Structures
Matrix 2015/11/18 Hongfei Yan zip(*a) is matrix transposition
CS 115 Lecture 8 Structured Programming; for loops
Matrix 2016/11/30 Hongfei Yan zip(*a) is matrix transposition
2-D Lists Taken from notes by Dr. Neil Moore
Week 9 - Monday CS 121.
Topics Introduction to Repetition Structures
Strings Part 1 Taken from notes by Dr. Neil Moore
Intro to PHP & Variables
Structured Programming; for loops Taken from notes by Dr. Neil Moore
While Loops BIS1523 – Lecture 12.
Boolean logic Taken from notes by Dr. Neil Moore
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Ruth Anderson UW CSE 160 Spring 2018
Ruth Anderson UW CSE 160 Winter 2017
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Repeating Instructions And Advance collection
Number and String Operations
Using files Taken from notes by Dr. Neil Moore
Data Structures – 1D Lists
Arrays 6-Dec-18.
Ruth Anderson UW CSE 140 Winter 2014
ARRAYS 1 GCSE COMPUTER SCIENCE.
Michael Ernst UW CSE 140 Winter 2013
String and Lists Dr. José M. Reyes Álamo.
Topics Sequences Introduction to Lists List Slicing
Computing Fundamentals
Loop Statements & Vectorizing Code
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Recursion Taken from notes by Dr. Neil Moore
Boolean logic Taken from notes by Dr. Neil Moore
Building Java Programs
For loops Taken from notes by Dr. Neil Moore
Relations And Functions.
Building Java Programs
Topics Sequences Introduction to Lists List Slicing
Building Java Programs
Python Review
Introduction to Computer Science
Building Java Programs
Loop Statements & Vectorizing Code
Class code for pythonroom.com cchsp2cs
Strings Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Control flow: Loops UW CSE 160.
Presentation transcript:

2-D Lists Taken from notes by Dr. Neil Moore CS 115 Lecture 2-D Lists Taken from notes by Dr. Neil Moore

Nested loops Notice that in program 2 you had essentially a loop inside another loop: the main function had a loop that played the whole game, and outside the loop it had another loop, for playing multiple games. This is called a nested loop. Which of the two loops iterates more times? the inner loop Once the inner loop finishes (game finishes), go to the next iteration of the outer loop (play another game). What if something should need to happen before/after each round? Put it inside the outer loop but not in the inner loop

Counting iterations Let’s use nested loops to print out a multiplication table. mult-table.py

Counting iterations How any times did we print a number? 10 times in the first iteration 10 times in the second iteration And so on… 10 x 10 = 100 times altogether When the inner loop’s sequence is the same each time: Total iterations = outer iterations x inner iterations If the inner loop doesn’t execute the same number of times each time, add up all the inner iterations to find the total for i in range(5): for j in range(i): # note, this is an “i“ not a 1 print(i,j) How many times does the print execute? 0 + 1 + 2 + 3 + 4 = 10 times

Two-dimensional lists Nested loops are particularly useful when we have nested lists That is, a list that contains other lists. That is also called a two-dimensional list Why would we use a 2D list? For storing a table of data Anything you would put in a spreadsheet Weather forecasts: row = city, column = days, data in cells = temperatures Grade book: row = student, column = assignment, data in cells = grade Or a game board For example, an 8x8 chess board Make a list of 8 rows Each row is a list of 8 squares Matrices Very useful for representing pixels in a graphics window Used all the time for “big data”

Row-major order In this class we’ll look at a 2-D list as “row-major” order. That means that the rows are the horizontal elements of the table, and they are numbered from 0 at the first row, increasing down to the bottom row And columns are the vertical components of the table. Each column is numbered from 0 at the left end, increasing as you move to the right. When you refer to a single element of a 2-D list, the row is given first, then the column “matrix[3][2]” is in the 4th row and 3rd column Typically you put the row on the outer loop and the column on the inner loop to process each element of the 2-D list

Creating 2D lists There are (at least) two ways to make a 2D list Hard code it table = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]] Row 0 is [ 1, 2, 3 ], etc. Or build it a row at a time - this method is MUCH more flexible!! First, create an empty list to hold the rows, table = [ ] Then create the row lists and append them to the outer list for rownum in range(5): # 5 rows row = [0 ] * 3 # 3 columns table.append(row) Why not just say this? table = [ [ 0, 0, 0 ] ] * 5 That makes all the rows aliases of each other! You really only have ONE row, not 5!!

Accessing 2D lists Suppose you have a list with 5 rows and 3 columns, called table. How do we access the element in the second row, first column? Take it a step at a time (for explanation, not necessary every time): How do you access the second row? row = table[1] What type is the second row? a ONE D list So now to get to the first column in the second row, element = row[0] Or, to put it together as element = table[1][0] Summary: to access an element in a 2D list, use list2D[row][column] This is a variable name just like x. It can be assigned to, printed, compared to another variable or constant, used in calculations, etc.

Traversing a 2D list To iterate over the contents of a 2D list, we need a nested loop Outer loop: for each row Inner loop: for each column in that row If we only need the elements, not the subscripts: for row in table: # row is a 1D list for element in row: process the element If we DO need subscripts, use ranges instead for rowno in range(len(table)): # len = number of rows for colon in range(len(table[rowno])): #len of one row process element in position [rowno][colno]

Tables with “rough edges” The previous slides assumed that each row of a table was the same length, “5 rows by 3 columns”. This IS the way 2-d lists are formed in other languages. But in Python they don’t have to be! Each row can have a different length if you want it to. They all start numbering at the zeroth column, as usual, but one row could be 5 elements, one row could be one element, one could be 20! This is easily handled by the code that was shown on the previous slide, either version (whether you need the subscripts or you don’t)

So be careful! It is easy to assume that a 2-d list is square (same number of rows and columns) for i in range(len(table)): for j in range(len(table)): # NOTE: this is different from the previous slides print(table[i][j]) This code would work as long as it was a square table! If you assumed that all rows were the same length, for j in range(len(table[0])): # NOTE: this is different from above! This code would work as long as the assumption is true!

Changing a 2D list element If you need to change an element, you need its subscripts! Suppose you just wanted to set all elements of an existing table to 0 for r in table: # r is a list that is one row for el in r: # el is one element in the row el = 0 Does NOT accomplish what you want to do! It just sets a temporary variable el to zero, over and over! What you need is for i in range(len(table)): for j in range(len(table[i])): table[i][j] = 0 This refers to the actual table element! And is what you want!

A large example: tic-tac-toe We’ll use a 2D list to represent a tic-tac-toe board. Each element in the list will be “X”, “O” or a space Use loops to print the board and to check whether someone won tictactoe.py