In: Computer Science
PYTHON LANGUAGE
PLEASE DO NUMBER 5 ONLY
"""
# 1. Based on Textbook R6.28
# Create a table of m rows and n cols and initialize with 0
m = 3
n = 4
# The long way:
table = []
for row in range(m) :
table.append([0]*n)
# The short way:
# 2. write a function to print the table in row, column
format,
# then call the function
'''
# using index
def printTable(t):
for i in range(len(t)) : # each i is an index, i = 0,1,2
for j in range(len(t[i])) : # j = 0,1,2,3
print(t[i][j], end=' ')
print()
'''
# without index:
def printTable(t):
for row in t :
for col in row :
print(col, end=' ')
print()
print()
printTable(table)
# what does the following print?
for i in range(m):
for j in range(n):
table[i][j] = i + j
printTable(table)
'''
Answer:
print: from these index values:
0 1 2 3 [0,0] [0,1] [0,2] [0,3]
1 2 3 4 [1,0] [1,1] [1,2] [1,3]
2 3 4 5 [2,0] [2,1] [2,2] [2,3]
'''
# 3. copy table to table2
table2 = copy.deepcopy(table)
'''
table2 = table => table2 is another reference to the same mem
location
table2 = table.copy() => shallow copy
only copy the 1D list (outer list) of references,
which has row1 - row4 references
table => [ row1 => [ , , , ]
row2 => [ , , , ]
row3 => [ , , , ]
row4 => [ , , , ]
]
'''
table[0][0] = -1 # will table2 be changed? No
printTable(table2)
# 4. fill elements of bottom row of table2 with -1's
# and all elements of left col of table2 with 0's
for i in range(len(table2[-1])) :
table2[-1][i] = -1
for i in range(len(table2)) :
table2[i][0] = 0
printTable(table2)
"""
"""
# 5. We start with a dictionary of student ids and
associated gpa's
d = {123:3.7, 456:3.8, 789:2.7, 120:2.8}
print(d)
# create a list of sid list and a tuple of gpa from d
# create a list of tuples (k,v) from d
# How do you construct a dictionary from a list of tuples?
# How do you construct a dictionary from the list of id and
gpa?
"""
Request : Please increase your Brightness...above images are only for comments...
Code:
Output: