Reputation: 3
I am currently learning python coding and I come across this qns on a learning site:
Create a function that takes a sequence of inputs (may be a list, a tuple, or just a bunch of inputs). The function should return the minimum and the maximum of the list.
This are some of the test values that are using:
minmax(5,4) 4,5
minmax(5,4,8,3,5,7,4) 3,8
minmax([5,4,6]) 4,6
minmax(5.1,4.2,68.34,129.1,-90.3) -90.3,129.1
And I had tried doing it this way but when the parameter is a list, I can't seems to convert it into a tuple and find the max and min. Here is what I had tried:
def minmax(*a):
b = tuple(a)
minNum = min(b)
maxNum = max(b)
c = (minNum, maxNum)
return c
When a list is taken in, the return result is ([5, 4, 6], [5, 4, 6])
Upvotes: 0
Views: 973
Reputation: 94565
def minmax(*a):
if len(a) == 1: # Single (list, tuple, or scalar) argument
try:
return minmax(*a[0]) # Expansion of sequence elements, if possible
except TypeError: # Case of minmax(42)
pass # The general code below handles this directly
return (min(a), max(a))
>>> minmax(3, 5, 1, 10)
(1, 10)
>>> minmax([3, 5, 1, 10])
(1, 10)
>>> minmax((42, 123, -12))
(-12, 123)
>>> minmax(42)
42
This works in more cases than the built-in min()
and max()
, which do not work on a single scalar argument (min(42)
).
>>> min(42)
TypeError: 'int' object is not iterable
It is however possible to write a simpler version that behaves like the built-in min()
and max()
(see my other answer, for instance).
This works by forcing min()
to be given strictly more than 1 element, except in the special case of minmax(42)
, which calls min((42,))
.
Upvotes: 2
Reputation: 94565
A simpler but slightly less powerful solution that mirrors my other solution is:
def minmax(*a):
if len(a) == 1: # Single (list or tuple) argument
return (min(a[0]), max(a[0]))
return minmax(a) # Single tuple argument given to minmax()
This version forces min()
to be given a single (list or tuple) argument.
It behaves like the built-in min()
and max()
: min(42)
and minmax(42)
both raise an exception:
>>> minmax(3, 5, 1, 10)
(1, 10)
>>> minmax([3, 5, 1, 10])
(1, 10)
>>> minmax((42, 123, -12))
(-12, 123)
>>> minmax(42)
TypeError: 'int' object is not iterable
>>> min(42)
TypeError: 'int' object is not iterable
Upvotes: 0
Reputation: 134491
To be able to handle different ways of passing in arguments, you need to have some conditions to handle each case.
>>> def minmax(*a):
... if len(a) == 1 and hasattr(a[0], '__getitem__'):
... # handle a single sequence passed in
... return min(a[0]), max(a[0])
... # handle values passed in
... return min(a), max(a)
...
>>> minmax(5, 4)
(4, 5)
>>> minmax(5, 4, 8, 3, 5, 7, 4)
(3, 8)
>>> minmax([5, 4, 6])
(4, 6)
>>> minmax(5.1, 4.2, 68.34, 129.1, -90.3)
(-90.3, 129.1)
Upvotes: 1