Skip to content

Instantly share code, notes, and snippets.

@tomkaith13
Created May 17, 2014 02:14
Show Gist options
  • Save tomkaith13/38cc6b0f17664ba415ae to your computer and use it in GitHub Desktop.
Save tomkaith13/38cc6b0f17664ba415ae to your computer and use it in GitHub Desktop.
"""
Problem:
PASS TRIANGLE
CHALLENGE DESCRIPTION:
By starting at the top of the triangle and moving to adjacent numbers on the row below, the maximum total from top to bottom is 27.
5
9 6
4 6 8
0 7 1 5
5 + 9 + 6 + 7 = 27
INPUT SAMPLE:
Your program should accept as its first argument a path to a filename. Input example is the following
5
9 6
4 6 8
0 7 1 5
"""
import sys
def pass_triangle(OList, lvl):
if lvl == 0:
root = OList[lvl][0]
left = OList[lvl+1][0]
right = OList[lvl+1][1]
OList[lvl][0] = max(left+root, right+root)
return
for i,item in enumerate(OList[lvl]):
#print i,item
root = OList[lvl][i]
left = OList[lvl+1][i]
right = OList[lvl+1][i+1]
OList[lvl][i]= max(root + left, root + right)
pass_triangle(OList,lvl-1)
outerList=[]
def main(argv):
sum = 0
if len (argv) != 2:
print 'Please give the filename as the arg'
print 'the len argv is:',len(argv),'and the argv is',argv
exit(1)
try:
fd = open(argv[1], 'r')
except IOError as e:
print 'Encounter exception',e
level=1
index = 0
max_list=[]
for line in fd:
#print line
if line != '\n':
innerList = line.strip().split()
outerList.append(map(int, innerList))
else:
break
#print outerList
pass_triangle(outerList, len(outerList)-2)
print outerList[0][0]
fd.close()
if __name__ == "__main__":
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment