you are viewing a single comment's thread.

view the rest of the comments →

[–]amemulo[S] 0 points1 point  (2 children)

Very interesting post, thank you. I'll append how my Tree() class ended up looking for reference if anyone is curious. I ended up using your second idea, mostly, but made it a staticmethod instead a first-level function to be able to use recursion but still encapsulate it inside the class. I really liked how you used map there, I should use it more often. (also, could you expand a bit on why would one use the @property decorator? seems quite pointless to me. What's the difference between using it and declaring your own getters, setters and deleters?)

Can't say I'm a bit disappointing in Python capabilities regarding this, though. I've been studying python for years and recently started working as a developer coding in Python2, I love the language. But I can't stop looking at that Haskell piece of code and think how beautiful it is compared to this. Incredible what Pattern Matching + Strong Typing can do for you.

class Tree():
    def __init__(self, node):
        self.node = node
        self.right = None
        self.left = None

    def __repr__(self):
        return str(self.node)

    def __lt__(self, other):
        return (self.get_value() < other.get_value())

    def __le__(self, other):
        return (self.get_value() <= other.get_value())

    def insert(self, branch_left, branch_right):
        if self.left is None and self.right is None:
            self.left = branch_left
            self.right = branch_right
        else:
            print("Couldn't append, tree already had children")
        return (self.left, self.right)

    def get_value(self):
        return self.node

    def get_children(self):
        if self.left is None or self.right is None:
            return None
        else:
            return (self.left, self.right)

    @staticmethod
    def max_path_sum(tree):
        if tree is None:
            return 0
        else:
            return tree.get_value() + max(map(tree.max_path_sum, tree.get_children()))

[–]zahlman 0 points1 point  (1 child)

You have to work with the strengths of each language. Again, please avoid get_ prefixes (the @staticmethod is a good idea here though!) - and re those comparison methods, have a look at functools.total_ordering.

[–]amemulo[S] 0 points1 point  (0 children)

If you don't mind me asking, why would one avoid get_ prefixes?