2

I am trying to simplify this function at his maximum, how can I do?

def eleMax(items, start=0, end=None):
    if end is None:
        end = len(items)
    return max(items[start:end])

I thought of

def eleMax(items, start=0, end=-1):
    return max(items[start:end])

But the last element is deleted from the list.

4
  • That's a really, really weird approach to max(items). And if you need to slice max(items[start:end]) or even max(items[start:]) works.
    – g.d.d.c
    Oct 8, 2010 at 17:45
  • Yes you are right, but it is just to exercice :)
    – Natim
    Oct 8, 2010 at 18:04
  • If it's homework, please mark the question with [Homework]
    – S.Lott
    Oct 8, 2010 at 22:49
  • 1
    It is not Homework it is entertainment :)
    – Natim
    Oct 11, 2010 at 8:21

4 Answers 4

4

You can just remove these two lines:

if end is None:
    end = len(items)

The function will work exactly the same:

>>> a=[5,4,3,2,1]
>>> def eleMax(items, start=0, end=None):
...     return max(items[start:end])
...
>>> eleMax(a,2)   # a[2:] == [3,2,1]
3
1
  • if i have to calculate that how many times this maximum value occur in given list slice?then how to do this in optimized way if we have longest range of slice Aug 15, 2015 at 15:52
2

Just use max(items).

Python ranges are 'half-open'. When you slice a list in Python with [start:end] syntax, the start is included and the end is omitted.

2
def eleMax(items, start=None, end=None):
    return max(items[slice(start, end)])
0
1

When operating over large lists or many calls to this you can avoid the overhead of the slice creating a new list and copying the pointers.

http://docs.python.org/library/itertools.html#itertools.islice

Itertools contains islice which allows for iterating over the list in place without actually returning a new list for the slice.

from itertools import islice

def eleMax(items, start=None, end=None):
    return max(itertools.islice(items, start, end))

One current limitation is that negative values are not allowed for start, end, step.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.