[Solved] Contracting in python


Let me try to understand the question:

im given a list that looks like this l1 = [1, 3, 9, 1, 2, 7, 8] and im
supposed to contract the list by taking the first number then the next
bigest and the smallest after that and then the biggest again. This is
a school assignment and i have no idea on how to do this. english
isn’t my first language and it’s realy difficult to explain the
assignment :/

I supposed that “biggest” and “smallest” refer to local maxima and minima. So a number at index i is “biggest” if l[i-1] < l[i] and l[i] > l[i+1]. “Smallest” the other way around. So basically your are searching for the extrema of a function N -> N.

If this is what you want, this should help (considering that start and end points always are extrema):

#! /usr/bin/python3.2

def sign(x): return 0 if not x else x // abs(x)

def extrema (l):
    return [l[0]] + [e for i, e in enumerate(l[:-1]) if i and sign(e-l[i-1])==sign(e-l[i+1])] + [l[-1]]

l1 = [1, 3, 9, 1, 2, 7, 8]
print (extrema (l1))

1

solved Contracting in python