diff options
| author | Dave Jacoby <jacoby.david@gmail.com> | 2021-08-16 15:30:40 -0400 |
|---|---|---|
| committer | Dave Jacoby <jacoby.david@gmail.com> | 2021-08-16 15:30:40 -0400 |
| commit | 637f7bbeceeaf4a26e1e6ecba8c6fcb308790bb3 (patch) | |
| tree | 9809af6d10a767e998f569b80cabfdeb979ece95 /challenge-125/stuart-little/python/ch-2.py | |
| parent | 989dcde471a30935b8e51c557b971496963caffc (diff) | |
| parent | d9bbad705412903ffd55fb8c07bedcaeae734f85 (diff) | |
| download | perlweeklychallenge-club-637f7bbeceeaf4a26e1e6ecba8c6fcb308790bb3.tar.gz perlweeklychallenge-club-637f7bbeceeaf4a26e1e6ecba8c6fcb308790bb3.tar.bz2 perlweeklychallenge-club-637f7bbeceeaf4a26e1e6ecba8c6fcb308790bb3.zip | |
Merge branch 'master' of https://github.com/manwar/perlweeklychallenge-club
Diffstat (limited to 'challenge-125/stuart-little/python/ch-2.py')
| -rwxr-xr-x | challenge-125/stuart-little/python/ch-2.py | 57 |
1 files changed, 57 insertions, 0 deletions
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 <script> <tree in preorder form with '.' for empty nodes, entered as space-separated values> + +ref: https://stackoverflow.com/a/2676849/11064961 + +e.g. 1 2 4 . 7 . . . 3 5 . . 6 . . represents the tree + + 1 + / \ + 2 3 + / / \ + 4 5 6 + \ + 7 + +given as an example in the problem formulation at https://perlweeklychallenge.org/blog/perl-weekly-challenge-113/#TASK2 +""" |
