Code to check if a list of numbers is in arithmetic progression or not

3.6k views Asked by At

Following is the code to check if a list of items is in arithmetic progression or not.

def ap():
    l=[int(x) for x in list(input("Enter the list: "))]
    diff=l[1]-l[0]
    for i in range(len(l)-1):
        if not ( l[i+1]-l[i]==diff):
           return False
    return True

When I am executing the above code, it is working fine, but If I am modifying the code and don't use the "not" keyword it is returning true in all the cases. Following is the code:

def ap():
    l=[int(x) for x in list(input("Enter the list: "))]
    diff=l[1]-l[0]
    for i in range(len(l)-1):
        if (l[i+1]-l[i]==diff):
            return True
    return False

Can someone please help me to figure out where am I going wrong?

1

There are 1 answers

3
Geoduck On

Of course it does. You get the difference between the first two elements, and then in your loop, the first step will check if the difference between the first two elements is the same, which it will always be. So, it will always return true in the first iteration of the loop.