I'm working on a small task from the checkio-python coding game. It involves hard-scripting the built-in functions min() and max().
Anyway to "store" the minimal or maximal value, I thought of initializing a variable first and then store the respective lowest or highest value in it.
min_value = None
...function to compare element 1 with element 2 of a list and find lowest..
min_value = lowest_value
...function continues
When I realized that I had forgotten to compare the min_value with the lowest_value, to make sure that I would have the "globally" lowest value (of the whole list). But when I compare it, it gives me a NoneError with the first initialized variable.
min_value = None
...function to compare element 1 with element 2 and find lowest..
if lowest_value < min_value:
NoneError
So how could I initialize a value without a value, which has in this case also the highest possible value, which then would change after the first comparison.
I hope, I that I was able to make my question clear.
Thanks!
3 Answers 3
Depend of the type of the value.
For a int, then use:
min_value = sys.maxsize
For a float, then use:
min_value = float('inf')
So any values will be smaller than those maximal numbers.
Alternatively, you can define the initial value with the first value of your list and iterate the list from the second value.
min_value = list[0]
for value in list[1:]:
if value < min_value:
min_value = value
This has the advantage to work with any type.
Even more alternatively, you can reduce a lambda expression like this:
min_value = reduce(lambda min_value, value: min_value if (min_value < value) else value, list)
Comments
Instead in initializing them as None, you can initialize them with a maximum/minimum integer value:
import sys
min_value = sys.maxsize
max_value = -sys.maxsize
Comments
You just have to make sure that you are not comparing to None:
mylist = [2, 5, 3, 6, 7, 4, 8]
min_value = None
for num in mylist:
if min_value is not None and num > min_value:
continue
else:
min_value = num
print "Minimum value: {0}".format(min_value)
Produces:
Minimum value: 2