Causes of Line Segment Search Errors

Asked 2 years ago, Updated 2 years ago, 107 views

def LinearSearch(N,a):
n = len(N)
for i in range(n):
    if N[i] == a:
        return True

    else:
        return False

N = [13, 16, 23, 45, 54, 58, 76, 91]
a = 76

an=LinearSearch(N,a)
print(ans)

The result is false for some reason,
I wonder if the combination of the for and if statements is not good.
Thank you for your cooperation.

python xcode visual-studio

2022-09-30 19:18

4 Answers

I guess Wakewakameman was going to write as follows.

def LinearSearch(N,a):
  n = len(N)
  for i in range(n):
    if N[i] == a:
        return True
  else:
    return False

# This is not a mistake, but


2022-09-30 19:18

Perhaps you are using python for algorithm learning, but I will give you a python-like writing method.

N=[13,16,23,45,54,58,76,91]#N is usually a natural number, so this naming is not recommended.
a = 76

as
ain N

If you write, you get the result you want.
The flow of code presented by the questioner is
Since N[0]=13 is not 76, N[0]==76 is False, and the sentence after the else clause is executed.
Return False also escapes from the for loop to exit the function LinearSearch and becomes False.


2022-09-30 19:18

Is the combination of for and if statements not good?

I think so.When comparing the first 13 in the for statement, False is returned and the for statement is omitted.Only one element has been compared.

For example, if you only return True if the for statement is true, and if you exit the for statement, you should return False.

In any case, once Python can be debugged in your development environment, you will be able to understand the symptoms and fix bugs yourself.

def LinearSearch(N,a):
    n = len(N)
    for i in range(n):
        if N[i] == a:
            return True
    return False


N = [13, 16, 23, 45, 54, 58, 76, 91]
a = 76

an=LinearSearch(N,a)
print(ans)


2022-09-30 19:18

In a loop in the LinearSearch function, you first compare the first element N[0] with a, where N[0] and a are not equal, you immediately return false.This is the cause of the bug.

This is not the case, and it should be return false if it is not equal to any of the elements.

I have written the sample code below, so please use it as needed (it appears when you hover your mouse over it).

def LinearSearch(N,a):
    n=len(N)
    for i in range(n):
        if N[i] == a:
            return True
    return False


2022-09-30 19:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.