-1

I was working in a small problem in python. This is the problem -

Given an array of ints, compute recursively if the array contains a 6. We'll use the convention of considering only the part of the array that begins at the given index. In this way, a recursive call can pass index+1 to move down the array. The initial call will pass in index as 0.

array6([1, 6, 4], 0) → true
array6([1, 4], 0) → false
array6([6], 0) → true

This is the solution which i came up with.

def array6(intList, index):
    if len(intList) < index + 1:
        print(False)
    else:
        if intList[index] == 6:
            print(True)
        else:
            array6(intList, index + 1)

The script seems to work correctly, except when i change print to return statements and call it as : print(array6([1, 6, 4], 0)) it displays "None" in the console. Why is this? It should ideally display True or False - Right? Or am i missing something in the script?

Ashwin
  • 164
  • 6

3 Answers3

1

When the execution moves to the most inner else statement, no return statement is found, so None is assumed.

In order to solve that, do:

return array6(intList, index + 1)
ForceBru
  • 43,482
  • 10
  • 63
  • 98
1

It seems like you forgot to return the function array6(intList, index+1). It's crucial in recursive functions that all blocks of your if-else-if chain are returning something. You get a None whenever the function is not returning anything.

This is what the whole code will look like - (look at the comment to know where you went wrong)

def array6(intList, index):
    if len(intList) < index + 1:
        return False
    else:
        if intList[index] == 6:
            return True
        else:
            # you forgot the return here
            return array6(intList, index + 1)
martianwars
  • 6,380
  • 5
  • 35
  • 44
1

All Python functions return something. If you do not explicitly return then the return value is None. You are not returning anything, but you were close:

def array6(intList, index):
    if len(intList) < index + 1:
        return False
    else:
        if intList[index] == 6:
            return True
        else:
            return array6(intList, index + 1)

Also, you can remove a level of indentation like this

def array6(intList, index):
    if len(intList) < index + 1:
        return False
    if intList[index] == 6:
        return True
    return array6(intList, index + 1)

Any time an if has a return inside it, you can remove the follow else and de-dent as the function will have already returned.

sberry
  • 128,281
  • 18
  • 138
  • 165