Publications: 27 | Followers: 0

24_2Darray_nested_loops

Publish on Category: Birds 0

2D Array, Nested Loops
One dimensionalarrays and lists
We have learned lists and some applications.For example, for a given list of numbersa_listCompute the sumCompute the average
defcompute_sum(a_list):sum=0foriin range(len(a_list)):sum+=a_list[i]return sum
defcompute_avg(a_list):sum=compute_sum(a_list)return sum /len(a_list)
2D arrays and lists
Many other applications require 2D arrays and listsFor example, if we want to compute the average test scores of a class in which we havenstudents andktests. The data will look something like the following.In your up-coming labs and homework you will see other applications.We usually need nested loops to handle 2D data.
Sizing up arrays…
How could we create this rectangular array of0s?
or
x= 5*[ 3*[0] ]
x= 3*[ 5*[0] ]
[[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
4
or
x= 5*[ 3*[0] ]
x= 3*[ 5*[0] ]
[[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
Sizing up arrays…
How could we create this rectangular array of0s?
but NEITHER ONE works!
because lists are handledby reference!
5
Try ref_copy.py
What's really going on?
x= 3*[ 5*[0] ]
inner = 5*[0]
x= 3*[inner]
list
x
list
list
list
inner
inner
inner
copies the listreference, not the list data
"shallow copy"
7
Safelycreating arrays…
defcreate_one_row( width ):""" does just that """row = []# start with nothingforcolinrange( width ):row = row + [0]returnrow
So, how would you create alist of rows!?
# loop andappend!
8
Safelycreating arrays…
defcreate2d_array( width, height ):""" does just that """x= []# start with nothingforrow_countinrange( height ):row =[0] * widthx=x+ [row]returnx
the same approach as before!
9
24_create_arrays.py
Exercise
defmystery(x):""" what happens tox? """NUM_ROWS =len(x)NUM_COLS =len(x[0])forrowinrange( 0,NUM_ROWS ):forcolinrange( 0,NUM_COLS ):ifrow == col:x[row][col] = 42else:x[row][col] += 1
1 2 3 45 6 7 89 10 11 12
Before
After
x
x
Starting with the 2d arrayxshown here, what are the values inxafter running this code?
row 0
row 1
row 2
col 0
col 1
col 2
col 3
What are the resulting values inx?
10
Exercise
defmystery(x):""" what happens tox? """NUM_ROWS =len(x)NUM_COLS =len(x[0])forrowinrange( 0,NUM_ROWS ):forcolinrange( 0,NUM_COLS ):ifrow == col:x[row][col] = 42else:x[row][col] += 1
1 2 3 45 6 7 89 10 11 12
Before
After
x
x
Starting with the 2d arrayxshown here, what are the values inxafter running this code?
row 0
row 1
row 2
col 0
col 1
col 2
col 3
What are the resulting values inx?
11
$Maximum Profit$
Your stock'sprices by the day :
A good investmentstrategy: maximize your profit!
prices= [ 40, 80, 10, 30, 27, 52,5, 15 ]
DayPrice Stocks valid to sell040.0 40.0180.0 40.0, 80.0210.0 40.0, 80.0, 10.0330.0 40.0, 80.0, 10.0, 30.0427.0 …552.0 …65.0 …715.0 …
youmustsellafteryou buy.
12
>>> diff( [7,3],[0,6] )1
defdiff(lst1, lst2):
Return the minimum difference between one value fromlst1and one value fromlst2.
Example:
lst1andlst2will be lists of numbers
Only considerabsolutedifferences.
smallest difference
13
>>> diff( [7,3],[0,6] )1
defdiff(lst1, lst2):
Return the minimum difference between one value fromlst1and one value fromlst2.
Example:
lst1andlst2will be lists of numbers
Only considerabsolutedifferences.
smallest difference
14
min_diff_so_far=9999999forvalue1 in lst1:forvalue2 in lst2:diff= abs(value1 - value2)if diff <min_diff_so_far:min_diff_so_far= diffreturnmin_diff_so_far
How tocomputer the maximumdifference?
A few matrix and array problems
15
Given a matrix (2D array with equal dimension), how to compute the sum for the top-right half?
[[3,2,6,8],[9,2,5,7],[0,3,2,3],[1,2,3,4]]
The result should be 42
The key is to figure out the indices
16
[[3,2,6,8],[9,2,5,7],[0,3,2,3],[1,2,3,4]]
When row is 0, column goes from 0 to 3When row is 1, column goes from 1 to 3When row is 2, column goes from 2 to 3When row is 3, column goes from 3 to 3
0123
rows
0 1 2 3
columns
for row in range( 4 ):for col in range( row, 4 ):# do work
defsumUpperRight( matrix ):'''Sum up the upper-right corner of a matrix.Matrixisa2D array with equal dimensions '''sum= 0forrow in range(len( matrix ) ): # rowforcol in range( row,len( matrix[0] ) ): # columnsum+= matrix[row][col]return summatrix= [[3,2,6,8],[9,2,5,7],[0,3,2,3],[1,2,3,4]]value=sumUpperRight( matrix)print( 'the sum of right upper corner is ', value )
Given a matrix (2D array with equal dimension), how to compute the maximum for each row and each column?
# compute row max for a given ‘row’rowMax= matrix[row][0]foriin range(len( matrix[row] ) ):if matrix[row][i] > max:rowMax= matrix[row][i]
But how to go through a column to compute the maximum?
# compute column max for a given ‘column’colMax= matrix[0][col]foriin range(len( matrix ) ):if matrix[i][col] > max:rowMax= matrix[i][col]
In addition to the row and column maximum, find the maximum of the entire matrix?
deffindMax(matrix,rowMax,colMax):'''Givena matrix, find and return the global max, anarrayofrowmaxand an array of column max '''max = matrix[0][0] # current maxforiin range(len(matrix) ): # find each row maxrowMax[i] =findRowMax( matrix,i)ifrowMax[i] > max:max =rowMax[i]foriin range(len(matrix[0])): # find each column maxcolMax[i] =findColMax( matrix,i)ifcolMax[i] > max:max =colMax[i]return max

0

Embed

Share

Upload

Make amazing presentation for free
24_2Darray_nested_loops