0

Here is problem: when I write any number to find, it says, that it was found, but index is None. What can I do?

tree = [1, 3, 5, 8, 12, 14, 17, 21, 25, 28, 29, 31, 35, 40, 45, 48, 50]

input = int(input())

def binnary_tree_search(list, wanted_number, start, stop):
    if start > stop: return False
    middle = (start + stop) // 2
    if wanted_number < list[middle]:
        binnary_tree_search(list, wanted_number, start, middle - 1)
    elif wanted_number > list[middle]:
        binnary_tree_search(list, wanted_number, middle + 1, stop)
    else:
        return middle
        
result = binnary_tree_search(tree, input, 0, len(tree))

if result == False:
    print("The number was not found")
else:
    print(str(input) + " was found with index " + str(result))
Péter Leéh
  • 2,069
  • 2
  • 10
  • 23
Anisimov
  • 25
  • 1
  • 8
  • You may want to avoid using built-in names such as `input` and `list` as variable names. – Gustave Coste Aug 25 '20 at 06:37
  • 1
    Does this answer your question? [Why does my recursive function return None?](https://stackoverflow.com/questions/17778372/why-does-my-recursive-function-return-none) – DarrylG Aug 25 '20 at 06:38

1 Answers1

0

You forgot to return the value of the recursive call:

def binnary_tree_search(list, wanted_number, start, stop):
    if start > stop: return False
    middle = (start + stop) // 2
    if wanted_number < list[middle]:
        return binnary_tree_search(list, wanted_number, start, middle - 1)
    elif wanted_number > list[middle]:
        return binnary_tree_search(list, wanted_number, middle + 1, stop)
    else:
        return middle
kutschkem
  • 7,826
  • 3
  • 21
  • 56