From 913bd2198fa356651e23e90e9552a5b78e378b50 Mon Sep 17 00:00:00 2001 From: chirvasitua Date: Mon, 9 Aug 2021 19:49:22 -0400 Subject: 1st commit on 125_python --- challenge-125/stuart-little/python/ch-2.py | 57 ++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100755 challenge-125/stuart-little/python/ch-2.py (limited to 'challenge-125/stuart-little/python/ch-2.py') diff --git a/challenge-125/stuart-little/python/ch-2.py b/challenge-125/stuart-little/python/ch-2.py new file mode 100755 index 0000000000..9b5b75aa84 --- /dev/null +++ b/challenge-125/stuart-little/python/ch-2.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python + +import sys + +def lr(tree): + if (len(tree) < 3 or tree[0] == '.'): + return [[],[]] + if len(tree) == 3: + return [["."],["."]] + left=[] + sm,ix = 0,1 + while sm != -1: + left.append(tree[ix]) + sm+=(-1 if tree[ix] == '.' else 1) + ix+=1 + right = tree[len(left)+1:] + return [left,right] + +def lrLongPath(tree): + if tree[0] == '.': + return [[],[]] + if len(tree) == 3: + return [[tree[0]],[tree[0]]] + left,right = lr(tree) + lLongPath = [tree[0]] + max(lrLongPath(left), key=len) + rLongPath = [tree[0]] + max(lrLongPath(right), key=len) + return [lLongPath,rLongPath] + +def biLongPath(tree): + if len(tree) < 3 or tree[0] == '.': + return [] + if len(tree) == 3: + return [tree[0]] + lPath,rPath = lrLongPath(tree) + path = list(reversed(lPath[1:])) + rPath + left,right = lr(tree) + return max([path]+list(map(biLongPath, [left,right])), key=len) + +print(" ".join(biLongPath(sys.argv[1:]))) + +""" +run