This code snippet shows 2 common patterns I see a lot in Python that I don't really like:
- Arbitrarily-named, narrowly-scoped recursive function
- Inappropriate data type (in this case, an array
ansto store 1 float) used purely for its mutability and scope, to store side-effects from some other scope
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def maximumAverageSubtree(self, root: TreeNode) -> float: ans =  def helper(node): if not node: return 0, 0 left_sum, left_count = helper(node.left) right_sum, right_count = helper(node.right) ans = max(ans, (left_sum + right_sum + node.val) / (left_count + right_count + 1)) return left_sum + right_sum + node.val, left_count + right_count + 1 helper(root) return ans
ans has to be an array, even though we just want to store one scalar value, because if we tried to use a float it would not be visible inside
helper. This seems like an ugly shortcut to me.
And the other pattern I don't like is defining
helper just so we can do recursion with additional return values for logic, then return
helper's side effects. Is it normal to define short, sort of "throwaway" functions like this?