aboutsummaryrefslogtreecommitdiff
path: root/challenge-129/paulo-custodio/python/ch-1.py
blob: a04cfac0e9f3a34046210342c6bb428aade9fc43 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#!/usr/bin/env python3

# Challenge 129
#
# TASK #1 > Root Distance
# Submitted by: Mohammad S Anwar
# You are given a tree and a node of the given tree.
#
# Write a script to find out the distance of the given node from the root.
#
# Example 1:
# Tree:
#         1
#        / \
#       2   3
#            \
#             4
#            / \
#           5   6
#
# Node: 6
# Output: 3 as the distance of given node 6 from the root (1).
#
# Node: 5
# Output: 3
#
# Node: 2
# Output: 1
#
# Node: 4
# Output: 2
# Example 2:
# Tree:
#         1
#        / \
#       2   3
#      /     \
#     4       5
#      \     /
#       6   7
#      / \
#     8   9
#
# Node: 7
# Output: 3 as the distance of given node 6 from the root (1).
#
# Node: 8
# Output: 4
#
# Node: 6
# Output: 3

import fileinput
import re
import sys

class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

    def __repr__(self):
        return "Node(value: {}, left: {}, right: {})" \
                .format(self.value, self.left, self.right)

def read_input():
    lines = []
    for line in fileinput.input():
        lines.append(line)
    return lines

def parse_subtree(lines, row, col):
    def ch(row, col):
        if row < 0 or row >= len(lines) or \
           col < 0 or col >= len(lines[row]):
            return ' '
        else:
            return lines[row][col]

    tree = Node(int(lines[row][col]))
    if ch(row + 1, col - 1) == '/':
        tree.left = parse_subtree(lines, row + 2, col - 2)
    if ch(row + 1, col + 1) == '\\':
        tree.right = parse_subtree(lines, row + 2, col + 2)

    return tree

def parse(lines):
    found = re.search("^[ ]+\d", lines[0])
    col = found.span()[1] - 1
    return parse_subtree(lines, 0, col)

def root_dist(tree, value):
    def subtree_dist(node, value, dist):
        if value == node.value:
            return dist
        if node.left:
            found = subtree_dist(node.left, value, dist+1)
            if found > 0:
                return found
        if node.right:
            found = subtree_dist(node.right, value, dist+1)
            if found > 0:
                return found
        return -1

    return subtree_dist(tree, value, 0)

value = int(sys.argv.pop())
tree = parse(read_input())
dist = root_dist(tree, value)
print(dist)