key
: Optional. Key function, where items pass. The comparison is performed on the result returned after passing the key function.The min () function returns different results corresponding to the two types as above:
1. min(iterable, *iterables[, key, default])
2. min(item1, item2, *item[, key])
# su dung min(item1, item2, *item) print('So nho nhat la:', min(1, 3, 2, 5, 4)) # su dung min(iterable) num = [1, 3, 2, 8, 5, 10, 6] print('So nho nhat la:', min(num))
Run the program, the result is:
So nho nhat la: 1 So nho nhat la: 2
def sumDigit(num): sum = 0 while(num): sum += num % 10 num = int(num / 10) return sum # su dung min(item1, item2, *item, key) print('Ket qua nho nhat la:', min(100, 321, 267, 59, 40, key=sumDigit)) # su dung min(iterable, key) num = [15, 300, 2700, 821, 52, 10, 6] print('Ket qua nho nhat la:', min(num, key=sumDigit))
The return output is:
Ket qua nho nhat la: 100 Ket qua nho nhat la: 10
In this example, the parameters or each element in the iterable parameter are passed in turn to sumDigit()
to get the result that the number has the smallest sum of digits.
num = [15, 300, 2700, 821] num1 = [12, 2] num2 = [34, 567, 78] # su dung min(iterable, *iterables, key) print('List ngan nhat la:', min(num, num1, num2, key=len))
Results returned:
List ngan nhat la: [12, 2]
In the above program, iterable num, num1 and num2 passed into the key function are built-in len () functions in Python. The result is iterable, and the min () function will iterable with the smallest length.
See also: Built-in Python functions