Skip to content

Commit aa556d0

Browse files
authored
Add one-line method to Q38.
1. 把函数名的大写变为小写 2. 给原来的方法中加了漏掉的空格 3. 把方法二中的无用的 `else` 去掉 3. 加了一种一行的方法
1 parent ceb86c4 commit aa556d0

File tree

1 file changed

+21
-11
lines changed

1 file changed

+21
-11
lines changed

README.md

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -875,29 +875,39 @@ def func1(l):
875875
```
876876
### 38.写一个函数找出一个整数数组中,第二大的数
877877
```python
878-
def find_Second_large_num(num_list):
878+
def find_second_large_num(num_list):
879879
"""
880880
找出数组第2大的数字
881881
"""
882-
#直接排序,输出倒数第二个数即可
882+
# 方法一
883+
# 直接排序,输出倒数第二个数即可
883884
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("方法一\nSecond_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
887890
one = num_list[0]
888891
two = num_list[0]
889-
for i in range(1,len(num_list)):
892+
for i in range(1, len(num_list)):
890893
if num_list[i] > one:
891894
two = one
892895
one = num_list[i]
893896
elif num_list[i] > two:
894897
two = num_list[i]
895-
else:
896-
pass
897-
print("Second_large_num is :",two)
898+
print("方法二\nSecond_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("方法三\nSecond_large_num is :", num)
906+
907+
898908
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)
901911
```
902912
### 39.阅读一下代码他们的输出结果是什么?
903913
```python

0 commit comments

Comments
 (0)