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.
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
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
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.
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)
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
884 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
577 PHP ssh2_scp_send fails to send files as intended
572 Understanding How to Configure Google API Key
606 Uncaught (inpromise) Error on Electron: An object could not be cloned
567 Who developed the "avformat-59.dll" that comes with FFmpeg?
© 2024 OneMinuteCode. All rights reserved.