Why Does My Recursive Binary Search Code Return None Instead of True?

Linda Hamilton
Release: 2024-10-26 03:18:27
Original
602 people have browsed it

Why Does My Recursive Binary Search Code Return None Instead of True?

Recursive Code Failing to Return True Value

The given code aims to determine if a character exists within a string using a binary search approach. However, it fails to return the expected True value and keeps returning None.

Analysis:

The code employs a recursive function isIn that takes a character and a string as input. It performs a binary search by dividing the string into two halves at the midpoint. If the character matches the midpoint, it prints a message indicating the character's presence and returns True.

If the character is greater than the midpoint character and the midpoint is not the last character in the string (i.e., there are still characters to search), the function updates the string by removing the first half. If the character is less than the midpoint character and the midpoint is not the first character in the string (i.e., there are still characters to search), the function updates the string by removing the second half.

However, the code lacks a return statement on the last line within the else block. Without this return statement, the function simply terminates without explicitly returning a value. This results in Python implicitly returning None, which is why the function keeps on returning None.

Solution:

To fix the issue, you need to add a return statement on the last line within the else block:

<code class="python">return isIn(char, aStr)</code>
Copy after login

With this modification, the function will return the result of the recursive call, which will eventually return True if the character is found within the string.

The above is the detailed content of Why Does My Recursive Binary Search Code Return None Instead of True?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template