First of all:
for i in range(len(listaEv) ):
if listaEv[i] > listaEv[i - 1]:
return print("La lista crece")
else:
return print("La lista decrece")
The verification you do within the for
is only verified once, because whatever the result, you exit the function with a return
and on the other hand, in python, when you do listaEv[i - 1]
e i = 0
you end up with listaEv[-1]
that is totally valid, it just represents the last element and I do not think that's what you're looking for.
I think the idea is: verify the existence of a growth pattern in the list and then a decrement pattern or vice versa, no matter the length of each pattern, but only two unique patterns should exist , if it first grows, then it decreases and it grows back we have three different patterns and that invalidates the requirement, or even if we only have one pattern we would be in the same situation.
In practice we will have three patterns in any list, either grow (+1) or decrease (-1) or stay the same (0), what interests us is that there are only two patterns (+1) and (- one).
To detect the patterns, we can do something like this:
def patrones(lista):
return [1 if lista[i] > lista[i-1] else -1 if lista[i] < lista[i-1] else 0 for i in range(1,len(lista))]
print(patrones([2, 4, 5, 7, 4, 3]))
print(patrones([1, 2, 5, 7, 4, 3, 6]))
print(patrones([7, 5, 3]))
print(patrones([1, 2]))
[1, 1, 1, -1, -1]
[1, 1, 1, -1, -1, 1]
[-1, -1]
[1]
the function patrones
returns the mentioned patterns, it simply uses an understanding of lists to go comparing each element of the list with the previous one, the peculiarity is that we must begin to compare from the second element that is why we do range(1,len(lista))
the verification is not complex, simply 1 if lista[i] > lista[i-1] else -1 if lista[i] < lista[i-1] else 0
, that is, we will obtain a +1 if the list grows, a -1 if it decreases and a 0 if it is maintained with the same value.
The output gives us an idea of which of the lists is actually a triangular list, only the first case is, as we said, we only have two patterns and these are +1 and -1. The second case we have the patterns +1 and -1, but we have three patterns, which is not a triangular list either.
Having the built pattern, it is easy to verify the requirements:
from itertools import groupby
def patrones(lista):
return [1 if lista[i] > lista[i-1] else -1 if lista[i] < lista[i-1] else 0 for i in range(1,len(lista))]
def listaTriangular(lista):
p = [e[0] for e in list(groupby(patrones(lista)))]
return len(p) == 2 and (p == [-1,1] or p == [1,-1])
print(listaTriangular([1]))
print(listaTriangular([1,2,3]))
print(listaTriangular([1,1,1]))
print(listaTriangular([2, 4, 5, 7, 4, 3]))
print(listaTriangular([2, 4, 5, 7, 5, 8, 4, 3, 1]))
False
False
False
True
False
We use groupby()
of the module itertools
to obtain the groups, the only possibility that does not work is that they are 2 and are [-1,1]
or [1,-1]