Computer >> Máy Tính >  >> Lập trình >> Python

Sử dụng min () và max () trong Python

Trong bài viết này, chúng ta sẽ tìm hiểu về các hàm min và max có trong Thư viện chuẩn Python. Nó chấp nhận vô số tham số tùy theo cách sử dụng

Cú pháp

max( arg1,arg2,arg3,...........)

Giá trị trả lại - Tối đa tất cả các đối số

Lỗi &Ngoại lệ:Ở đây lỗi chỉ xuất hiện trong trường hợp các đối số không cùng loại. Đã gặp lỗi khi so sánh chúng.

Trước tiên, hãy xem tất cả các cách chúng ta có thể triển khai hàm max ().

Ví dụ

# Getting maximum element from a set of arguments passed
print("Maximum value among the arguments passed is:"+str(max(2,3,4,5,7,2,1,6)))
# the above statement also executes for characters as arguments
print("Maximum value among the arguments passed is:"+str(max('m','z','a','b','e')))
# it can also a accept arguments mapped in the form of a list
l=[22,45,1,7,3,2,9]
print("Maximum element of the list is:"+str(max(l)))
# it can also a accept arguments mapped in the form of a tuple
l=(22,45,1,7,71,91,3,2,9)
print("Maximum element of the tuple is:"+str(max(l)))

Đầu ra

Maximum value among the arguments passed is:7
Maximum value among the arguments passed is:z
Maximum element of the list is:45
Maximum element of the tuple is:91

Ở đây có thể thấy rõ rằng bằng cách sử dụng hàm max, chúng ta có thể nhận trực tiếp các giá trị lớn nhất giữa các đối số mà không cần bất kỳ thao tác so sánh nào.

Tương tự, chúng ta có thể triển khai hàm min () tại đây

Ví dụ

# Getting maximum element from a set of arguments passed
print("Minimum value among the arguments passed is:"+str(min(2,3,4,5,7,2,1,6)))
# the above statement also executes for characters as arguments
print("Minimum value among the arguments passed is:"+str(min('m','z','a','b','e')))
# it can also a accept arguments mapped in the form of a list
l=[22,45,1,7,3,2,9]
print("Minimum element of the list is:"+str(min(l)))
# it can also a accept arguments mapped in the form of a tuple
l=(22,45,1,7,71,91,3,2,9)
print("Minimum element of the tuple is:"+str(min(l)))

Đầu ra

Minimum value among the arguments passed is:1
Minimum value among the arguments passed is:a
Minimum element of the list is:1
Minimum element of the tuple is:1

Bằng cách sử dụng các hàm tích hợp sẵn như max () &min (), chúng ta có thể trực tiếp nhận được các giá trị tối đa và tối thiểu tương ứng mà không cần triển khai logic thực tế để thực hiện so sánh

Kết luận

Trong bài viết này, chúng ta đã học cách triển khai hàm max và min có trong Thư viện Python chuẩn.