CMU 15-110: Principles of Computing
Week7 Practice (Due never)
Contents:
1. Code Tracing
What will this code print? Figure it out by hand, then run the code to confirm. Then slightly edit the code and try again.
- Trace #1:
def ct1(L): rows = len(L) cols = len(L[0]) r = c = 0 b = L[0][0] for row in range(rows): for col in range(cols): if (L[row][col] > b): b = L[row][col] r = row c = col return [r, c] print(ct1([ [5, 2, 3, 1], [6, 0, 8, 4] ]))
- Trace #2:
def make2dList(rows, cols, defaultValue=None): a=[] for row in range(rows): a.append([defaultValue]*cols) return a def print2dList(a): # For a nicer but more complex version, see http://goo.gl/eiZ42n print('[') for row in range(len(a)): print(' ', a[row]) print(']') def ct2(L): # Hint: we've seen this before, in a very different way rows = len(L) cols = len(L[0]) M = make2dList(rows+1, cols+1) for row in range(rows): total = 0 for col in range(cols): M[row][col] = L[row][col] total += M[row][col] M[row][cols] = total%2 for col in range(cols+1): total = 0 for row in range(rows): total += M[row][col] M[rows][col] = total%2 return M print2dList(ct2([ [ 0, 1, 1, 0 ], [ 1, 1, 0, 0 ], [ 1, 1, 1, 0 ], [ 0, 1, 1, 0 ] ]))
- Trace #3:
def ct3(L): # Hint: we've seen this before, too! rows = len(L) cols = len(L[0]) r = c = None for row in range(rows): total = 0 for col in range(cols): total += L[row][col] if (total % 2 == 1): r = row for col in range(cols): total = 0 for row in range(rows): total += L[row][col] if (total % 2 == 1): c = col return [r, c] print(ct3([ [0, 1, 1, 0, 0], [1, 1, 0, 0, 0], [1, 1, 1, 0, 1], [0, 0, 1, 0, 0], [0, 0, 1, 0, 1] ]))
- CSV Data Challenge
For this exercise, we will analyze CSV data found online such as here:
https://github.com/fivethirtyeight/data
- Download this file. It contains two years of daily weather data for New York City.
- Open the file in Excel and inspect it, so you understand what's in the file. Do not edit it.
- Open the file in Sublime or in pyzo to inspect it, and see that it really is comma-separated data. Again, do not edit it.
- Using Python, and the readCsvFile function from
here,
answer the following questions:
- What was the largest temperature range (difference between the max and min temperatures) for any given day over the 2-year period?
- On which days did that occur?
- To give us some perspective on this, what was the average daily range in that time period?
- Think up a few other interesting questions one can ask about this data set, and then working together, write the code to answer the questions.
- More 2d-List Practice
See here