'''
P.I. WORKS Technical Assignment 
Simay Yazicioglu

This script finds maximum sum of the numbser in a  orthogonal triangle input 
according to the given rules below:
1. You will start from the top and move downwards to an adjacent number as in below.
2. You are only allowed to walk downwards and diagonally.
3. You can only walk over NON PRIME NUMBERS.
4. You have to reach at the end of the pyramid as much as possible.
5. You have to treat your input as pyramid.

This file can also be imported as a module and contains the following
functions:
    * fill_array - returns a 2D array based on the triangle input in the file
    * is_prime - given a number returns if the number is prime or not
    * solve -uses dynamic programming to find maximum sum in the 2D array
    * main- main function of the script
'''
def fill_array(file_name):
    """reads the file, gets the triangular input, 
    and fills the 2D array based on the input data

    Parameters
    ----------
    file_name : string
        The name of the file that contains the triangle input
    
    Returns
    -------
    array
        2D array that represents the data in the triangle input
    """
    with open(file_name, 'r') as file_obj:
        count = 0
        array =  []#2D array
        for line in file_obj:
            count+=1
            line_lst = line.strip().split(" ")
            array_row = []
            for num in line_lst:
                if is_prime(int(num)):
                    array_row.append(float('-inf'))
                else:
                    array_row.append(int(num))
            array.append(array_row)
        #fill the rest of the array_row with 0
        for row  in range(count):
            for col in range(count-row-1, 0, -1):
                array[row].append(0)
        return array

def is_prime(n):
    """checks if the number is prime

    Parameters
    ----------
    n : int
        The number we want to check
    
    Returns
    -------
    boolean
        True if number is prime, false otherwise
    """
    if (n <= 1) : 
        return False
    if (n <= 3) : 
        return True
    if (n % 2 == 0 or n % 3 == 0) : 
        return False
    i = 5
    while(i * i <= n) : 
        if (n % i == 0 or n % (i + 2) == 0) : 
            return False
        i = i + 6
    return True

def solve(arr): 
    """uses dynamic programming to find maximum sum in the 2D array

    Parameters
    ----------
    arr : list
        The 2D array that represents the triangle input values
    
    Returns
    -------
    float
        returns the max sum, or if that's not possible  returns negative infinity
    """
    row = len(arr)
    for r in range(row-1-1, -1,-1):
        for c in range(0,r+2-1):
            elem1 = arr[r+1][c]
            elem2 =  arr[r+1][c+1]
            #if either of the elems are -inf, then dont check prime
            if elem1 == float('-inf') and elem2==float('-inf'):
                continue
            elif  not (elem1 == float('-inf')) and not (elem2==float('-inf')):
                    m = max(arr[r+1][c+1] , arr[r+1][c])
                    arr[r][c] += m  # current arr[r][c]
            elif elem1 == float('-inf'): #only elem1 negative infinity
                arr[r][c] += elem2  # current arr[r][c]
            else: #only elem2 negative infinity
                arr[r][c] += elem1  # current arr[r][c]
    return arr[0][0]
    
def main():
    '''
    Main function for the script.
    Given a file name, main function calls the function to fill the array with the triangle input given in the file
    and calls the function to find the max sum.
    Then prints the maximum sum if found, else prints 'No possible path' 
    '''
    arr = fill_array('triangle.txt')
    path_sum = solve(arr)
    if path_sum == float('-inf'):
        print('No posssible path')
    else:
        print(path_sum)

if __name__ == "__main__":
    main() 

Python Online Compiler

Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.

Taking inputs (stdin)

OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.

import sys
name = sys.stdin.readline()
print("Hello "+ name)

About Python

Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.

Tutorial & Syntax help

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition IF-ELSE is used.

if conditional-expression
    #code
elif conditional-expression
    #code
else:
    #code

Note:

Indentation is very important in Python, make sure the indentation is followed correctly

2. For:

For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.

Example:

mylist=("Iphone","Pixel","Samsung")
for i in mylist:
    print(i)

3. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while condition  
    #code 

Collections

There are four types of collections in Python.

1. List:

List is a collection which is ordered and can be changed. Lists are specified in square brackets.

Example:

mylist=["iPhone","Pixel","Samsung"]
print(mylist)

2. Tuple:

Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.

Example:

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)

Below throws an error if you assign another value to tuple again.

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)

3. Set:

Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.

Example:

myset = {"iPhone","Pixel","Samsung"}
print(myset)

4. Dictionary:

Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.

Example:

mydict = {
    "brand" :"iPhone",
    "model": "iPhone 11"
}
print(mydict)

Supported Libraries

Following are the libraries supported by OneCompiler's Python compiler

NameDescription
NumPyNumPy python library helps users to work on arrays with ease
SciPySciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation
SKLearn/Scikit-learnScikit-learn or Scikit-learn is the most useful library for machine learning in Python
PandasPandas is the most efficient Python library for data manipulation and analysis
DOcplexDOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling