1

I can find max value, I can find average but I just can't seem to find the min. I know there is a way to find max and min in a loop but right now I can only find the max.

def large(s)
    sum=0
    n=0
    for number in s:
        if number>n:
            n=number 
    return n 

Is there a way to find the min value using this function?

1
  • how can a question which prompted 7 answers be downvoted? Commented Mar 31, 2017 at 19:32

8 Answers 8

3

You can use Python's built-in sum(), min(), and max() functions for this kind of analysis.

However, if you're wanting to do it all in one pass or just want to learn how to write it yourself, then the process is 1) iterate over the input and 2) keep track of the cumulative sum, the minimum value seen so far, and the maximum value seen so far:

def stats(iterable):
    '''Return a tuple of the minimum, average, and maximum values

        >>> stats([20, 50, 30, 40])
        (20, 35.0, 50)

    '''
    it = iter(iterable)
    first = next(it)     # Raises an exception if the input is empty
    minimum = maximum = cumsum = first
    n = 1
    for x in it:
        n += 1
        cumsum += x
        if x < minimum:
            minimum = x
        if x > maximum:
            maximum = x
    average = cumsum / float(n)
    return minimum, average, maximum

if __name__ == '__main__':
    import doctest
    print doctest.testmod()

The code has one other nuance. It uses the first value from the input iterable as the starting value for the minimum, maximum, and cumulative sum. This is preferred over creating a positive or negative infinity value as initial values for the maximum and minimum. FWIW, Python's own builtin functions are written this way.

Sign up to request clarification or add additional context in comments.

2 Comments

stats throws an exception if the list is empty. Although that doesn't seem to be a problem for Python programmers (that's the "pythonic" way), it still bothers me a bit. Personally, I prefer to handle special cases and return a meaningful result, since passing an empty list is not an exceptional condition per se. A matter of style.
@ÓscarLópez Python's own min and max raise a ValueError when fed an empty list ("errors should not pass silently"), but if it bothers you, it's not hard to add a default value with something like first = next(it, default_value).
2

Finding the minimum takes the same algorithm as finding the maximum, but with the comparison reversed. < becomes > and vice versa. Initialize the minimum to the largest value possible, which is float("inf"), or to the first element of the list.

FYI, Python has a builtin min function for this purpose.

1 Comment

This will work. A more sophisticated approach will capture the initial value as the starting point rather than using an infinity value to start with :-)
2

You must set n to a very high number (higher than any of the expected) or to take one from the list to start comparison:

def large(s)
    n = s.pop()
    for number in s:
        if number < n:
            n = number 
    return n 

Obviously you have already max and min for this purpose.

2 Comments

This is a nice example that avoids infinity values. See the stats() example for how to do it without requiring a list input.
@RaymondHettinger thanks, yes I see the iterator pattern. Also very useful for reading files when getting text headers or to analyze line structure is needed before starting iterating the thing.
1

A straightforward solution:

def minimum(lst):
    n = float('+inf')
    for num in lst:
        if num < n:
            n = num
    return n

Explanation: first, you initialize n (the minimum number) to a very large value, in such a way that any other number will be smaller than it - for example, the infinite value. It's an initialization trick, in case the list is empty, it will return infinite, meaning with that that the list was empty and it didn't contain a minimum value.

After that, we iterate over all the values in the list, checking each one to see if it is smaller than the value we assumed to be the minimum. If a new minimum is found, we update the value of n.

At the end, we return the minimum value found.

2 Comments

See the stats example for a more robust way to do this without infinity values.
@RaymondHettinger the reason I initialized n in a special value (infinity in my case) is to take into account the special case when the list is empty. Your code throws an exception for an empty list, mine returns a special value - it's a matter of style
1

Why not just replace large with small and > with <? Also, you might not want to initialize n to 0 if you're looking for the smallest value. Your large function only works for lists of positive numbers. Also, you're missing a ":" after your def line.

def small(s):
    if len(s)==0: return None
    n = s[0]
    for number in s[1:]:
        if n < number:
            n=number 
    return n 

This handles empty lists by returning None.

Comments

1

Using this function to find minimum is

min=-large(-s)

The logic is just to find maximum of the negative list , which gives the minimum value

Comments

1

You can use same function with iteration just instead of n=0 use n=L[0]

def min(L): n=L[0] for x in L: if x

Comments

0

def min(s):

n=s[0]

for number in s:                
    if number < n:        
        n=number                                 
return n                                            

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.