Since adapting some code by adding new lines is hardly groundbreaking, let's come back with a new solution involving our triad of One Function, One Helper and One Global Variable. The question was how to look for values inside a BST that satisfies a group of parameters (ie range of numbers, multiple of 3). This can be done rather easily with the triad. Take a look at the code below:
_gather_values = [] def in_between(node, start, end): _gather_values.clear() _get_values(node, start, end) return _gather_values def _get_values(node, start, end): if node.data > start and node.data < end and node.data % 3 == 0: _gather_values.append(node.data) if len(node.children) != 0: for x in node.left: _get_values(x, start, end) for y in node.right: _get_values(y, start, end)Now, it does have a major flaw: it does not take advantage, nor tries to take advantage of, the properties of BSTs. The code at the end of the helper function could be changed to cover the properties of BSTs (left branch goes down, right branch goes up in value). Regardless, this could be improved quickly. The point was to show that this code, which solves the problem, could be constructed easily.
Looking back at that old post, I can see how many different ways you can solve a problem. Creatively, or not, it is always exciting. Whilst I aim for writing elegant code, this does not negate the power of quick, easy solutions. Let us keep coming with creative solutions, and improve upon our code writing.
I must say, you have quite the creativity in your titles! I've enjoyed reading your SLOG throughout the semester and found various tidbits to be fairly helpful, while at the same time entertaining. Good job! :)
ReplyDelete