Homework 1: Variables & Functions, Control
Q1: Syllabus Quiz
Q2: A Plus Abs B
Fill in the blanks in the following function for adding
a
to the absolute value ofb
, without callingabs
. You may not modify any of the provided code other than the two blanks.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 >>> # a check that you didn't change the return statement! >>> import inspect, re >>> re.findall(r'^\s*(return .*)', inspect.getsource(a_plus_abs_b), re.M) ['return f(a, b)'] """ if b < 0: f = _____ else: f = _____ return f(a, b)
Answer:
if b < 0:
f = sub(a, b)
else:
f = add(a, b)
return f(a, b)
看示例可知 其实 f = a + |b|
所以b<0时取 a - b 就相当于取 b 的绝对值
Q3: Two of Three
Write a function that takes three positive numbers as arguments and returns the sum of the squares of the two smallest numbers. Use only a single line for the body of the function.