Python编程:计算三个数最大值的3中方法

2021年4月1日18:25:37 发表评论 807 次浏览

给定三个数字a b和c, 任务是我们必须找到给定数字中的最大元素

例子:

Input : a = 2, b = 4, c = 3
Output : 4 

Input : a = 4, b = 2, c = 6 
Output : 6

方法1(简单)

# Python program to find the largest
# number among the three numbers
  
def maximum(a, b, c):
  
     if (a > = b) and (a > = c):
         largest = a
  
     elif (b > = a) and (b > = c):
         largest = b
     else :
         largest = c
          
     return largest
  
  
# Driven code 
a = 10
b = 14
c = 12
print (maximum(a, b, c))

输出如下:

14

方法2(使用列表)

用n1, n2和n3初始化三个数字

将三个数字加到列表lst = [n1, n2, n3]。

使用max()函数查找最大数max(lst)。

最后, 我们将打印最大数量

# Python program to find the largest number 
# among the  three numbers using library function 
  
def maximum(a, b, c):
     list = [a, b, c]
     return max ( list )
  
# Driven code 
a = 10
b = 14
c = 12
print (maximum(a, b, c))

输出如下:

14

方法3(使用max函数)

# Python program to find the largest number 
# among the  three numbers using library function 
  
# Driven code 
a = 10
b = 14
c = 12
print ( max (a, b, c))

输出如下:

14

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: