Homework 1: Variables & Functions, Control
Q1: Syllabus Quiz
Q2: A Plus Abs B
Fill in the blanks in the following function for adding
ato 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 functio

这是CS61A课程2019秋季的作业1,涉及变量、函数及控制结构。包括Syllabus Quiz、求绝对值问题、两数平方和、最大因子查找以及If函数与语句的区别。此外,还介绍了Hailstone序列的计算及其步数。

890

被折叠的 条评论
为什么被折叠?



