Home > Software engineering >  Increase minumum value distance between Integers in Array
Increase minumum value distance between Integers in Array

Time:04-02

I would like the increase the minimum 'distance' between values in an array. For example, if I have the array

44,45,47,51,65,66

I would like the minimum 'distance' to be 2. So, the desired output would be

44,46,48,51,65,67

I've tried doing something like

prevValue = array[0]
array.pop(0)

for a in array:
  if(prevValue   1 >= a):
    a  = 1

this wasn't the entire code as I had create temp arrays to not mess up the original one. But, this logic does not work.

Has anybody done anything similar? I was looking at np.arrange() but that wasn't the desired use case.

Thank you!

CodePudding user response:

The line a = 1 only modifies your local variable named a; it would not modify any elements in a list. Here is one way to do what you want:

list1 = [44, 45, 47, 51, 65, 66]

list2 = []
prev = None
for a in list1:
  if prev and prev   1 >= a:
    a = prev   2
  list2.append(a)
  prev = a

print(list2)

They are actually called "lists", not "arrays", in Python. Using the correct search terms might help you find answers better on your own.

CodePudding user response:

Try (assuming the lst is sorted):

lst = [44, 45, 47, 51, 65, 66]

distance = 2

for i in range(1, len(lst)):
    diff = lst[i] - lst[i - 1]
    if diff < distance:
        lst[i]  = distance - diff

print(lst)

Prints:

[44, 46, 48, 51, 65, 67]

For distance = 5:

[44, 49, 54, 59, 65, 70]
  • Related