Problem 9: Second Largest (100pts)
Problem
Write a function that takes in three comparable values
x
,y
, andz
, return the second largest value. More precisely, ifx
is the second largest value inx
,y
, andz
, theny >= x >= z or z >= x >= y
.Compared to the Problem 2, in this question, you cannot assume that the input values support arithmetic operations. Solve this problem using only comparison or functions like
min
andmax
.Warning:
You should not use data structures like lists and the
sorted
function in this problem.Violating this requirement may result in 0 score in online judge testing.
编写一个函数,接受三个可比较的值 x
、y
和 z
作为参数,返回第二大的值。更精确地说,如果 x
是 x
、y
和 z
中的第二大值,那么满足 y >= x >= z
或 z >= x >= y
。
与问题 2 相比,在这个问题中,你不能假设输入值支持算术运算。只能使用比较运算符或像 min
和 max
这样的函数来解决此问题。
Warning
在本问题中,您不应使用列表等数据结构或 sorted
函数。
违反此要求可能导致在线判题测试得分为 0。
def second_largest(x, y, z):
"""Return the second largest value in `x`, `y`, and `z`.
More precisely, if `x` is the second largest value in `x`, `y`, and `z`,
then `y >= x >= z` or `z >= x >= y`.
>>> second_largest(1, 1, 1)
1
>>> second_largest(1, 2, 3)
2
>>> second_largest(6, 5, 4)
5
>>> second_largest(1, 3, 2)
2
>>> second_largest(2, 3, 1)
2
>>> second_largest(2, 2, 1)
2
>>> second_largest(1, 2, 1)
1
>>> second_largest('a', 'b', 'c') # strings in python are also comparable
'b'
>>> check_no_square_brackets(second_largest)
"""
"*** YOUR CODE HERE ***"
Hints
-
有一个简洁数学方法,可以只用
min
和max
,直接return
-
可以写三个
if
来实现 -
可以自己写一个排序
-
测试案例有字符串,所以没法加减
-
本地测试只检测了方括号,OJ 的检测严格很多,可能本地和 OJ 检测结果不一样