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
Asked By: Superheroo2

||

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
Answered By: Gameplay
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.