Python program to check whether given array can form Arithmetic Progression

In this article, we will check whether given an array can form Arithmetic Progression in Python.

Example

Input: arr[] = {6, 4, 8, 2, 0}
Output: Yes
Explanation: Rearrange the given array {0, 2, 4, 6, 8} which is an arithmetic progression.

Input: arr[] = {6, 3, 2, 0}
Output: No

When the difference between two consecutive numbers is constant, then we can say that the array formed an arithmetic progression.

Check whether given array can form Arithmetic Progression in Python

We will implement this problem by sorting the array.

1. Sort the given array using the sort() function.

2. Now calculate the difference between 1st two-element and store its value as d.

3. Iterate the array from range n-1 to 1 and compare the difference between consecutive elements.

4. If the difference is not equal to d then return “No”.

5, Else, return “Yes”.

def isAP(arr):
    n = len(arr)
    arr.sort()
    d = arr[1]-arr[0]
    for i in range(n-1, 1, -1):
        if(arr[i]-arr[i-1] != d):
            return "No"
    return "Yes"

arr = [2, 4, 6, 8, 10]
print("The given array is:", str(arr))
print(isAP(arr))

arr1 = [2, 3, 5, 7]
print("The given array is:", str(arr1))
print(isAP(arr1))

Output

The given array is: [2, 4, 6, 8, 10]
Yes
The given array is: [2, 3, 5, 7]
No

Also, read

Leave a Reply

Your email address will not be published. Required fields are marked *