a = [] ff = open('triangle.txt', 'r') for i in ff.readlines(): tmp = i.split(' ') for j in xrange(len(tmp)): tmp[j] = int(tmp[j]) a.append(tmp) ff.close() path = a[-1][:] for i in xrange(len(a) - 2, 0, -1): newpath = [] for j in xrange(i + 1): better = max(path[j], path[j + 1]) newpath.append(a[i][j] + better) path = newpath print max(path) + a[0][0] ''' path = [[a[0][0], [a[0][0]]]] for i in xrange(1, len(a)): newpath = [] tmp = path[0][1][:] tmp.append(a[i][0]) newpath.append([path[0][0] + a[i][0], tmp]) for j in xrange(1, i): flag = (path[j - 1][0] > path[j][0]) and -1 or 0 tmp = path[j + flag][1][:] tmp.append(a[i][j]) newpath.append([path[j + flag][0] + a[i][j], tmp]) tmp = path[i - 1][1][:] tmp.append(a[i][i]) newpath.append([path[i - 1][0] + a[i][i], tmp]) path = newpath maxx = [0, 0] for i in path: if i[0] > maxx[0]: maxx = i print maxx '''