MIS Programming Assignment 4

.docx

School

University Of Arizona *

*We aren’t endorsed by this school

Course

301

Subject

Computer Science

Date

Apr 3, 2024

Type

docx

Pages

4

Uploaded by CoachDiscovery2101

Report
MIS Programming Assignment 4 By Tanishka Bansal Code: # Tanishka Bansal Programming Assignment 4 def main(): # print basic Info about the program using info function info() # Read and split data file and store in square_data # dimension of the first square is the first value in square_data square_data = open("magicData.txt") all_data = square_data.read().split() index = 0 number = 1 while index < len(all_data) and all_data[index] != '-1': size = int(all_data[index]) print("The size of the square is:", size) print("*" * 5, "Square", number, "*" * 5) square = [[0] * size for _ in range(size)] # prints out matrix using nested loops index += 1 for i in range(size): for j in range(size): square[i][j] = int(all_data[index]) print(square[i][j], end=" ") index += 1 print() # use sum_rows function to compute the sum of each of the rows row_sums = sum_rows(square) # use sum_cols function to compute the sum of each of the columns col_sums = sum_cols(square) # use sum_main_diag to compute the sum of the main diagonal main_diag_sum = sum_main_diag(square) # use sum_off_diag to compute the sum of the off diagonal off_diag_sum = sum_off_diag(square)
# determine if the square matrix is perfect and print the result is_perfect = is_magic_square(row_sums, col_sums, main_diag_sum, off_diag_sum) print("Is it a magic square?", is_perfect) number += 1 square_data.close() def sum_rows(matrix): return [sum(row) for row in matrix] def sum_cols(matrix): return [sum(col) for col in zip(*matrix)] def sum_main_diag(matrix): return sum(matrix[i][i] for i in range(len(matrix))) def sum_off_diag(matrix): return sum(matrix[i][len(matrix) - i - 1] for i in range(len(matrix))) def is_magic_square(row_sums, col_sums, main_diag_sum, off_diag_sum): # Check if all row sums, column sums, and diagonals have the same value return all(val == row_sums[0] for val in row_sums) \ and all(val == col_sums[0] for val in col_sums) \ and main_diag_sum == off_diag_sum == row_sums[0] def info(): print("This program reads a series of square matrices from a file and determines if each matrix is a magic square.") main() Screenshot of code:
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help