tfalade
tfalade

Reputation: 111

Operation on consecutive numbers in a python list

I'm trying to write a function that accepts a list of integers as an argument. It will then find all runs of 3 consecutive numbers that increase or decrease by 1. It will return the list of indices of the first element of each run. If there are no consecutive runs it should return None.
Example: [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7, 8, 7] returns [0, 4, 6, 7]. Any help on how I can break this down will be appreciated.

My attempt gave me the wrong output:

lst = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7, 8, 7]


def cal_abs(a, b, c):

  return abs(a - b) == 1 and abs(b - c) == 1

def consecutive(lst):

   a = []

   for i in range(0,lst[-1]):

       if cal_abs(lst[i], lst[i+1], lst[i+2]):

           a.append(i)

          i += 1

   print(a)

Now when I ran consecutive(lst)

It returns [0, 4, 5, 6]. WRONG. Any ideas?

Upvotes: 0

Views: 669

Answers (4)

chelly
chelly

Reputation: 33

I suggest making a helper function called isARun(f, m, l)

def isARun(f,m,l):
    return (f == m-1 and f == l-2) or (f == m + 1 and f == l+2)

Then you want to do a for loop in your main function consecutive that looks like this.

for i in range(len(l) - 3):
    if (isARun(l[i], l[i+1], l[i+2])):
        a.append(i)
if len(a) == 0:
    return None
return a

Upvotes: 0

kernel
kernel

Reputation: 49

Try this simple solution:

my_list = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7, 8, 7]

consective_indices = []
for index, num in enumerate(my_list[:-2]):
    immediate_next = abs(my_list[index + 1])
    next = abs(my_list[index + 2])
    if (num + 1 == immediate_next and num + 2 == next) or 
              (num - 1 == immediate_next and num - 2 == next):

        consective_indices.append(index)

print consective_indices

hope this helps. Cheers !

Upvotes: 0

user8190410
user8190410

Reputation: 1314

You will need to check either a > b > c or a < b < c. you can see the code below

lst = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7, 8, 7]

def cal_abs(a, b, c):
    if a < b and b < c and (a-b) == -1 and (b-c) == -1:
        return True
    elif a > b and b > c and (a-b) == 1 and (b-c) == 1:
        return True
    else:
        return False

def consecutive(lst):
    a = []
    for i in range(0,len(lst)-3):
        if cal_abs(lst[i], lst[i+1], lst[i+2]):
            a.append(i)
            i += 1
    print(a)

consecutive(lst)

Upvotes: 1

NPE
NPE

Reputation: 500377

There are a couple of problems. I'll give you some hints that should be sufficient to figure out and fix them.

This:

return abs(a - b) == 1 and abs(b - c) == 1

accepts an increase followed by a decrease, and vice versa. This doesn't quite fit your problem statement, which appears to require either two increases or two decreases.

Also, the upper bound on the main loop, lst[-1], takes the value of the last element - why?

Upvotes: 1

Related Questions