def is_prime(num): """ Check whether given number is prime :param num: any number to check :return: a boolean value that shows whether the number is prime(true or false) """ if num == 1 or num == 2: return False else: for i in range(num): if i != 0 and i != 1: if num % i == 0: return False return True class PyramidCalculator: """A class for calculating the possible maximum sum where all the numbers are prime and the only allowed path is downwards or diagonally""" def __init__(self, file): """ Initializer(constructor) of the class :param file: a file that contains number values """ self.file = file self.num_list = self.extract_from_file() self.ROW_NUMBER = len(self.num_list) - 1 self.convert_to_int() def extract_from_file(self): """ Extract all lines from the file and store each number separately in a file :return: a file that contains all number separately in each line """ temp_list = list() for line in self.file.readlines(): temp_list.append(line.split()) return temp_list def convert_to_int(self): """ Convert all the numbers in the file into integer :return: a list where all numbers are integers """ for line in self.num_list: for i in range(len(line)): line[i] = int(line[i]) return self.num_list def max_sum(self): """ Calculate the possible maximum sum where all the numbers are prime and the path is downwards or diagonally :return: possible maximum sum """ pyramid = self.num_list row = self.ROW_NUMBER for i in range(row-1, -1, -1): for j in range(i + 1): temp1 = pyramid[i + 1][j] temp2 = pyramid[i + 1][j + 1] if is_prime(pyramid[i][j]): pyramid[i][j] = -1 if i == row - 1: if pyramid[i][j] != -1: if is_prime(temp1) and is_prime(temp2) is False: pyramid[i][j] += temp2 elif is_prime(temp2) and is_prime(temp1) is False: pyramid[i][j] += temp1 elif is_prime(temp1) and is_prime(temp2): pyramid[i][j] = -1 else: if pyramid[i][j] != -1: pyramid[i][j] += max(temp1, temp2) print(pyramid[0][0]) sample_file = open("assignment.txt") pyramid_calculator = PyramidCalculator(sample_file) pyramid_calculator.max_sum()