010. Python 最大最小

版权声明:欢迎联系我转载!欢迎交流分享!转载和分享请注明出处! https://blog.csdn.net/u014303046/article/details/82555538

The most numbers

一、题目描述

要求:给定一组浮点数,找到这组数字最大值和最小值的差;要求程序可以自适应个数不同的参数,如果这组数字是空集,返回0.

输入:一组数字

输出:浮点数

示例

checkio(1, 2, 3) == 2
checkio(5, -5) == 10
checkio(10.2, -2.2, 0, 1.1, 0.5) == 12.4
checkio() == 0

二、解题示例

1.学会可变参数

def checkio(*args):
    tmp = list(args)
    return 0 if len(tmp) == 0 else max(tmp) - min(tmp)

#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    def almost_equal(checked, correct, significant_digits):
        precision = 0.1 ** significant_digits
        return correct - precision < checked < correct + precision

    assert almost_equal(checkio(1, 2, 3), 2, 3), "3-1=2"
    assert almost_equal(checkio(5, -5), 10, 3), "5-(-5)=10"
    assert almost_equal(checkio(10.2, -2.2, 0, 1.1, 0.5), 12.4, 3), "10.2-(-2.2)=12.4"
    assert almost_equal(checkio(), 0, 3), "Empty"
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")

2.精简写法

def checkio(*args):
    return max(args) - min(args) if args else 0

if __name__ == '__main__':
    def almost_equal(checked, correct, significant_digits):
        precision = 0.1 ** significant_digits
        return correct - precision < checked < correct + precision

    assert almost_equal(checkio(1, 2, 3), 2, 3), "3-1=2"
    assert almost_equal(checkio(5, -5), 10, 3), "5-(-5)=10"
    assert almost_equal(checkio(10.2, -2.2, 0, 1.1, 0.5), 12.4, 3), "10.2-(-2.2)=12.4"
    assert almost_equal(checkio(), 0, 3), "Empty"
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")

猜你喜欢

转载自blog.csdn.net/u014303046/article/details/82555538