Week 1
Homework
Q1: A Plus Abs B
Fill in the blanks in the following function definition for adding a
to the absolute value of b
, without calling abs
.
from operator import add, sub
def a_plus_abs_b(a, b):
"""Return a+abs(b), but without calling abs.
>>> a_plus_abs_b(2, 3)
5
>>> a_plus_abs_b(2, -3)
5
"""
if b < 0:
f = _____
else:
f = _____
return f(a, b)
我的答案
def a_plus_abs_b(a, b):
if b < 0:
f = sub
else:
f = add
return f(a, b)
Q2: Two of Three
Write a function that takes three positive numbers and returns the sum of the squares of the two largest numbers. Use only a single line for the body of the function.
def two_of_three(a, b, c):
"""Return x*x + y*y, where x and y are the two largest members of the
positive numbers a, b, and c.
>>> two_of_three(1, 2, 3)
13
>>> two_of_three(5, 3, 1)
34
>>> two_of_three(10, 2, 8)
164
>>> two_of_three(5, 5, 5)
50
"""
return _____
我的答案
return max(a*a + b*b, a*a + c*c