# Sequence of Differences in Python

Upasana | September 15, 2019 | 2 min read | 26 views |

Given a set of four numbers representing a “circular array” we can test to see if the absolute values of the differences between each adjoining element will eventually coalesce into a single value.

For example, consider the set of four numbers: `{1, 10, 8, 3}`.

We can repeatedly take the absolute values of the differences of the adjoining numbers. Since this is a circular array, calculate the value of the last element in the new array as the last number minus the first number.

For example, starting with `{1, 10, 8, 3}`

• The first iteration will produce {9, 2, 5, 2} calculated as |1 - 10|, |10 - 8|, |8 - 3|, |3 - 1|.

• The second iteration will produce {7, 3, 3, 7} calculated as |9 - 2|, |2 - 5|, |5 - 2|, |2 - 9|.

• The third iteration will produce {4, 0, 4, 0} calculated as |7 - 3|, |3 – 3|, |3 - 7|, |7 – 7|.

• The fourth iteration will produce {4, 4, 4, 4} calculated as |4 - 0|, |0 - 4|, |4 - 0|, |0 - 4|.

Test Data
Input Output

1 0 0 0

3 iterations were required for 1 0 0 0

0 1 4 11

5 iterations were required for 0 1 4 11

0 0 0 2

3 iterations were required for 0 0 0 2

34 12 19 28

4 iterations were required for 34 12 19 28

100 200 321 345

4 iterations were required for 100 200 321 345

``````def seq_diff(list_of_nums):
orig_list = list_of_nums
j = 0
while len(set(list_of_nums)) != 1:
lis = []
for i in range(len(list_of_nums)):
try:
lis.append(abs(list_of_nums[i]-list_of_nums[i+1]))
except:
lis.append(abs(list_of_nums[i]-list_of_nums))
list_of_nums = lis
j = j+1
return orig_list, j``````
Input
``print(seq_diff([9934, 8543, 812, 1001]))``
Output
`([9934, 8543, 812, 1001], 3)`

##### Top articles in this category:

###### Recommended books for interview preparation:
Book you may be interested in..
Book you may be interested in..