Created
May 21, 2021 03:36
-
-
Save nevzatseferoglu/e7a939ceeadc00205dc3597bc80921a6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
PiWorks interview question solution (-v python3) | |
Nevzat Seferoglu | |
[email protected] | |
Gebze Technical University | |
''' | |
import sys | |
# returned path pocket | |
class ReturnValue: | |
def __init__(self, total, state, depth): | |
self.total = total | |
self.state = state | |
self.depth = depth | |
# return whether given input is a prime number | |
def isPrime(num): | |
if num < 2: | |
return False | |
for i in range(2, (num//2+1)): | |
if num % i == 0: | |
return False | |
return True | |
# traverse the possible path recursively | |
def traversePyramid(inList, index, depth): | |
curValue = ReturnValue(0, False, 0) | |
size = len(inList) | |
if index >= size: | |
return curValue | |
if isPrime(inList[index]): | |
curValue.state = True | |
curValue.depth = depth | |
return curValue | |
left = traversePyramid(inList, index + depth, depth + 1) | |
left.total += inList[index] | |
right = traversePyramid(inList, index + depth + 1, depth + 1) | |
right.total += inList[index] | |
if not left.state and right.state: | |
return left | |
elif not right.state and left.state: | |
return right | |
elif left.depth > right.depth: | |
return left | |
elif left.depth < right.depth: | |
return right | |
else: | |
return left if left.total > right.total else right | |
# behave input as a pyramid | |
def find(inList): | |
maxPath = traversePyramid(inList, 0, 1) | |
return maxPath.total | |
def script(inputfile): | |
with open(inputfile, 'r') as f: | |
return find([int(x) for x in f.read().split()]) | |
# takes inputfile file as a command line argument | |
if __name__ == '__main__': | |
if len(sys.argv) != 2: | |
print(f"Usage: python {sys.argv[0]} inputfile\n\ | |
inputfile: contains orthogonal triangle") | |
sys.exit(-1) | |
print(f"{script(sys.argv[1])}") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment