1 | initial version |
Call C the list of coefficients, removing immediate repeats.
Unimodality means there is no decrease-then-increase in C.
The package more-itertools (which can be installed with pip) enables an elegant solution:
def is_unimodal(p):
"""
Return whether this polynomial is unimodal.
EXAMPLES::
sage: R.<t> = ZZ[]
sage: is_unimodal(1 + t + t^2 + 4*t^3 + t^4)
True
sage: is_unimodal(1 + t^2 + 4*t^3 + t^4)
False
"""
from more_itertools import triplewise, unique_justseen
return all((a < b) or (b > c)
for a, b, c in triplewise(unique_justseen(p)))
2 | No.2 Revision |
Call C the list of coefficients, removing immediate repeats.
Unimodality means there is no decrease-then-increase in C.
The package more-itertools (which can be installed with pip) enables an elegant solution:
def is_unimodal(p):
"""
Return whether this polynomial is unimodal.
EXAMPLES::
sage: R.<t> = ZZ[]
sage: is_unimodal(1 + t + t^2 + 4*t^3 + t^4)
t^4) # coeffs: 1, 1, 1, 4, 1
True
sage: is_unimodal(1 + t^2 + 4*t^3 + t^4)
t^4) # coeffs: 1, 0, 1, 4, 1
False
"""
from more_itertools import triplewise, unique_justseen
return all((a < b) or (b > c)
for a, b, c in triplewise(unique_justseen(p)))