Question

In: Computer Science

For this lab, you will work with two-dimensional lists in Python. Do the following: Write a...

For this lab, you will work with two-dimensional lists in Python. Do the following:

  1. Write a function that returns the sum of all the elements in a specified column in a matrix using the following header:
    def sumColumn(matrix, columnIndex)
  2. Write a function display() that displays the elements in a matrix row by row, where the values in each row are displayed on a separate line. Use a single space to separate different values. Sample output from this function when it is called on a 3 X 4 matrix is as follows:
    2.5 3.0 4.0 1.5
    1.5 4.0 2.0 7.5
    3.5 1.0 1.0 2.5
    
  3. Given this partial code
    def getMatrix(numRows, numColumns):
        '''returns a matrix with the specified number of rows and columns'''
        m = [] # the 2D list (i.e., matrix), initially empty
        for row in range(numRows):
            matrix_dimensions_string = str(numRows) + "-by-" + str(numColumns)
            line = input("Enter a " + matrix_dimensions_string + " matrix row for row " + str(row) + ": ")
        
            
        return m    
    write a function called getMatrix(numRows, numColumns) that returns a matrix with numRows rows and numColumns columns. The function reads the values of the matrix from the user on a row by row basis. The values of each row must be entered on one line using a space to separate the values. Use loops in your solution. A sample run of this function when it is caled as getMatrix(3, 4) to return a 3 by 4 matrix is as follows. Values shown in red are entered by the user:
    Enter a 3-by-4 matrix row for row 0: 2.5 3 4 1.5
    Enter a 3-by-4 matrix row for row 1: 1.5 4 2 7.5
    Enter a 3-by-4 matrix row for row 2: 3.5 1 1 2.5
    

Use the following function to test your code:

def main():
    m = getMatrix(3, 4)
    print("\nThe matrix is")
    display(m)

    print()
    for col in range(len(m[0])):
        print("Sum of elements for column %d is %.2f" % (col, sumColumn(m,col)))          

main()

A sample program run is as follows:

Enter a 3-by-4 matrix row for row 0: 1 22 3.7869 8
Enter a 3-by-4 matrix row for row 1: 4 5.6543 3 3
Enter a 3-by-4 matrix row for row 2: 1 1 1 1

The matrix is
1.0 22.0 3.7869 8.0 
4.0 5.6543 3.0 3.0 
1.0 1.0 1.0 1.0 

Sum of elements for column 0 is 6.00
Sum of elements for column 1 is 28.65
Sum of elements for column 2 is 7.79
Sum of elements for column 3 is 12.00

The format of the input and output of your program must be as in the sample run.

Solutions

Expert Solution

Program

def getMatrix(numRows, numColumns):
    '''returns a matrix with the specified number of rows and columns'''
    m = [] # the 2D list (i.e., matrix), initially empty
    for row in range(numRows):
        matrix_dimensions_string = str(numRows) + "-by-" + str(numColumns)
        line = input("Enter a " + matrix_dimensions_string + " matrix row for row " + str(row) + ": ")
        row = line.split(' ')
        row = [float(i) for i in row]
        m.append(row)
      
      
    return m

def display(m):
    for row in m:
        print (" ".join([str(col) for col in row]))
      
def sumColumn(matrix, columnIndex):
    return sum([row[columnIndex] for row in matrix])

def main():
    m = getMatrix(3,4)
    print("\nThe matrix is")
    display(m)

    print()
    for col in range(len(m[0])):
        print("Sum of elements for column %d is %.2f" % (col, sumColumn(m,col)))        

main()

Output

Enter a 3-by-4 matrix row for row 0: 1 22 3.7869 8
Enter a 3-by-4 matrix row for row 1: 4 5.6543 3 3
Enter a 3-by-4 matrix row for row 2: 1 1 1 1

The matrix is
1.0 22.0 3.7869 8.0
4.0 5.6543 3.0 3.0
1.0 1.0 1.0 1.0

Sum of elements for column 0 is 6.00
Sum of elements for column 1 is 28.65
Sum of elements for column 2 is 7.79
Sum of elements for column 3 is 12.00

Screenshot


Related Solutions

Overview: You will write a python program that will work with lists and their methods allowing...
Overview: You will write a python program that will work with lists and their methods allowing you to manipulate the data in the list. Additionally you will get to work with randomization. Instructions: Please carefully read the Instructions and Grading Criteria. Write a python program that will use looping constructs as noted in the assignment requirements. Name your program yourlastname_asgn5.py Assignment Requirements IMPORTANT: Follow the instructions below explicitly. Your program must be structured as I describe below. Write a Python...
Given two lists, write python code to print “True” if the two lists have at least...
Given two lists, write python code to print “True” if the two lists have at least one common element. For example, x = [1,2,3], y=[3,4,5], then the program should print “True” since there is a common element 3.
PYTHON Computer Science Objectives Work with lists Work with functions Work with files Assignment Write each...
PYTHON Computer Science Objectives Work with lists Work with functions Work with files Assignment Write each of the following functions. The function header must be implemented exactly as specified. Write a main function that tests each of your functions. Specifics In the main function ask for a filename and fill a list with the values from the file. Each file should have one numeric value per line. This has been done numerous times in class. You can create the data...
Using Python write a function that implements the following two-dimensional objective function: F (x, y) =...
Using Python write a function that implements the following two-dimensional objective function: F (x, y) = (x^2 + y − 11)^2 + (x + y^2 − 7 )^22 . Determine how many local minimums and maximums and their location for this objective function.
Build a two dimensional array out of the following three lists. The array will represent a...
Build a two dimensional array out of the following three lists. The array will represent a deck of cards. The values in dCardValues correspond to the card names in dCardNames. Note that when you make an array all data types must be the same. Apply dSuits to dCardValues and dCardNames by assigning a suit to each set of 13 elements. dCardNames = ['2','3','4','5','6','7','8','9','10','J','Q','K','A'] dCardValues = ['2','3','4','5','6','7','8','9','10','11','12','13','14'] dSuits = ["Clubs","Spades","Diamonds","Hearts"] Once assigned your two dimensional array should resemble this : 2...
Python: Write a function that receives a one dimensional array of integers and returns a Python...
Python: Write a function that receives a one dimensional array of integers and returns a Python tuple with two values - minimum and maximum values in the input array. You may assume that the input array will contain only integers and will have at least one element. You do not need to check for those conditions. Restrictions: No built-in Python data structures are allowed (lists, dictionaries etc). OK to use a Python tuple to store and return the result. Below...
Python Code Needed Two-Player, Two-Dimensional Tic-Tac-Toe Write a script to play two-dimensional Tic-Tac-Toe between two human...
Python Code Needed Two-Player, Two-Dimensional Tic-Tac-Toe Write a script to play two-dimensional Tic-Tac-Toe between two human players who alternate entering their moves on the same computer. Create a 3-by-3 two-dimensional array. Each player indicates their moves by entering a pair of numbers representing the row and column indices of the square in which they want to place their mark, either an 'X' or an 'O'. When the first player moves, place an 'X' in the specified square. When the second...
Longest ‘A’ Path Objectives Manipulating two-dimensional lists Using recursion to solve a problem Problem Specification Write...
Longest ‘A’ Path Objectives Manipulating two-dimensional lists Using recursion to solve a problem Problem Specification Write a Python application to find the longest ‘A’ path on a map of capital (uppercase) letters. The map is represented as a matrix (2-dimensional list) of capital letters. Starting from any point, you can go left, right, up and down (but not diagonally). A path is defined as the unbroken sequence of letters that only covers the spots with the letter A. The length...
Please include comments on what you are doing.   Using linked lists, write a Python program that...
Please include comments on what you are doing.   Using linked lists, write a Python program that performs the following tasks: store the records for each college found in the input file - colleges.csv - into a linked list. (File includes name and state data fields) allow the user to search the linked list for a college’s name; display a message indicating whether or not the college’s name was in the database allow the user to enter a state's name and...
Use PYTHON --Nested Lists and DateTime Module. Write a program that does the following: Reads information...
Use PYTHON --Nested Lists and DateTime Module. Write a program that does the following: Reads information from a text file into a list of sublists. Be sure to ask the user to enter the file name and end the program if the file doesn’t exist. Text file format will be as shown, where each item is separated by a comma and a space: ID, firstName, lastName, birthDate, hireDate, salary Store the information into a list of sublists called empRoster. EmpRoster...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT