Issue
im just getting into python for my discrete structures and algorithms class > and for some reason, im getting an error with my syntax and I don't understand why can you assist this is the error:
line 10
i = i + 1
IndentationError: unindent does not match any outer indentation level also for some reason my code isn't printing
#linear search algorithm
def search(list1, n):
i = 0
while i < len(list1):
if list1[i] == n:
print("found now")
return True
i = i + 1
return False
list1 = [1,5,9,3,4,6]
n = 6
if search(list1, n):
print("found")
else:
print("not found")
Solution
As others have mentioned in your comments, your indentation is wonky. Pythonic code prefers 4 spaces for every indented/unindented line.
To linear search for an element in a list data structure, you can use the in
keyword. Here is your code functionally, but with less lines:
list1 = [1,5,9,3,4,6]
n = 6
if n in list1:
print("found") # Indent 4 spaces
else: # Unindent 4 spaces
print("not found") # Indent 4 spaces
Now for your code:
def search(list1, n): # Careful! You have an extra space here.
i = 0 # Indent 3 spaces
while i < len(list1):
if list1[i] == n: # Indent 5 spaces
print("found now") # Indent 3 spaces
return True
i = i + 1 # Unindent 4 spaces
return False # Unindent 4 spaces
So remove the extra space at the start, and fix it to 4 spaces each time.
Note: The in
keyword can be used on other iterables (tuples, dictionaries, sets, etc...) as well, or objects with __contains__ in the class.
Since this is a class, they probably just want you to familiarize yourself with linear search by using an index variable (e.g. for i in ....) as you've done, but the python already does this for you in the background with the in
keyword.
Answered By - jsonV
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.