Quiz 02 Practice


Questions

The quiz itself will be similar in difficulty to this practice worksheet.

Solutions for each problem can be found at the bottom of this page.

Conceptual Questions

  1. Global variables are limited to the scope of the function they are declared in. (T/F)
  2. Variables can have the same name but store different values if they are defined in a different scope. (T/F)
  3. Named constants should be used to store values that may change throughout the program. (T/F)
  4. When using a for...in loop, on the first line of the loop you must specify the type of the variable (variable refers to i in for i in nums). (T/F)
  5. In Python dictionaries, each dictionary’s value type must match its key type. (T/F)
  6. Writing a for...in loop on a dict loops through the keys of a dictionary. (T/F)
  7. The values in a dictionary cannot be changed once they are assigned. (T/F)
  8. Explain the similarities and differences between Python’s list and dict.

Memory Diagrams

  1. Produce a memory diagram for the following code snippet, being sure to include its stack, heap, and output.
    def main() -> None:
        """Entry point of program."""
        strings: list[str] = ["hey", "o", "eh", "e"]
        word: str = make_word(strings)
        print(word)


    def make_word(root: list[str]) -> str:
        """A nonsensical function that makes a 'word'."""
        word: str = ""
        i: int = 0
        while i < len(root):
            if i % 2 == 0:
                word += root[i]
            else:
                if len(word) < 5:
                    word += root[i]
                else:
                    return word
            i += 1
        return word


    if __name__ == "__main__":
        main()
  1. Produce a memory diagram for the following code snippet, being sure to include its stack, heap, and output.
    """References Practice."""


    def create() -> list[int]:
        """An obnoxious way to make a list."""
        list_1: list[int] = []
        i: int = 0
        while i < 3:
            list_1.append(i)
            i += 1
        return list_1


    def increase (a_list: list[int], x: int) -> None:
        """Lets pump it up!"""
        i: int = 0
        while i < len(a_list):
            a_list[i] += x
            i += 1
        return None


    def main() -> None:
        """Entrypoint of the program."""
        list_1: list[int] = create()
        list_2: list[int] = list_1
        list_1 = create()
        increase(list_1, 2)

        print(list_1)
        print(list_2)


    if __name__ == "__main__":
        main()
  1. Given the following code snippet, answer the questions below.
    def change_and_check(x: int, nums: list[int]) -> int:
        """Let's see what happens!"""
        if x < 0:
            return 0
        
        i: int = 0
        while i < len(nums):
            nums[i] += x
            i += 1

        i = 0
        while i < len(nums):
            if nums[i] == x:
                return 0
            i += 1

        return x - 1


    def main() -> None:
        """The entrypoint of this program."""
        num_1: int = 0
        list_1: list[int] = [1, 2, num_1]
        list_1.append(change_and_check(2, list_1))
        list_1.append(change_and_check(3, list_1))


    main()

4.1. What is the value of list_1 once the code snippet completes?
4.2. What is the value of i on line 10 during the last call to change_and_check?
4.3. How many total frames are created on the stack throughout the run of this program (including the globals frame)?

Function Writing

  1. Odd and Even: instructions
  2. Value Exists: instructions
  3. Short Words: instructions

Autograder instructions:

Join the Gradescope class for practice problems with the code: 4V7PB5 (Do this by going to your Gradescope homepage and clicking on “Enroll in Course”) Do not compress these files before submitting. Simply submit the .py files.

More Practice

For more practice, make sure to check out our page of practice memory diagrams. For QZ02, we especially recommend doing the following diagrams:

Solutions

Conceptual Questions

  1. False
  2. True
  3. False
  4. False
  5. False
  6. True
  7. False
  8. Similarities:
    Both are collections that can be looped through using a for...in loop, reference types that live on the heap, mutable, can duplicate values, subscription notation to access values, .pop() to remove items
    Differences:
    list – Index by increasing integers, add items with .append(), ordered, for...in loop gives items
    dict – Matched Key-Value pairs, pair with assignment operator = (dict_name[key] = value), control over key type (not limited to int), for...in gives keys
    Note: these are not all of the similarities and differences, just some important ones to remember

Memory Diagrams

  1. The memory diagram includes a column labeled Stack, a column labeled Heap, and a column labeled Output. The stack has 3 frames in the following order from top to bottom: globals, main, and make underscore word. 
In the Globals frame there are 2 items. First is the label `main` pointing to a function on the heap from lines 1-5. The label make underscore word points to a function on the heap from lines 8-21. 
The main frame has 4 items, RA, RV, strings, and word. The return address is 25 and the return value is None. The variable `strings` pointing to a list in the Heap. The list is labeled list bracket str close bracket and has 4 rows and 2 columns. The first column has the indices 0, 1, 2, and 3 and the second column has the values 'hey', 'o', 'eh', and 'e'. Finally, the `main` stack frame has the variable `word` with the value of quote H E Y O E H end quote. 
The make underscore word frame has 5 items, RA, RV, root, word, and i. Make underscore word has a return address of 4 and a return value of quote H E Y O E H end quote. It has the variable `root` pointing to the same list in the heap as the variable strings. There is another variable `word` with the value of quote H E Y O E H end quote and a variable i with the value of 3. Finally, in the output column is the string H E Y O E H.

  2. The memory diagram has three columns labeled stack, heap and output. The stack has 5 frames labeled from top to bottom, in the following order: globals, main, create, create, and increase. 
The globals frame has three labels: create, increase, and main. Create is pointing to a function on the heap from lines 4-11, increase points to a function on the heap from lines 14-20, and main points to a function on the heap from lines 23-31. 
The main frame has 4 items, including the RA, RV, and two variables list underscore 1 and list underscore 2. The return address is 31 and the return value is None. list underscore 2 points to a list on the heap labeled list open bracket int close bracket with 3 rows and two columns. At index 0 is the value 0, at index 1 is the value 1 and at index 2 is the value 2. list underscore 1 points to a list on the heap. The list is labeled list open bracket int close bracket and has two columns and three rows below that. The first row has the index 0 on the left and the previous value of 0 crossed out and a final value of 2. Index 1 has the previous value of 1 crossed out and a final value of 3. Index 2 has the previous value of 2 crossed out and the final value of 4.
The first create frame has four items, RA, RV, list underscore 1, and i. The return address is 25 and the return value points to the same list in the heap that the variable list underscore 2 in the previous main frame pointed to. In the create frame, the variable list underscore 1 points to that same list in the heap. The variable i has the previous values of 0, 1, and 2 crossed out and the final value of 3. 
The second create frame also has four items, RA, RV, list underscore 1 and i. The return address is 27 and the return value is the same list in the heap that the variable list underscore 1 in main pointed to. Within the create frame, list underscore 1 points to that same list in the heap. The variable i has the previous values of 0, 1, and 2 crossed out and the final value of 3.
The final frame of increase has 5 items, RA, RV, a underscore list, x, and i. The return address is 28 and the return value is None. a_underscore list points to the same list pointed to by list underscore 1 in main and list underscore 1 in the second create frame. The variable x has the value of 2 and the variable i has the previous values of 0, 1, and 2 crossed out and the final value of 3.

3.1. [6, 7, 5, 3, 0]
3.2. 4
3.3. 4

Function Writing

Note: Your solution does not need to be identical to these, these are just examples of one of many possible solutions.

    def odd_and_even(list1: list[int]) -> list[int]:
        """Find the odd elements with even indexes."""
        i: int = 0
        list2: list[int] = []

        while i < len(list1):
            if list1[i] % 2 == 1 and i % 2 == 0:
                list2.append(list1[i])
            i += 1

        return list2
    def value_exists(inp_dict: dict[str,int], val: int) -> bool:
        """Return true if val is in inp_dict"""
        exists: bool = False
        for elem in inp_dict:
            if inp_dict[elem] == val:
                exists = True
        return exists
    def short_words(inp_list: list[str]) -> list[str]:
        """Filter out the shorter words"""
        ret_list = []
        for x in inp_list:
            if len(x) < 5:
                ret_list.append(x)
            else:
                print(f"{x} is too long!")
        return ret_list
Contributor(s): Megan Zhang, David Karash, Coralee Vickers, Alyssa Byrnes, Carolyn Pierce