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[0]))
list_of_nums = lis
j = j+1
return orig_list, j
Sequence of Differences in Python
Upasana | September 15, 2019 | 2 min read | 26 views | Python Coding Problems
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|.
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 |
print(seq_diff([9934, 8543, 812, 1001]))
([9934, 8543, 812, 1001], 3)
Top articles in this category:
- Write a program for Hailstone Sequence in Python
- Python coding challenges for interviews
- Top 100 interview questions on Data Science & Machine Learning
- Flask Interview Questions
- Find extra long factorials in python
- Google Data Scientist interview questions with answers
- Difference between Loss, Accuracy, Validation loss, Validation accuracy in Keras