User Tools

Site Tools


script:ex8

Exercise 8 Code

exercise8.py
# Answer key to lists notebook, exercise 8
 
'''
8e) Make a list, my_list, containing three values. Check that the object you
created is a list using the type() function.
'''
my_list = [1,2,3]
type(my_list)
 
 
'''
8f) Make the following three lists into a single matrix:
'''
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
matrix = [list1, list2, list3]
matrix
 
 
'''
8g) Using list indices, extract the value in row 2, column 2 from the matrix
in 8f.
'''
matrix[1][1]
 
 
'''
8h) Using slicing, extract the first two rows from the matrix in 8f.
'''
matrix[:2]
 
 
'''
8i) Using an index, extract the last row of the matrix in 8f, assuming you
don't know how many rows are in the matrix:
'''
matrix[-1]
 
 
'''
8j) Write a function, element_replace(matrix, n, i, c), that replaces the
element in the nth row and ith column with value c and returns a new matrix
containing the results.
'''
def element_replace(matrix, n, i, c):
    new_matrix = matrix
    new_matrix[n-1][i-1] = c
    return new_matrix
 
element_replace(matrix, 1, 2, 'a')
 
 
'''
8k) Write a function called sum_rows(matrix) that sums the elements in each
row in a matrix and returns the values as a list. Hint: use a nested for loop.
The outer for loop will iterate through each row and the nested for loop will
iterate through each element in each row.
'''     
def sum_rows(matrix):
    totals_list = []
    for i in range(len(matrix)):
        total = 0
        for n in range(len(matrix)):
            total += matrix[i][n]
        totals_list.append(total)
    return totals_list
 
sum_rows(matrix)
 
 
'''
8l) Write a function called sum_columns(matrix) that sums the elements in each
column in a matrix and returns the values as a list.
'''
def sum_columns(matrix):
    totals_list = []
    for i in range(len(matrix)):
        total = 0
        for n in range(len(matrix[i])):
            total += matrix[n][i]
        totals_list.append(total)
    return totals_list
 
sum_columns(matrix)
script/ex8.txt · Last modified: 2018/10/15 16:11 by dokuroot