Matrices-Practice-Tool / src / QuestionClasses / question_file_writer.py
question_file_writer.py
Raw
'''Question file writer objects'''

import sys
import numpy as np
WARNING = '\033[93m'


class QuestionFileWriter:
    '''Class to write question data to .txt files'''
    file_name = ''
    output = []
    question = 0

    def __init__(self, file_name:str , question:str):
        '''Constructor'''
        self.file_name = file_name
        self.question = question
        self.output = []

    def write_to(self):
        '''Public method to write to file'''
        try:
            with open(self.file_name, 'x') as f:
                self.output.extend((str(self.question.q_type),
                                    self.write_matrices(self.question),
                                    str(self.question.operation),
                                    self.write_answer(self.question)))
                f.write('$'.join(self.output))
        except FileExistsError as e:
            print(f'{WARNING}{e}')
            sys.exit(1)

    @staticmethod
    def np_to_list(matrix: np.array) -> list:
        '''Convert numpy array to list'''
        return str(matrix.flatten().tolist())

    def write_matrices(self, q: 'Question') -> str:
        '''Format matrix data'''
        matrices_data = []
        for (key, matrix) in q.matrices_dict.items():
            single = []
            single.extend((key,
                          str(np.shape(matrix)).replace(' ', ''),
                          self.np_to_list(matrix).replace(' ', '')))
            matrices_data.append('%'.join(single))
        return '$'.join(matrices_data)

    def write_answer(self, q: 'Question') -> str:
        '''Format answer data'''
        a_data = []
        a_data.append(str(np.shape(q.answer_matrix)).replace(' ', ''))
        a_data.append(self.np_to_list(q.answer_matrix).replace(' ', ''))
        return '%'.join(a_data)