CS61A 10

Mutable Function & Growth

10.1 Functions with behavior that changes over time

def make_withdraw(balance):
    def withdraw(amount):
        nonlocal balance
        if amount > balance:
            return 'insufficient funds'
        balance = balance - amount
        return balance
    return withdraw
>>> withdraw = make_withdraw(100)
>>> withdraw(10)
90
>>> withdraw(10)
80

nonlocal: first nonlocal frame
nonlocal 注意两个特性:一是不能在local中重复定义:

def f():
    def g(x):
        nonlocal x
        return 2 * x
    return g

SyntaxError: name 'x' is parameter and nonlocal

二是不能定义global environment中的变量:

x = 4
def g():
    nonlocal x
    return 2 * x

SyntaxError: no binding for nonlocal 'x' found

对比没有nonlocal声明

def make_withdraw(balance):
    def withdraw(amount):
        if amount > balance:
            return 'insufficient funds'
        new_balance = balance - amount
        return new_balance
    return withdraw
>>> withdraw = make_withdraw(100)
>>> withdraw(10)
90
>>> withdraw(10)
90

Example:

def f(x):
    x = 4
    def g(y):
        def h(z):
            nonlocal x
            x = x + 1
            return x + y + z
        return h
    return g

a = f(1)
b = a(2)
total = b(3) + b(4)

Answer: 22

a = f(1): x = 1 → x = 4 
b = a(2): y = 2
b(3): z = 3 → x = 4 + 1 → x + y + z = 5 + 2 + 3 = 10
b(4): z = 4 → x = 5 + 1 → x + y + z = 6 + 2 + 4 = 12
total = 22

10. 2 Measuring Growth

Common Patterns

Linear Growth
Logarithmic Growth
Exponential Growth
Example:
在这里插入图片描述Linear Growth → Logarithmic Growth

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值