What is wrong with my code checking for arithmetic sequence eligibility?
Question:
When inputting a list of numbers, they would always result in True
def arithmetic(lst):
for i in range(0,len(lst)-1):
if (lst[i+1] - lst[i]) != (lst[i+2] - lst[i+1]):
return False
return True
Answers:
Since your return True
statement is inside the for loop it’s gonna return true on the first iteration of the loop (even if the if
condition is false).
You should remove indentation from that line, so that the return True
is in the function, but NOT in the for loop.
Like this:
def arithmetic(lst):
for i in range(0,len(lst)-1):
if (lst[i+1] - lst[i]) != (lst[i+2] - lst[i+1]):
return False
return True
But as mentioned by others in the comments this code will fail, cause you are trying to access elements outside the list. Hint i+2
is the issue.
Homework would be:
- fix iteration issue by proper indexing
- think of better argument name and don’t use abbreviations
- [OPTIONAL] by convention functions returning bool start with
is_
, are_
and so on, it improves readability imho
When inputting a list of numbers, they would always result in True
def arithmetic(lst):
for i in range(0,len(lst)-1):
if (lst[i+1] - lst[i]) != (lst[i+2] - lst[i+1]):
return False
return True
Since your return True
statement is inside the for loop it’s gonna return true on the first iteration of the loop (even if the if
condition is false).
You should remove indentation from that line, so that the return True
is in the function, but NOT in the for loop.
Like this:
def arithmetic(lst):
for i in range(0,len(lst)-1):
if (lst[i+1] - lst[i]) != (lst[i+2] - lst[i+1]):
return False
return True
But as mentioned by others in the comments this code will fail, cause you are trying to access elements outside the list. Hint i+2
is the issue.
Homework would be:
- fix iteration issue by proper indexing
- think of better argument name and don’t use abbreviations
- [OPTIONAL] by convention functions returning bool start with
is_
,are_
and so on, it improves readability imho