# HW 04
# Q1: Weights
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]
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# Q2: Balanced
if is_planet(m):
return True
return length(left(m)) * total_weight(end(left(m))) == length(right(m)) * total_weight(end(right(m))) and balanced(end(left(m))) and balanced(end(right(m)))
1
2
3
2
3
# Q3: Totals
if is_planet(m):
return [size(m)]
return [total_weight(m), totals_tree(end(left(m))), totals_tree(end(right(m)))]
1
2
3
2
3
# Trees
# Q4: Replace Leaf
if is_leaf(t) and old == label(t):
return tree(replacement)
return tree(label(t),[replace_leaf(branch,old,replacement) for branch in branches(t)])
1
2
3
2
3
# Q5: Password Protected Account
注意尝试三次后账号将被锁定!
try_pwds = []
def withdraw(amount, pas):
nonlocal balance
if len(try_pwds) >= 3:
return "Your account is locked. Attempts: " + str(try_pwds)
if password != pas:
try_pwds.append(pas)
return 'Incorrect password'
if amount > balance:
return 'Insufficient funds'
balance = balance - amount
return balance
return withdraw
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# Q6: Joint Account
其实在 withdraw 函数上加限制条件就好了。
account = withdraw(0, old_pass)
if type(account) == str:
return account
def joint(money, pwd):
if pwd == new_pass or pwd == old_pass:
return withdraw(money, old_pass)
return withdraw(money, pwd)
return joint
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# Extra Questions
下面是一些区间方面的函数抽象。
# Q7: Interval Abstraction
注意格式。
答案:interval.py
代码实现:
def lower_bound(x):
return x[0]
def upper_bound(x):
return x[1]
1
2
3
4
5
2
3
4
5
# Q8: Sub Interval
答案:mul_interval.py 。
# Q9: Div Interval
# Q11: Quadratic
point = -b/(2*a)
point_val = a*point*point + b*point + c
lower_val = a*lower_bound(x)*lower_bound(x)+ b*lower_bound(x) + c
upper_val = a*upper_bound(x)*upper_bound(x)+ b*upper_bound(x) + c
if point > lower_bound(x) and point < upper_bound(x):
return interval(min(lower_val,upper_val,point_val), max(lower_val,upper_val,point_val))
else:
return interval(min(lower_val,upper_val), max(lower_val,upper_val))
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8