Answer:
To create a Python program that processes a text file containing several arrays, you can use the following code:
import numpy as np
import os
# Read input file
with open('input.txt', 'r') as f:
contents = f.readlines()
# Create dictionary to store matrices
matrices = {}
# Loop over lines in input file
for line in contents:
# Remove whitespace and split line into elements
elements = line.strip().split(',')
# Check if line is empty
if len(elements) == 0:
continue
# Get matrix name and dimensions
name = elements[0]
shape = tuple(map(int, elements[1:]))
# Get matrix data
data = np.zeros(shape)
for i in range(shape[0]):
line = contents.pop(0).strip()
while line == '':
line = contents.pop(0).strip()
row = list(map(int, line.split(',')))
data[i,:] = row
# Store matrix in dictionary
matrices[name] = data
# Create output files
output_dir = 'output'
if not os.path.exists(output_dir):
os.mkdir(output_dir)
for i in range(1, 6):
output_file = os.path.join(output_dir, str(i) + '.txt')
with open(output_file, 'w') as f:
# Check which point to process
if i == 1:
# Print matrices with values included in A matrix
A = matrices['A']
for name, matrix in matrices.items():
if np.all(np.isin(matrix, A)):
f.write(name + '\\')
f.write(str(matrix) + '\\\\')
elif i == 2:
# Swap secondary diagonal with first column in square matrices
for name, matrix in matrices.items():
if matrix.shape[0] == matrix.shape[1]:
matrix[:,[0,-1]] = matrix[:,[-1,0]] # Swap columns
matrix[:,::-1] = np.fliplr(matrix) # Flip matrix horizontally
f.write(name + '\\')
f.write(str(matrix) + '\\\\')
elif i == 3:
# Calculate average of all elements in each matrix
for name, matrix in matrices.items():
f.write(name + '\\')
f.write(str(np.mean(matrix)) + '\\\\')
elif i == 4
Step-by-step explanation: