中级农民
- 积分
- 153
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-7-9
- 最后登录
- 1970-1-1
|
## 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)
|
|