0
$\begingroup$

The following is a function to write a recursive function that accepts an array and a callback. Function returns true if a single value in array returns true when passed to the callback otherwise it returns false.

I have trouble understanding the "if not" line written here(line 4), how does the cb interact with arr? Please help.

def isOdd(num):
    if num%2==0:
        return False
    else:
        return True
        
def someRecursive(arr, cb):
    if len arr == 0:
        return False
    if not(cb(arr[0])):     #Maybe till it is an empty array. DOUBT HERE
        return someRecursive(arr[1:],cb)
    return True
$\endgroup$
2
  • $\begingroup$ (While programming questions are off-topic here, the relevant part from the Python 3 reference reads not_test ::= comparison | "not" not_test […] The operator not yields True if its argument is false, False otherwise. The parentheses around cb(arr[0]) are dispensable. The statement in isOdd(num) might better read return num%2;, return num%2 != 0; or even return not (num%2 == 0);.) $\endgroup$ – greybeard Jan 4 at 5:40
  • $\begingroup$ cb is a function, so cb(arr[0]) is simply calling cb with arr[0] as an argument. What don't you understand? $\endgroup$ – xskxzr Feb 7 at 1:23
0
$\begingroup$

The if not branches says that the program continues to recurse if the first element of the array does not satisfy cb (cb(arr[0]) returns false).

The function checks the condition cb on one (the first) element at every call, and give the rest to the next recursion. Since the first element is removed at every iteration, arr[0] is different in each function call.

Once not(cb(arr[0])) gives false, the function returns True, and the return value propagates back to previous iterations.

$\endgroup$
1
  • $\begingroup$ Thank you for your immediate response, I think I understand this code better now. Have a good day my friend! $\endgroup$ – nazneen tamboli Jan 4 at 18:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.