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?
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With