Why Does My Recursive Method from Helper Not Return Every Value

Why does my recursive method from helper not return every value?

The mothod you are using will return just one value (the fist call to category.name actually)
About the console, you are getting the puts that you have inside the loop (that is not the return value of the method).

Try this and let me know if there's still something not clear enough:

module CategoriesHelper

def display_tree(category)
tree = category.name
if category.has_children?
category.children.each do |sub_category|
tree += "/#{display_tree(sub_category)}"
end
end
tree
end

end

Python recursive helper method returns none instead of int

The problem is that your helper function does not always return a value. Only in the base case, where the if condition is true, it will return a numeric value. But it should also return that same number where the corresponding recursive calls are made.

So change:

self.helper(arr,left,p-1,k)
self.helper(arr,p+1,right,k)

to:

result = self.helper(arr,left,p-1,k)
if result is not None:
return result
return self.helper(arr,p+1,right,k)

This way the deepest return value will bubble up the recursion tree, and a success in the first recursive call will avoid that the second recursive call is made.

Python recursive function doesn't return

You need to actually return your RecursiveProcess. Look below at your modified code.

You aren't exactly doing anything recursively if all you do is call the function and store the value in ListIn2. You will keep overwriting your previous data. By returning, you will end up getting your recursive behaviour:

def RecursiveProcess(ListIn2, target): #Recursive function that adds to target value the value to its right
if target > -1: #stop function if index is below 0
ListIn2[target] = ListIn2[target] + ListIn2[target+1] #Add value to the right of target to the target value
return RecursiveProcess(ListIn2, target-1) #Call the function again with lower taget value to process the next value
else:
return ListIn2 #return the changed list

l = [5, 10, 11, 6, 7, 1, 2, 4, 6, 7]
d = RecursiveProcess(l, len(l)-2)
print(d) # [59, 54, 44, 33, 27, 20, 19, 17, 13, 7]

Recursive Function not returning value as expected

You have to return value in each call of the recursive function like:

return helper(msg, head, count);

function numWaysDecodable(msg) {    msg = msg.toString().split("");
function helper(msg, past = 99, count = 1) { if (msg.length === 0) { console.log("wtf count is:"+count); return count; } let head = msg.shift(); if (head < 7 && past < 3) { count++ } return helper(msg, head, count); } return helper(msg);}
console.log(numWaysDecodable(123));

How exactly does return statement work in recursive function?

Although you return something different in the two versions of the code, neither helper functions actually use the value returned from a recursive call:

getList2Helper(root.left, list);

The above makes the recursive call, which returns something, but the caller does not do anything with it.

The only time there is a difference in the returned value, is when the base case kicks in. That means that there is a difference for the initial caller when they pass null as first argument (denoting an empty tree). The first version will return an empty array list, while the second will return null. So they are not completely equivalent. The one that returns the array list would be more what I would expect to get back for an empty tree (i.e. an empty array list, not null).

Cleaning up

As the helper function actually populates the array list that is given as argument, it should not need to return anything. The main function could create the array list, pass it to the helper (which returns nothing) and then return that populated list.

Like this:

public List<Integer> getList(TreeNode root) {
List<Integer> list = new ArrayList<>();
getListHelper(root, list);
return list;
}

private void getListHelper(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
list.add(root.val);
getListHelper(root.left, list);
getListHelper(root.right, list);
}

Alternative

You could avoid to have the helper function (with its second parameter) at all, and instead populate a local array list from the lists that the recursive calls return:

public List<Integer> getList(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root != null) {
list.add(root.val);
list.addAll(getList(root.left));
list.addAll(getList(root.right));
}
return list;
}

This is less efficient, as values get copied from one list to another several times. With a linked list implementation that would allow to concatenate lists in O(1) time, you could overcome that downside.

Recursive helper method

As AllenKll already pointed out, the high value should probably take the role that you intended for your index. You have been counting the number of occurances in the high variable, but this counting can be "hidden" in the recursion.

The purpose of these "helper" methods for recursion in general is exactly that: They usually have (at least) one additional parameter that somehow describes how far the recursion has already proceeded or how far it still has to proceed. As an example for the latter: You could also have used the high variable as a "countdown", by writing

public static int count(char[] chars, char ch)
{
return count(chars, ch, chars.length - 1);
}

public static int count(char[] chars, char ch, int high)
{
if (high == -1)
{
return 0;
}
if (chars[high] == ch)
{
return 1 + count(chars, ch, high - 1);
}
return count(chars, ch, high - 1);
}

Of course, one could only offer the helper method. Instead of calling

count(chars, ch);

you could ask the user to call

count(chars, ch, 0);

But the problem here is that this method may be misused: When then user passes a wrong value as the last parameter, then the method will not work.

Note: This whole "helper method" thing only makes sense when the helper method is private. When it is public, the user may still call the wrong method. I see that the public modifier was requested in the task description, but... maybe you'll receive some bonus points when you make your instructor aware of this flaw ;-)

Python recursive function with helper function

There are the following issues:

  • _size is an instance attribute that is set in the __init__ function. That means that self._size will refer to that attribute, and not to the class method with the same name. This is the cause of the error you get. You should use a different name for these two things: one name for the integer size, and another for the helper function that will calculate the size recursively. I suggest to use _sizerecur as name for the helper method -- and will refer to it that way in the next point:

  • self._sizerecur(self, 0, self._root) should not pass self as argument, as that parameter is already getting the value of self by this type of method-call syntax (the prefix in the dot notation serves as that argument).

  • if current_node != None should have all the rest of that code in its block, otherwise current_node.left will still be evaluated when current_node is None, leading to an error.

  • The size is not calculated correctly. There are essentially two ways to implement this recursion, and your code seems to mix both of these, making it incorrect: When you pass the current size as argument to the recursive call, and that call returns the updated value, you should not add that to the original size you already passed to it. By doing that, you have double counting. You should either just assign it back to your variable (not adding to it), or (better), not pass the current count as argument, but let each recursive call start counting from 0.

Here is a correction keeping the existing current_size parameter:

    def size(self) -> int:
if self._root is None:
return 0
else:
return self._sizerecur(0, self._root) # don't pass self as arg

# A distinct name for this method
def _sizerecur(self, current_size, current_node):
if current_node:
current_size += 1
if current_node.left:
# don't ADD again to current size
current_size = self._sizerecur(current_size, current_node.left)
if current_node.right:
current_size = self._sizerecur(current_size, current_node.right)

return current_size

But as said, it is better practice to implement this recursive function without current_size parameter. Instead of updating the counter while you recur deeper, update it while getting out of recursion:

    def size(self) -> int:
if self._root is None:
return 0
else:
return self._sizerecur(self._root)

def _sizerecur(self, current_node):
current_size = 0
if current_node:
current_size = 1
if current_node.left:
current_size += self._sizerecur(current_node.left)
if current_node.right:
current_size += self._sizerecur(current_node.right)
return current_size

PHP Recursion Function not working as expected

The problem is misunderstanding the logic. In your code the recursion call result is not used ever.

function day_check($paymentDate, $paymentDay = 1) {
$CI =& get_instance();
$dateParts = explode("-", $paymentDate);
$holQ = $CI->db->query("SELECT * FROM holidays WHERE holidayDate = '$paymentDate'");
$holR = $holQ->row();

if ($paymentDay <= 0) {
$paymentDay = 1;
}

// while -> if
if (($holR->holidayDate == $paymentDate) || (date("l", strtotime($paymentDate)) == 'Saturday') || (date("l", strtotime($paymentDate)) == 'Sunday')) {
echo "$paymentDate: $paymentDay <br>";
$refinedDay = $dateParts[2] + 1;
if ($refinedDay < 10) {
$refinedDay = "0" . $refinedDay;
}
$paymentDate = $dateParts[0] . "-" . $dateParts[1] . "-" . ($refinedDay);
$paymentDay = $dateParts[2] + 1;
return day_check($paymentDate, $paymentDay); // return!
// break; // no need
}

echo "Final: $paymentDate: $paymentDay <br>";
return $paymentDay;

}

Also change while to if since we don't need a loop there.



Related Topics



Leave a reply



Submit