[2021 spring] CS61A Lab 7: Object-Oriented Programming, Linked Lists, Mutable Trees

Lab07: https://inst.eecs.berkeley.edu/~cs61a/sp21/lab/lab07/#topics

Q2: Making Cards

class Card:
    cardtype = 'Staff'

    def __init__(self, name, attack, defense):
        "*** YOUR CODE HERE ***"
        self.name = name
        self.attack = attack
        self.defense = defense

    def power(self, opponent_card):
        "*** YOUR CODE HERE ***"
        return self.attack - opponent_card.defense / 2

Q3: Making a Player

class Player:
    def __init__(self, deck, name):
        self.deck = deck
        self.name = name
        "*** YOUR CODE HERE ***"
        self.hand = list()
        for _ in range(5):
            self.hand.append(self.deck.draw())

    def draw(self):
        assert not self.deck.is_empty(), 'Deck is empty!'
        "*** YOUR CODE HERE ***"
        self.hand.append(self.deck.draw())

    def play(self, card_index):
        "*** YOUR CODE HERE ***"
        return self.hand.pop(card_index)

将链表结构转换为python列表,只需要将link.first依次添加到待返回的链表中。
代码:

def convert_link(link):
    """Takes a linked list and returns a Python list with the same elements.

    >>> link = Link(1, Link(2, Link(3, Link(4))))
    >>> convert_link(link)
    [1, 2, 3, 4]
    >>> convert_link(Link.empty)
    []
    """
    "*** YOUR CODE HERE ***"
    linkList = list()
    while link:
        linkList.append(link.first)
        link = link.rest
    return linkList

Q6: Cumulative Mul (Trees)

将每个节点的值变为该子树的所有节点值的乘积(累乘)。
分析:当前节点为叶节点时,不需要更改t.label;当前节点不为节点时,t.label需要乘上子节点的值b.label,在这之前对b进行cumulative mul。
代码:

def cumulative_mul(t):
    """Mutates t so that each node's label becomes the product of all labels in
    the corresponding subtree rooted at t.

    >>> t = Tree(1, [Tree(3, [Tree(5)]), Tree(7)])
    >>> cumulative_mul(t)
    >>> t
    Tree(105, [Tree(15, [Tree(5)]), Tree(7)])
    """
    "*** YOUR CODE HERE ***"
    if not t.is_leaf():
        for b in t.branches:
            cumulative_mul(b)
            t.label *= b.label
posted @ 2021-07-13 21:32  ikventure  阅读(3437)  评论(0编辑  收藏  举报