
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if Sequence Can Form Arithmetic Progression in Python
Suppose we have a list of numbers called nums. We have to check whether the elements present in nums are forming AP series or not. As we know in AP (Arithmetic Progression) series the common difference between any two consecutive elements is the same.
So, if the input is like nums = [9,1,17,5,13], then the output will be True because if we sort them, it will be [1,5,9,13,17] and here common difference is 4 for each pair of elements.
To solve this, we will follow these steps −
nums := sort the list nums
-
if number of elements in nums > 1, then
const := nums[1] - nums[0]
-
otherwise,
return True
-
for i in range 0 to size of nums -1, do
-
if nums[i+1] - nums[i] is not same as const, then
return False
-
return True
Example (Python)
Let us see the following implementation to get better understanding −
def solve(nums): nums = sorted(nums) if len(nums) > 1: const = nums[1] - nums[0] else: return True for i in range(len(nums)-1): if nums[i+1] - nums[i] != const: return False return True nums = [9,1,17,5,13] print(solve(nums))
Input
[9,1,17,5,13]
Output
True