[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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM