Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if the sequence is incremented? (python) [duplicate]

Tags:

python

def isIncreasing(seq):
    flag = True
    for i in range(len(seq) - 1):
        if seq[i + 1] < seq [i]:
            flag = False
    return flag


a = [1, 2, 3, 4, 5]  # print True
b = [2, 3, 1, 5, 4]  # print False

I have two sequence. Is there any better way to modify my function if the sequence is incrementing?

like image 475
vincentlai Avatar asked Jul 07 '26 14:07

vincentlai


2 Answers

Returning as soon as you find one is better. You can leverage pythons built in functions to do that:

def isIncreasing(seq):
   return all(a<b for a,b in zip(seq,seq[1:]))

This zippes your sequence into pairs:

[1,2,3,4] => [(1,2),(2,3),(3,4)]

and checks each pair. all() terminates as soon as it finds a False.

Documentation:

  • all()
  • zip()
like image 141
Patrick Artner Avatar answered Jul 09 '26 20:07

Patrick Artner


Using numpy.diff() and all()

In [33]: all(i>=1 for i in np.diff(b))
Out[33]: False

In [34]: all(i>=1 for i in np.diff(a))
Out[34]: True
like image 39
Fredrik Pihl Avatar answered Jul 09 '26 22:07

Fredrik Pihl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!