一亩三分地论坛

 找回密码
 获取更多干货,去instant注册!

扫码关注一亩三分地公众号
查看: 1391|回复: 8
收起左侧

[CS61A]lab05

[复制链接] |试试Instant~ |关注本帖
sky420 发表于 2015-5-23 00:15:29 | 显示全部楼层 |阅读模式

[其他]CS61A #2 - 04@UCBerkely

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看,没有帐号?获取更多干货,去instant注册!

x
本帖最后由 AveMaleficum 于 2015-5-24 15:07 编辑

Lab05: http://gaotx.com/cs61a/lab/lab05/
My Solution: http://gaotx.com/blogs/2015/05/16/cs61a-lab05/


评分

1

查看全部评分

FFFelix 发表于 2015-5-23 10:54:25 | 显示全部楼层
lab05
## Trees, Dictionaries ##

#########
# Trees #
#########

import inspect
# Tree definition - same Data Abstraction but different implementation from lecture
def tree(root, branches=[]):
    #for branch in branches:
    # assert is_tree(branch)
    return lambda dispatch: root if dispatch == 'root' else list(branches)

def root(tree):
    return tree('root')

def branches(tree):
    return tree('branches')

def is_tree(tree):
    try:
        tree_data = inspect.getargspec(tree)
        assert tree_data == inspect.getargspec(lambda dispatch: None)
        return all([is_tree(branch) for branch in branches(tree)])
    except:
        return False

def is_leaf(tree):
    return not branches(tree)

def print_tree(t, indent=0):
    """Print a representation of this tree in which each node is
    indented by two spaces times its depth from the root.

    >>> print_tree(tree(1))
    1
    >>> print_tree(tree(1, [tree(2)]))
    1
      2
    >>> print_tree(numbers)
    1
      2
      3
        4
        5
      6
        7
    """
    print('  ' * indent + str(root(t)))
    for branch in branches(t):
        print_tree(branch, indent + 1)

numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])])


# Q1
def countdown_tree():
    """Return a tree that has the following structure.

    >>> print_tree(countdown_tree())
    10
      9
        8
      7
        6
          5
    """
    "*** YOUR CODE HERE ***"
    return tree(10, [tree(9, [tree(8)]), tree(7,[tree(6, [tree(5)])])])

# Q2
def size_of_tree(t):
    """Return the number of entries in the tree.

    >>> print_tree(numbers)
    1
      2
      3
        4
        5
      6
        7
    >>> size_of_tree(numbers)
    7
    """
    "*** YOUR CODE HERE ***"
    branches_num = 0
    for branch in branches(t):
        branch_num += size_of_tree(branch)  
    return branches_num + 1

################
# Dictionaries #
################

# Q3
def counter(message):
    """ Returns a dictionary of each word in message mapped
    to the number of times it appears in the input string.

    >>> x = counter('to be or not to be')
    >>> x['to']
    2
    >>> x['be']
    2
    >>> x['not']
    1
    >>> y = counter('run forrest run')
    >>> y['run']
    2
    >>> y['forrest']
    1
    """
    word_list = message.split()
    "*** YOUR CODE HERE ***"
    dict = {}
    for word in word_list:
        if word in dict:
            dict[word] += 1
        else:
            dict[word] = 1
    return dict


extra
from lab05 import *


## Extra Trees, Dictionaries Questions ##

#########
# Trees #
#########

# Q5
def height(t):
    """Return the depth of the deepest node in the tree.

    >>> height(tree(1))
    0
    >>> height(tree(1, [tree(2), tree(3)]))
    1
    >>> print_tree(numbers)
    1
      2
      3
        4
        5
      6
        7
    >>> height(numbers)
    2
    """
    "*** YOUR CODE HERE ***"
    if is_leaf(t):
        return 0
    depth = 0
    for branch in branches(t):
        depth = max(depth, height(branch))
    return depth + 1

# Q6
def acorn_finder(t):
    """Returns True if t contains a node with the value 'acorn' and
    False otherwise.

    >>> sproul = tree('roots', [tree('branch1', [tree('leaf'), tree('acorn')]), tree('branch2')])
    >>> acorn_finder(sproul)
    True
    >>> acorn_finder(numbers)
    False
    """
    "*** YOUR CODE HERE ***"
    if root(t) == 'acorn':
        return True
    else:
        for branch in branches(t):
            if acorn_finder(branch) == True:
                return True
    return False

# Q7
def preorder(t):
    """Return a list of the entries in this tree in the order that they
    would be visited by a preorder traversal (see problem description).

    >>> preorder(numbers)
    [1, 2, 3, 4, 5, 6, 7]
    >>> preorder(tree(2, [tree(4, [tree(6)])]))
    [2, 4, 6]
    """
    "*** YOUR CODE HERE ***"
    if branches(t) == []:
        return [root(t)]
    pre = []
    for branch in branches(t):
        pre += preorder(branch)
    return [root(t)] + pre

################
# Dictionaries #
################

# Q8
def build_successors_table(tokens):
    """Return a dictionary: keys are words; values are lists of
    successors.

    >>> text = ['We', 'came', 'to', 'investigate', ',', 'catch', 'bad', 'guys', 'and', 'to', 'eat', 'pie', '.']
    >>> table = build_successors_table(text)
    >>> sorted(table)
    [',', '.', 'We', 'and', 'bad', 'came', 'catch', 'eat', 'guys', 'investigate', 'pie', 'to']
    >>> table['to']
    ['investigate', 'eat']
    >>> table['pie']
    ['.']
    >>> table['.']
    ['We']
    """
    table = {}
    prev = '.'
    for word in tokens:
        if prev not in table:
            "*** YOUR CODE HERE ***"
            table[prev] = []
        "*** YOUR CODE HERE ***"
        table[prev].append(word)
        prev = word
    return table

# Q9
def construct_sent(word, table):
    """Prints a random sentence starting with word, sampling from
    table.
    """
    import random
    result = ' '
    while word not in ['.', '!', '?']:
        "*** YOUR CODE HERE ***"
        result += word + ''
        word = random.choice(table[word])
    return result + word

# Warning: do NOT try to print the return result of this function
def shakespeare_tokens(path='shakespeare.txt', url='http://goo.gl/SztLfX'):
    """Return the words of Shakespeare's plays as a list."""
    import os
    from urllib.request import urlopen
    if os.path.exists(path):
        return open('shakespeare.txt', encoding='ascii').read().split()
    else:
        shakespeare = urlopen(url)
        return shakespeare.read().decode(encoding='ascii').split()

# Uncomment the following two lines
# tokens = shakespeare_tokens()
# table = build_successors_table(tokens)

def random_sent():
    import random
    return construct_sent(random.choice(table['.']), table)


extra里面还有些不理解

评分

1

查看全部评分

回复 支持 反对

使用道具 举报

TammyChow 发表于 2015-5-23 16:39:14 | 显示全部楼层
楼主 求问reading链接没问题吗~~
一直都打不开好着急嗷嗷嗷嗷
回复 支持 反对

使用道具 举报

 楼主| sky420 发表于 2015-5-24 12:36:03 | 显示全部楼层
TammyChow 发表于 2015-5-23 16:39
楼主 求问reading链接没问题吗~~
一直都打不开好着急嗷嗷嗷嗷

似乎好多国内的同学都看不了,有另一本书,但是那本书是scheme,不是Python的,内容一样。你可以去cs61a.org看一下,其实光看lecture我觉得就够了
回复 支持 反对

使用道具 举报

karte_polo 发表于 2015-5-25 18:22:02 | 显示全部楼层
EXTRA里的来不及做了,就先交这些吧


## Trees, Dictionaries ##

#########
# Trees #
#########

import inspect
# Tree definition - same Data Abstraction but different implementation from lecture
def tree(root, branches=[]):
    #for branch in branches:
    # assert is_tree(branch)
    return lambda dispatch: root if dispatch == 'root' else list(branches)

def root(tree):
    return tree('root')

def branches(tree):
    return tree('branches')

def is_tree(tree):
    try:
        tree_data = inspect.getargspec(tree)
        assert tree_data == inspect.getargspec(lambda dispatch: None)
        return all([is_tree(branch) for branch in branches(tree)])
    except:
        return False

def is_leaf(tree):
    return not branches(tree)

def print_tree(t, indent=0):
    """Print a representation of this tree in which each node is
    indented by two spaces times its depth from the root.

    >>> print_tree(tree(1))
    1
    >>> print_tree(tree(1, [tree(2)]))
    1
      2
    >>> print_tree(numbers)
    1
      2
      3
        4
        5
      6
        7
    """
    print('  ' * indent + str(root(t)))
    for branch in branches(t):
        print_tree(branch, indent + 1)

numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])])


# Q1
def countdown_tree():
    """Return a tree that has the following structure.

    >>> print_tree(countdown_tree())
    10
      9
        8
      7
        6
          5
    """
    "*** YOUR CODE HERE ***"
    return tree(10,[tree(9,[tree(8)]),tree(7,[tree(6,[tree(5)])])])

# Q2
def size_of_tree(t):
    """Return the number of entries in the tree.

    >>> print_tree(numbers)
    1
      2
      3
        4
        5
      6
        7
    >>> size_of_tree(numbers)
    7
    """
    "*** YOUR CODE HERE ***"
    i = 1
    if not is_leaf(t):
        for branch in branches(t):
            i += size_of_tree(branch)
    return i
        

################
# Dictionaries #
################

# Q3
def counter(message):
    """ Returns a dictionary of each word in message mapped
    to the number of times it appears in the input string.

    >>> x = counter('to be or not to be')
    >>> x['to']
    2
    >>> x['be']
    2
    >>> x['not']
    1
    >>> y = counter('run forrest run')
    >>> y['run']
    2
    >>> y['forrest']
    1
    """
    word_list = message.split()
    "*** YOUR CODE HERE ***"
    l = {}
    for word in word_list:
        if word not in l:
            l[word]=1
        else:
            l[word]+=1
    return l
回复 支持 反对

使用道具 举报

wuxiaomin98 发表于 2015-6-3 05:46:41 | 显示全部楼层
# Q1
def countdown_tree():
    """Return a tree that has the following structure.

    >>> print_tree(countdown_tree())
    10
      9
        8
      7
        6
          5
    """
    "*** YOUR CODE HERE ***"
    return tree(10, [tree(9, [tree(8)]), tree(7, [tree(6, [tree(5)])])])

# Q2
def size_of_tree(t):
    """Return the number of entries in the tree.

    >>> print_tree(numbers)
    1
      2
      3
        4
        5
      6
        7
    >>> size_of_tree(numbers)
    7
    """
    "*** YOUR CODE HERE ***"
    return 1 + sum([size_of_tree(t) for t in branches(t)])

################
# Dictionaries #
################

# Q3
def counter(message):
    """ Returns a dictionary of each word in message mapped
    to the number of times it appears in the input string.

    >>> x = counter('to be or not to be')
    >>> x['to']
    2
    >>> x['be']
    2
    >>> x['not']
    1
    >>> y = counter('run forrest run')
    >>> y['run']
    2
    >>> y['forrest']
    1
    """
    word_list = message.split()
    "*** YOUR CODE HERE ***"
    dic = {}
    for word in word_list:
        if word in dic:
            dic[word] += 1
        else:
            dic[word] = 1
    return dic

from lab05 import *

## Extra Trees, Dictionaries Questions ##

#########
# Trees #
#########

# Q5
def height(t):
    """Return the depth of the deepest node in the tree.

    >>> height(tree(1))
    0
    >>> height(tree(1, [tree(2), tree(3)]))
    1
    >>> print_tree(numbers)
    1
      2
      3
        4
        5
      6
        7
    >>> height(numbers)
    2
    """
    "*** YOUR CODE HERE ***"
    if is_leaf(t):
        return 0
    return 1 + max([height(subtree) for subtree in branches(t)])

# Q6
def acorn_finder(t):
    """Returns True if t contains a node with the value 'acorn' and
    False otherwise.

    >>> sproul = tree('roots', [tree('branch1', [tree('leaf'), tree('acorn')]), tree('branch2')])
    >>> acorn_finder(sproul)
    True
    >>> acorn_finder(numbers)
    False
    """
    "*** YOUR CODE HERE ***"
    if root(t) == 'acorn':
        return True
    else:
        for branch in branches(t):
            if acorn_finder(branch) == True:
                return True
        return False


# Q7
def preorder(t):
    """Return a list of the entries in this tree in the order that they
    would be visited by a preorder traversal (see problem description).

    >>> preorder(numbers)
    [1, 2, 3, 4, 5, 6, 7]
    >>> preorder(tree(2, [tree(4, [tree(6)])]))
    [2, 4, 6]
    """
    "*** YOUR CODE HERE ***"
    if branches(t) == []:
        return [root(t)]
    orged_branches = []
    for branch in branches(t):
        orged_branches += preorder(branch)
    return [root(t)] + orged_branches

################
# Dictionaries #
################

# Q8
def build_successors_table(tokens):
    """Return a dictionary: keys are words; values are lists of
    successors.

    >>> text = ['We', 'came', 'to', 'investigate', ',', 'catch', 'bad', 'guys', 'and', 'to', 'eat', 'pie', '.']
    >>> table = build_successors_table(text)
    >>> sorted(table)
    [',', '.', 'We', 'and', 'bad', 'came', 'catch', 'eat', 'guys', 'investigate', 'pie', 'to']
    >>> table['to']
    ['investigate', 'eat']
    >>> table['pie']
    ['.']
    >>> table['.']
    ['We']
    """
    table = {}
    prev = '.'
    for word in tokens:
        if prev not in table:
            "*** YOUR CODE HERE ***"
            table[prev] = []
        "*** YOUR CODE HERE ***"
        table[prev].append(word)
        prev = word
    return table

# Q9
def construct_sent(word, table):
    """Prints a random sentence starting with word, sampling from
    table.
    """
    import random
    result = ' '
    while word not in ['.', '!', '?']:
        "*** YOUR CODE HERE ***"
        result += word + ''
        word = random.choice(table[word])
    return result + word
回复 支持 反对

使用道具 举报

reasonapp 发表于 2015-6-22 16:32:06 | 显示全部楼层
关于树的内容上次作业基本都做过,倒是list那题想了一会,代码:
## Trees, Dictionaries ##

#########
# Trees #
#########

import inspect
# Tree definition - same Data Abstraction but different implementation from lecture
def tree(root, branches=[]):
    #for branch in branches:
    # assert is_tree(branch)
    return lambda dispatch: root if dispatch == 'root' else list(branches)

def root(tree):
    return tree('root')

def branches(tree):
    return tree('branches')

def is_tree(tree):
    try:
        tree_data = inspect.getargspec(tree)
        assert tree_data == inspect.getargspec(lambda dispatch: None)
        return all([is_tree(branch) for branch in branches(tree)])
    except:
        return False

def is_leaf(tree):
    return not branches(tree)

def print_tree(t, indent=0):
    """Print a representation of this tree in which each node is
    indented by two spaces times its depth from the root.

    >>> print_tree(tree(1))
    1
    >>> print_tree(tree(1, [tree(2)]))
    1
      2
    >>> print_tree(numbers)
    1
      2
      3
        4
        5
      6
        7
    """
    print('  ' * indent + str(root(t)))
    for branch in branches(t):
        print_tree(branch, indent + 1)

numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])])


# Q1
def countdown_tree():
    """Return a tree that has the following structure.

    >>> print_tree(countdown_tree())
    10
      9
        8
      7
        6
          5
    """
    "*** YOUR CODE HERE ***"
    return tree(10, [tree(9,[tree(8)]),tree(7,[tree(6,[tree(5)])])])

# Q2
def size_of_tree(t):
    """Return the number of entries in the tree.

    >>> print_tree(numbers)
    1
      2
      3
        4
        5
      6
        7
    >>> size_of_tree(numbers)
    7
    """
    "*** YOUR CODE HERE ***"
    if is_leaf(t):
        return 1
    return 1 + sum(size_of_tree(subtree) for subtree in branches(t))

################
# Dictionaries #
################

# Q3
def counter(message):
    """ Returns a dictionary of each word in message mapped
    to the number of times it appears in the input string.

    >>> x = counter('to be or not to be')
    >>> x['to']
    2
    >>> x['be']
    2
    >>> x['not']
    1
    >>> y = counter('run forrest run')
    >>> y['run']
    2
    >>> y['forrest']
    1
    """
    word_list = message.split()
    "*** YOUR CODE HERE ***"
    dict = {}
    for word in word_list:
        if word in dict:
            dict[word] += 1
        else:
            dict[word] = 1
    return dict
   
   
回复 支持 反对

使用道具 举报

liyimeng 发表于 2016-2-7 09:34:31 | 显示全部楼层
因为赶进度,制作了必做的部分, extra没有写 lab05.png

代码:
  1. ## Trees, Dictionaries ##

  2. #########
  3. # Trees #
  4. #########

  5. import inspect
  6. # Tree definition - same Data Abstraction but different implementation from lecture
  7. def tree(root, branches=[]):
  8.     #for branch in branches:
  9.     # assert is_tree(branch)
  10.     return lambda dispatch: root if dispatch == 'root' else list(branches)

  11. def root(tree):
  12.     return tree('root')

  13. def branches(tree):
  14.     return tree('branches')

  15. def is_tree(tree):
  16.     try:
  17.         tree_data = inspect.getargspec(tree)
  18.         assert tree_data == inspect.getargspec(lambda dispatch: None)
  19.         return all([is_tree(branch) for branch in branches(tree)])
  20.     except:
  21.         return False

  22. def is_leaf(tree):
  23.     return not branches(tree)

  24. def print_tree(t, indent=0):
  25.     """Print a representation of this tree in which each node is
  26.     indented by two spaces times its depth from the root.

  27.     >>> print_tree(tree(1))
  28.     1
  29.     >>> print_tree(tree(1, [tree(2)]))
  30.     1
  31.       2
  32.     >>> print_tree(numbers)
  33.     1
  34.       2
  35.       3
  36.         4
  37.         5
  38.       6
  39.         7
  40.     """
  41.     print('  ' * indent + str(root(t)))
  42.     for branch in branches(t):
  43.         print_tree(branch, indent + 1)

  44. numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])])


  45. # Q1
  46. def countdown_tree():
  47.     """Return a tree that has the following structure.

  48.     >>> print_tree(countdown_tree())
  49.     10
  50.       9
  51.         8
  52.       7
  53.         6
  54.           5
  55.     """
  56.     "*** YOUR CODE HERE ***"
  57.     return tree(10, [tree(9, [tree(8)]), tree(7, [tree(6, [tree(5)])])])

  58. # Q2
  59. def size_of_tree(t):
  60.     """Return the number of entries in the tree.

  61.     >>> print_tree(numbers)
  62.     1
  63.       2
  64.       3
  65.         4
  66.         5
  67.       6
  68.         7
  69.     >>> size_of_tree(numbers)
  70.     7
  71.     """
  72.     "*** YOUR CODE HERE ***"
  73.     if is_leaf(t):
  74.         return 1
  75.     else:
  76.         return 1 + sum([size_of_tree(node) for node in branches(t)])

  77. ################
  78. # Dictionaries #
  79. ################

  80. # Q3
  81. def counter(message):
  82.     """ Returns a dictionary of each word in message mapped
  83.     to the number of times it appears in the input string.

  84.     >>> x = counter('to be or not to be')
  85.     >>> x['to']
  86.     2
  87.     >>> x['be']
  88.     2
  89.     >>> x['not']
  90.     1
  91.     >>> y = counter('run forrest run')
  92.     >>> y['run']
  93.     2
  94.     >>> y['forrest']
  95.     1
  96.     """
  97.     word_list = message.split()
  98.     "*** YOUR CODE HERE ***"
  99.     my_dict = dict()
  100.     for word in word_list:
  101.         if word in my_dict:
  102.             my_dict[word] += 1
  103.         else:
  104.             my_dict[word] = 1

  105.     return my_dict
复制代码
回复 支持 反对

使用道具 举报

Liaeve 发表于 2016-4-24 19:54:02 | 显示全部楼层
## Trees, Dictionaries ##

#########
# Trees #
#########

import inspect
# Tree definition - same Data Abstraction but different implementation from lecture
def tree(root, branches=[]):
    #for branch in branches:
    # assert is_tree(branch)
    return lambda dispatch: root if dispatch == 'root' else list(branches)

def root(tree):
    return tree('root')

def branches(tree):
    return tree('branches')

def is_tree(tree):
    try:
        tree_data = inspect.getargspec(tree)
        assert tree_data == inspect.getargspec(lambda dispatch: None)
        return all([is_tree(branch) for branch in branches(tree)])
    except:
        return False

def is_leaf(tree):
    return not branches(tree)

def print_tree(t, indent=0):
    """Print a representation of this tree in which each node is
    indented by two spaces times its depth from the root.

    >>> print_tree(tree(1))
    1
    >>> print_tree(tree(1, [tree(2)]))
    1
      2
    >>> print_tree(numbers)
    1
      2
      3
        4
        5
      6
        7
    """
    print('  ' * indent + str(root(t)))
    for branch in branches(t):
        print_tree(branch, indent + 1)

numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])])


# Q1
def countdown_tree():
    """Return a tree that has the following structure.

    >>> print_tree(countdown_tree())
    10
      9
        8
      7
        6
          5
    """
    "*** YOUR CODE HERE ***"
    return tree(10, [tree(9, [tree(8)]), tree(7, [tree(6, [tree(5)])])])

# Q2
def size_of_tree(t):
    """Return the number of entries in the tree.

    >>> print_tree(numbers)
    1
      2
      3
        4
        5
      6
        7
    >>> size_of_tree(numbers)
    7
    """
    "*** YOUR CODE HERE ***"
    entry_sum = 1
    for entry in branches(t):
        entry_sum += size_of_tree(entry)
    return entry_sum

################
# Dictionaries #
################

# Q3
def counter(message):
    """ Returns a dictionary of each word in message mapped
    to the number of times it appears in the input string.

    >>> x = counter('to be or not to be')
    >>> x['to']
    2
    >>> x['be']
    2
    >>> x['not']
    1
    >>> y = counter('run forrest run')
    >>> y['run']
    2
    >>> y['forrest']
    1
    """
    word_list = message.split()
    "*** YOUR CODE HERE ***"
    result = {}
    for word in word_list:
        if word in result:
            result[word] += 1
        else:
            result[word] = 1
    return result
from lab05 import *

## Extra Trees, Dictionaries Questions ##

#########
# Trees #
#########

# Q5
def height(t):
    """Return the depth of the deepest node in the tree.

    >>> height(tree(1))
    0
    >>> height(tree(1, [tree(2), tree(3)]))
    1
    >>> print_tree(numbers)
    1
      2
      3
        4
        5
      6
        7
    >>> height(numbers)
    2
    """
    "*** YOUR CODE HERE ***"
    if is_leaf(t):
        return 0
    depth = 0
    for branch in branches(t):
        depth = max(depth, height(branch))
    return depth + 1

# Q6
def acorn_finder(t):
    """Returns True if t contains a node with the value 'acorn' and
    False otherwise.

    >>> sproul = tree('roots', [tree('branch1', [tree('leaf'), tree('acorn')]), tree('branch2')])
    >>> acorn_finder(sproul)
    True
    >>> acorn_finder(numbers)
    False
    """
    "*** YOUR CODE HERE ***"
    if root(t) == 'acorn':
        return True
    for branch in branches(t):
        if acorn_finder(branch) == True:
            return True
    return False



# Q7
def preorder(t):
    """Return a list of the entries in this tree in the order that they
    would be visited by a preorder traversal (see problem description).

    >>> preorder(numbers)
    [1, 2, 3, 4, 5, 6, 7]
    >>> preorder(tree(2, [tree(4, [tree(6)])]))
    [2, 4, 6]
    """
    "*** YOUR CODE HERE ***"
    if branches(t) == []:
        return [root(t)]
    print_order = []
    for branch in branches(t):
        print_order += preorder(branch)
    return [root(t)] + print_order



################
# Dictionaries #
################

# Q8
def build_successors_table(tokens):
    """Return a dictionary: keys are words; values are lists of
    successors.

    >>> text = ['We', 'came', 'to', 'investigate', ',', 'catch', 'bad', 'guys', 'and', 'to', 'eat', 'pie', '.']
    >>> table = build_successors_table(text)
    >>> sorted(table)
    [',', '.', 'We', 'and', 'bad', 'came', 'catch', 'eat', 'guys', 'investigate', 'pie', 'to']
    >>> table['to']
    ['investigate', 'eat']
    >>> table['pie']
    ['.']
    >>> table['.']
    ['We']
    """
    table = {}
    prev = '.'
    for word in tokens:
        if prev not in table:
            "*** YOUR CODE HERE ***"
            table[prev] = []
        "*** YOUR CODE HERE ***"
        table[prev].append(word)
        prev = word
    return table

# Q9
def construct_sent(word, table):
    """Prints a random sentence starting with word, sampling from
    table.
    """
    import random
    result = ' '
    while word not in ['.', '!', '?']:
        "*** YOUR CODE HERE ***"
        result += word + ' '
        word = randon.choice(table[word])
    return result + word

# Warning: do NOT try to print the return result of this function
def shakespeare_tokens(path='shakespeare.txt', url='http://goo.gl/SztLfX'):
    """Return the words of Shakespeare's plays as a list."""
    import os
    from urllib.request import urlopen
    if os.path.exists(path):
        return open('shakespeare.txt', encoding='ascii').read().split()
    else:
        shakespeare = urlopen(url)
        return shakespeare.read().decode(encoding='ascii').split()

# Uncomment the following two lines
# tokens = shakespeare_tokens()
# table = build_successors_table(tokens)

def random_sent():
    import random
    return construct_sent(random.choice(table['.']), table)
回复 支持 反对

使用道具 举报

本版积分规则

请点这里访问我们的新网站:一亩三分地Instant.

Instant搜索更强大,不扣积分,内容组织的更好更整洁!目前仍在beta版本,努力完善中!反馈请点这里

关闭

一亩三分地推荐上一条 /5 下一条

手机版|小黑屋|一亩三分地论坛声明 ( 沪ICP备11015994号 )

custom counter

GMT+8, 2016-12-9 10:23

Powered by Discuz! X3

© 2001-2013 Comsenz Inc. Design By HUXTeam

快速回复 返回顶部 返回列表