Home > Enterprise >  Count number of times the numbers are increasing in Python list
Count number of times the numbers are increasing in Python list

Time:12-01

I have this list of numbers: {199, 200, 208, 210, 200, 207, 240}.

  1. I want to determine how the numbers are increasing or decreasing in the list. For instance, after 199 I have 200, that is a difference of 1. But after 200, I have 208 which is a difference of 8. How do I determine this measure of increase/decrease for the entire list in Python?

  2. Secondly, I want to count how many times the numbers are increasing. As the list consist of increasing and decreasing numbers both, I just want to count how many times it is increasing.

Thank you.

CodePudding user response:

You can use zip() to pair up elements with their successors and process them in list comprehensions:

numbers = [199, 200, 208, 210, 200, 207, 240]

increments = [b-a for a,b in zip(numbers,numbers[1:]) if b>a]
decrements = [b-a for a,b in zip(numbers,numbers[1:]) if a>b]

print(increments)      # [1, 8, 2, 7, 33]
print(decrements)      # [-10]
print(len(increments)) # 5

CodePudding user response:

diff = [l[i 1] - l[i] for i in range(len(l) - 1)]
num_inc = sum([l[i 1] > l[i] for i in range(len(l) - 1)])
  • Related