hw04 of CS61A of UCB
作者:互联网
Mobiles
Q2: Weights
Implement the
planet
data abstraction by completing theplanet
constructor and thesize
selector so that a planet is represented using a two-element list where the first element is the string'planet'
and the second element is its size.
从问题的描述中我们可以知道什么是 planet
. 就是一个长度为 2 的 list
, 内容是 ['planet', size]
. 可以参考 mobile
函数, 这两个函数的代码是很类似的
def planet(size):
"""Construct a planet of some size."""
assert size > 0
return ['planet', size]
def size(w):
"""Select the size of a planet."""
assert is_planet(w), 'must call size on a planet'
return w[1]
Q3: Balanced
Implement the
balanced
function, which returns whetherm
is a balanced mobile. A mobile is balanced if both of the following conditions are met:
- The torque applied by its left arm is equal to that applied by its right arm. The torque of the left arm is the length of the left rod multiplied by the total weight hanging from that rod. Likewise for the right. For example, if the left arm has a length of
5
, and there is amobile
hanging at the end of the left arm of weight10
, the torque on the left side of our mobile is50
.- Each of the mobiles hanging at the end of its arms is balanced.
Planets themselves are balanced, as there is nothing hanging off of them.
这个问题需要用递归的方法来解决. 我们判断一个 mobile 平衡的条件如下
- 它是
planet
, 根据描述可以知道本身是平衡的 - 它是
arm
, 并且total_weight(left_arm) == total_weight(right_arm)
. 并且它的所有子树都要符合这个平衡的条件. 注意不要漏掉对子树的判断
写出代码的关键: 要区分开 arm
, planet
, mobile
这三个概念并且要能够知道用什么对应的函数来处理.
标签:return,hw04,interval,tree,bound,CS61A,planet,UCB,arm 来源: https://www.cnblogs.com/MartinLwx/p/15915545.html