@@ -875,29 +875,39 @@ def func1(l):
875
875
```
876
876
### 38.写一个函数找出一个整数数组中,第二大的数
877
877
``` python
878
- def find_Second_large_num (num_list ):
878
+ def find_second_large_num (num_list ):
879
879
"""
880
880
找出数组第2大的数字
881
881
"""
882
- # 直接排序,输出倒数第二个数即可
882
+ # 方法一
883
+ # 直接排序,输出倒数第二个数即可
883
884
tmp_list = sorted (num_list)
884
- print (" Second_large_num is :" ,tmp_list[- 2 ])
885
- # 设置两个标志位一个存储最大数一个存储次大数
886
- # two 存储次大值,one存储最大值,遍历一次数组即可,先判断是否大于one,若大于将one的值给two,将num_list[i]的值给one,否则比较是否大于two,若大于直接将num_list[i]的值给two,否则pass
885
+ print (" 方法一\n Second_large_num is :" , tmp_list[- 2 ])
886
+
887
+ # 方法二
888
+ # 设置两个标志位一个存储最大数一个存储次大数
889
+ # two 存储次大值,one 存储最大值,遍历一次数组即可,先判断是否大于 one,若大于将 one 的值给 two,将 num_list[i] 的值给 one,否则比较是否大于two,若大于直接将 num_list[i] 的值给two,否则pass
887
890
one = num_list[0 ]
888
891
two = num_list[0 ]
889
- for i in range (1 ,len (num_list)):
892
+ for i in range (1 , len (num_list)):
890
893
if num_list[i] > one:
891
894
two = one
892
895
one = num_list[i]
893
896
elif num_list[i] > two:
894
897
two = num_list[i]
895
- else :
896
- pass
897
- print (" Second_large_num is :" ,two)
898
+ print (" 方法二\n Second_large_num is :" , two)
899
+
900
+ # 方法三
901
+ # 用 reduce 与逻辑符号 (and, or)
902
+ # 基本思路与方法二一样,但是不需要用 if 进行判断。
903
+ from functools import reduce
904
+ num = reduce (lambda ot , x : ot[1 ] < x and (ot[1 ], x) or ot[0 ] < x and (x, ot[1 ]) or ot, num_list, (0 , 0 ))[0 ]
905
+ print (" 方法三\n Second_large_num is :" , num)
906
+
907
+
898
908
if __name__ == ' __main___' :
899
- num_list = [34 ,11 ,23 ,56 ,78 ,0 , 9 , 12 ,3 , 7 , 5 ]
900
- find_Second_large_num (num_list)
909
+ num_list = [34 , 11 , 23 , 56 , 78 , 0 , 9 , 12 , 3 , 7 , 5 ]
910
+ find_second_large_num (num_list)
901
911
```
902
912
### 39.阅读一下代码他们的输出结果是什么?
903
913
``` python
0 commit comments