Design of Computer Programs L3

Course Digest

正則表達(dá)式30min教程

Code1
Code2
  • 格式化字符串??
def matchset(pattern, text):
    "Match pattern at start of text; return a set of remainders of text."
    op, x, y = components(pattern)
    if 'lit' == op:
        return set([text[len(x):]]) if text.startswith(x) else null
    elif 'seq' == op:
        return set(t2 for t1 in matchset(x, text) for t2 in matchset(y, t1))
    elif 'alt' == op:
        return matchset(x, text) | matchset(y, text)
    elif 'dot' == op:
        return set([text[1:]]) if text else null
    elif 'oneof' == op:
        # return set([text[1:]]) if text[0] in x else null
        return set(text[1:]]) if text.startwith(x) 
    elif 'eol' == op:
        return set(['']) if text == '' else null
    elif 'star' == op:
        return (set([text]) |
                set(t2 for t1 in matchset(x, text)
                    for t2 in matchset(pattern, t1) if t1 != text))
    else:
        raise ValueError('unknown pattern: %s' % pattern)
        
null = frozenset()

def components(pattern):
    "Return the op, x, and y arguments; x and y are None if missing."
    x = pattern[1] if len(pattern) > 1 else None
    y = pattern[2] if len(pattern) > 2 else None
    return pattern[0], x, y
   
def test():
    assert matchset(('lit', 'abc'), 'abcdef')            == set(['def'])
    assert matchset(('seq', ('lit', 'hi '),
                     ('lit', 'there ')), 
                   'hi there nice to meet you')          == set(['nice to meet you'])
    assert matchset(('alt', ('lit', 'dog'), 
                    ('lit', 'cat')), 'dog and cat')      == set([' and cat'])
    assert matchset(('dot',), 'am i missing something?') == set(['m i missing something?'])
    assert matchset(('oneof', 'a'), 'aabc123')           == set(['abc123'])
    assert matchset(('eol',),'')                         == set([''])
    assert matchset(('eol',),'not end of line')          == frozenset([])
    assert matchset(('star', ('lit', 'hey')), 'heyhey!') == set(['!', 'heyhey!', 'hey!'])
    
    return 'tests pass'

print test()
  • str.startwith(x) 中x可以是一個(gè)tuple
dis Module
def test(a):
      return 1 if a>0 else 0 if a == 0 else -1
  • 編譯器優(yōu)化之一:避免重復(fù)
genseq
  • 函數(shù)式編程(裝飾器用法)
def n_ary(f):
    """Given binary function f(x, y), return an n_ary function such
    that f(x, y, z) = f(x, f(y,z)), etc. Also allow f(x) = x."""
    def n_ary_f(x, *args):
        # return f(x) if len(args)==0 else f(x, args[0]) \
        #     if len(args)==1 else f(x, n_ary_f(args[0], *args[1:]))
        return x if not args else f(x, n_ary_f(*args))
    return n_ary_f

@n_ary
def seq(x, y):
    return ('seq', x, y)

print(seq(1, 2, 3, 4, 5))
# output:  ('seq', 1, ('seq', 2, ('seq', 3, ('seq', 4, 5))))
update_wrapper
等效做法
  • @decorator 該函數(shù)定義了一些遷移文檔的語(yǔ)句塊(大概)。這樣很是方便。

后面的函數(shù)名稱(chēng)會(huì)在命名空間中覆寫(xiě)掉之前的定義

def test():
    print('test')

def test():
    print('Fake test')

test()
# Out: Fake test
  • Memoization: look-up, computation, store
    Memoization
Memo demo
  • Interesting:老師隨意給出一個(gè)數(shù)字——42。_
  • 字典的鍵值必須immutable.s
Counter Decorator
  • Tools types

  • debugging tool

  • performance tool

  • expressive tool

  • ** Usefule trace decorator**

from functools import update_wrapper

def decorator(d):
    "Make function d a decorator: d wraps a function fn."
    def _d(fn):
        return update_wrapper(d(fn), fn)
    update_wrapper(_d, d)
    return _d

@decorator
def trace(f):
    indent = '   '
    def _f(*args):
        signature = '%s(%s)' % (f.__name__, ', '.join(map(repr, args)))
        print '%s--> %s' % (trace.level*indent, signature)
        trace.level += 1
        try:
            result = f(*args)
            print '%s<-- %s == %s' % ((trace.level-1)*indent, 
                                      signature, result)
        finally:
            trace.level -= 1
        return result
    trace.level = 0
    return _f

@trace
def fib(n):
    if n == 0 or n == 1:
        return 1
    else:
        return fib(n-1) + fib(n-2)

fib(6) 
Disable Decorator
  • ** Context-free languages**
  • ** Wishful Thinking**
# ---------------
# User Instructions
#
# Modify the parse function so that it doesn't repeat computations.
# You have learned about a tool in this unit that prevents 
# repetitive computations. Try using that!
#
# For this question, the grader will be looking for a specific 
# solution. Hint: it should only involve adding one line of code
# (and that line should only contain 5 characters).

from functools import update_wrapper
import re

def parse(start_symbol, text, grammar):
    """Example call: parse('Exp', '3*x + b', G).
    Returns a (tree, remainder) pair. If remainder is '', it parsed the whole
    string. Failure iff remainder is None. This is a deterministic PEG parser,
    so rule order (left-to-right) matters. Do 'E => T op E | T', putting the
    longest parse first; don't do 'E => T | T op E'
    Also, no left recursion allowed: don't do 'E => E op T'"""

    tokenizer = grammar[' '] + '(%s)'

    def parse_sequence(sequence, text):
        result = []
        for atom in sequence:
            tree, text = parse_atom(atom, text)
            if text is None: return Fail
            result.append(tree)
        return result, text

    @memo  # This decorator makes parser work faster.
    def parse_atom(atom, text):
        if atom in grammar:  # Non-Terminal: tuple of alternatives
            for alternative in grammar[atom]:
                tree, rem = parse_sequence(alternative, text)
                if rem is not None: return [atom]+tree, rem  
            return Fail
        else:  # Terminal: match characters against start of text
            m = re.match(tokenizer % atom, text)
            return Fail if (not m) else (m.group(1), text[m.end():])
    
    # Body of parse:
    return parse_atom(start_symbol, text)

Fail = (None, None)

# The following decorators may help you solve this question. HINT HINT!

def decorator(d):
    "Make function d a decorator: d wraps a function fn."
    def _d(fn):
        return update_wrapper(d(fn), fn)
    update_wrapper(_d, d)
    return _d

@decorator
def memo(f):
    """Decorator that caches the return value for each call to f(args).
    Then when called again with same args, we can just look it up."""
    cache = {}
    def _f(*args):
        try:
            return cache[args]
        except KeyError:
            cache[args] = result = f(*args)
            return result
        except TypeError:
            # some element of args can't be a dict key
            return f(args)
    return _f
Verify Fucntion
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • http://python.jobbole.com/85231/ 關(guān)于專(zhuān)業(yè)技能寫(xiě)完項(xiàng)目接著寫(xiě)寫(xiě)一名3年工作經(jīng)驗(yàn)的J...
    燕京博士閱讀 7,791評(píng)論 1 118
  • # 第一優(yōu)先級(jí)規(guī)則聲明: # 除了夢(mèng)境,每一個(gè)意識(shí)主進(jìn)程都必須與一個(gè)身體參與的機(jī)械進(jìn)程相匹配,否則結(jié)束意識(shí)主進(jìn)程。...
    李洞BarryLi閱讀 4,196評(píng)論 0 1
  • 教程地址:python進(jìn)階 - 慕課網(wǎng) python函數(shù)式編程 變量可以指向函數(shù): f = absprint(f)...
    竹口小生閱讀 675評(píng)論 0 2
  • Python進(jìn)階框架 希望大家喜歡,點(diǎn)贊哦首先感謝廖雪峰老師對(duì)于該課程的講解 一、函數(shù)式編程 1.1 函數(shù)式編程簡(jiǎn)...
    Gaolex閱讀 5,982評(píng)論 6 53
  • 《千與千尋》 湯屋,從千尋誤入神隱世界,它便一直吸引著我們的眼球。白天,荒無(wú)人煙的一座古城。晚上,華燈初上,人聲鼎...
    夏至微雪閱讀 561評(píng)論 1 4

友情鏈接更多精彩內(nèi)容