# Author:
# Date: 11/21/25
# CSCI 141 Exam 3, Fall 2025

""" There are three functions to implement for this exam:
1. file_reverse (8 points)
2. pair_up (8 points)
3. brackets_match (4 points)
"""

def file_reverse(in_filename, out_filename):
    """ Given an input filename, read the file and save its contents to a file
    with the given output filename, but with its lines reversed (i.e., the first
    line of the input file appears as the last line in the output file).
    Precondition: in_filename exists.
    
    Examples:
    If input.txt contains:
    line 1
    line 2
    line 3
    
    Then file_reverse('input.txt', 'output.txt') creates output.txt with:
    line 3
    line 2
    line 1
    """
    fin = open(in_filename, 'r')
    fout = open(out_filename, 'w')
    
    lines = fin.readlines()
#     for i in range(len(lines)-1, -1, -1):
#         fout.write(lines[i])

    for line in lines[::-1]:
        fout.write(line)
    
    fin.close()
    fout.close()
    

def pair_up(lst):
    """ Given a list of items, return a list of 2-tuples, each containing two
    consecutive items from the input list. If the input list has odd length,
    the final tuple should have only one value in it.
    
    Hint: you can create a length-1 tuple like this: (1,)
    You can't just write (1) - this will just evaluate to 1
        
    Examples:
    >>> pair_up([1, 2, 3, 4, 5])
    [(1, 2), (3, 4), (5,)]
    >>> pair_up([1, 2, 3, 4])
    [(1, 2), (3, 4)]
    >>> pair_up([1])
    [(1,)]
    >>> pair_up([])
    []
    >>> pair_up(['a', 'b', 'c'])
    [('a', 'b'), ('c',)]
    """


def brackets_match(s):
    """ Determine whether a string contains correctly matched square brackets.
    That is, each opening bracket has exactly one corresponding closing bracket
    that appears after it. Non-bracket characters are ignored.
    
    Examples:
    >>> brackets_match("[]")
    True
    >>> brackets_match("[[]]")
    True
    >>> brackets_match("[[]")
    False
    >>> brackets_match("[]]")
    False
    >>> brackets_match("abc[def]ghi")
    True
    >>> brackets_match("a[b[c]d]e")
    True
    >>> brackets_match("][")
    False
    >>> brackets_match("")
    True
    """
    
    nesting_level = 0
    for char in s:
        if char == "[":
            nesting_level += 1
        elif char == "]":
            nesting_level -= 1
            if nesting_level < 0:
                return False
    
    return nesting_level == 0
