1. 程式人生 > 其它 >2021 fall cs61lab11

2021 fall cs61lab11

網址 https://inst.eecs.berkeley.edu/~cs61a/fa21/lab/lab11/#problem-3
problem1:

    class Buffer:
        """A Buffer provides a way of accessing a sequence of tokens across lines.

        Its constructor takes an iterator, called "the source", that returns the
        next line of tokens as a list each time it is queried, or None to indicate
        the end of data.

        The Buffer in effect concatenates the sequences returned from its source
        and then supplies the items from them one at a time through its pop_first()
        method, calling the source for more sequences of items only when needed.

        In addition, Buffer provides a current method to look at the
        next item to be supplied, without sequencing past it.

        The __str__ method prints all tokens read so far, up to the end of the
        current line, and marks the current token with >>.

        >>> buf = Buffer(iter([['(', '+'], [15], [12, ')']]))
        >>> buf.pop_first()
        '('
        >>> buf.pop_first()
        '+'
        >>> buf.current()
        15
        >>> buf.current()   # Calling current twice should not change buf
        15
        >>> buf.pop_first()
        15
        >>> buf.current()
        12
        >>> buf.pop_first()
        12
        >>> buf.pop_first()
        ')'
        >>> buf.pop_first()  # returns None
        """

        def __init__(self, source):
            self.index = 0
            self.source = source#source是每一次next是一個列表
            self.current_line = ()
            self.current()

        def pop_first(self):
            """Remove the next item from self and return it. If self has
            exhausted its source, returns None."""
            # BEGIN PROBLEM 1
            "*** YOUR CODE HERE ***"
            current = self.current()
            self.index += 1#只有每次pop_first才會改變index也就是改變current()
            return current
            # END PROBLEM 1

        def current(self):
            """Return the current element, or None if none exists."""
            while not self.more_on_line():#當more_on_line()函式False時超過了當前索引,就需要進入下一個列表
                self.index = 0
                try:
                    # BEGIN PROBLEM 1
                    "*** YOUR CODE HERE ***"
                    self.current_line = next(self.source)#進入下一個列表
                    # END PROBLEM 1
                except StopIteration:
                    self.current_line = ()
                    return None
            return self.current_line[self.index]

        def more_on_line(self):
            return self.index < len(self.current_line)

problem 2 and 3:
這兩道題目就是要對給定的src進行解釋,兩個函式相互遞迴,有一些規則
scheme_read遇到左括號就呼叫read_line函式來生成Pair,遇到'就是引用即解釋為quote,
read_line函式就是如果遇到右括號就結束,如果是其他的數字或者字母,布林值就正常儲存,在呼叫scheme_read函式進入遞迴

    def scheme_read(src):
        """Read the next expression from SRC, a Buffer of tokens.
        """
        if src.current() is None:
            raise EOFError
        val = src.pop_first()  # Get and remove the first token
        if val == 'nil':
            return nil
        elif val == '(':
            return read_tail(src)
        elif val == "'":
            return Pair('quote', Pair(scheme_read(src), nil))
        elif val not in DELIMITERS:
            return val
        else:
            raise SyntaxError('unexpected token: {0}'.format(val))


    def read_tail(src):
        """Return the remainder of a list in SRC, starting before an element or ).
        """
        try:
            if src.current() is None:
                raise SyntaxError('unexpected end of file')
            elif src.current() == ')':
                src.pop_first()
                return nil
            else:
                return Pair(scheme_read(src), read_tail(src))
        except EOFError:
            raise SyntaxError('unexpected end of file')