Quiz 02 Memory Diagram Practice Problems

Lists

  1. Create a memory diagram for the following code listing.
1     """Practice diagram."""
2
3     def check_quiz(responses: list[bool]) -> int:
4         answer_key: list[bool] = [True, True, False]
5         correct: int = 0
6         idx: int = 0
7         while idx < len(responses):
8             if responses[idx] == answer_key[idx]:
9                 correct += 1
10                idx += 1
11            else:
12                idx += 1
13        return correct
14
15    def main() -> None:
16        my_quiz: list[bool] = [True, True, True]
17        grade: int = check_quiz(my_quiz)
18        print(f"{grade} out of 3 questions correct.")
19
20
21    main()
  1. Create a memory diagram for the following code listing.
1     """Practice diagram."""
2
3     def create() -> list[int]:
4         """An obnoxious way to make a list."""
5         list_1: list[int] = []
6         i: int = 0
7         while i < 3:
8             list_1.append(i)
9             i += 1
10        return list_1
11
12
13    def increase(a_list: list[int], x: int) -> None:
14        """Lets pump it up!"""
15        i: int = 0
16        while i < len(a_list):
17            a_list[i] += x
18            i += 1
19        return None
20
21
22    def main() -> None:
23        """Entrypoint of the program."""
24        list_1: list[int] = create()
25        list_2: list[int] = list_1
26        list_1 = create()
27        increase(list_1, 2)
28        print(list_1)
29        print(list_2)
30
31
32    main()
  1. Create a memory diagram for the following code listing.
1     """Practice diagram."""
2 
3     def f(x: list[str]) -> str:
4         for y in range(0,len(x)):
5             x[y] += "x"
6         return x[y]
7 
8     def g(x: list[str]) -> list[str]:
9         new_list: list[str] = []
10        for z in x:
11            new_list.append(str(z))
12        return new_list
13
14    record: list[str] = ["x", "y"]
15    print(f(record))
16    print(g(record))
  1. Create a memory diagram for the following code listing.
1     """Practice diagram."""
2 
3     def change_and_check(x: int, nums: list[int]) -> int:
4         """Let's see what happens!"""
5         if x < 0:
6             return 0
7         i: int = 0
8         while i < len(nums):
9             nums[i] += x
10            i += 1
11        i = 0
12        while i < len(nums):
13            if nums[i] == x:
14                return 0
15            i += 1
16        return x - 1
17
18
19    def main() -> None:
20        """The entrypoint of this program."""
21        num_1: int = 0
22        list_1: list[int] = [1, 2, num_1]
23        list_1.append(change_and_check(2, list_1))
24        list_1.append(change_and_check(3, list_1))
25
26    main()
  1. Create a memory diagram for the following code listing.
1     """Practice diagram."""
2
3     def apply_discounts(order_amounts: list[float]) -> list[float]:
4         index: int = 0
5         counter: int = 0
6         discounted_amounts: list[float] = []
7 
8         while index < len(order_amounts):
9             amount: float = order_amounts[index]
10
11            if amount > 50:
12                discount = 0.10
13            else:
14                discount = 0
15
16            discounted_amount = amount * (1 - discount)
17            discounted_amounts.append(discounted_amount)
18
19            counter += 1
20            index += 1
21
22        print(f"Total orders processed: {counter}")
23        return discounted_amounts
24
25    def main() -> None:
26        order_amounts: list[float] = [45.0, 75.0, 150.0, 30.0]
27        discounted_amounts: list[float] = apply_discounts(order_amounts)
28        print(discounted_amounts)
29
30    if __name__ == "__main__":
31        main()

SHOW SOLUTIONS

  1. Video

    Image Description

    The Memory Diagram includes one box titled Output and below that box two columns, the left one titled Stack and the right one titled Heap.

    The Stack includes 3 frames in the following order from top to bottom including Globals, main, and check_quiz.

    The Globals frame has 2 variables including check_quiz and main.

    • check_quiz has id 0, it is a function on the Heap (lines 1-11).
    • main points id 1, it is a function on the Heap (lines 14-17).

    The main frame has 4 items including the RA and RV, and variables named my_quiz and grade.

    • The RA is defined at line 19.
    • The RV is None.
    • my_quiz has id 2, it is a list[bool] on the Heap.
      • Indexes 0, 1, 2 and values True, True, True respectively.
    • grade is 2.

    The check_quiz frame has 6 items including the RA and RV, and variables named responses, answer_key, correct, and idx.

    • The RA is defined at line 15.
    • The RV is 2.
    • responses has id 2.
    • answer_key has id 3, it is a list[bool] on the Heap.
      • Indexes 0, 1, 2 and values True, True, False respectively.
    • correct is 2.
      • Previous values of correct include 0 and 1, which are now crossed out.
    • idx is 3.
      • Previous values of idx include 0, 1, and 2, which are now crossed out.

    The Heap includes 2 function objects, and 2 list[bool] objects.

    Output includes the phrase: “2 out of 3 questions correct.”

  2. Video

  3. Image Descriptions: Under Globals:

    • Variable f has id 0, it is a function labeled Fn [1-4] on the Heap.
    • Variable g id 1, it is a function labeled Fn [1-6] on the Heap.
    • Variable record id 2, it is a list object on the Heap with the type list[str].

    The f function frame has:

    • Return Address (RA) pointing to line 13.
    • Variables x and y, where x has id 2, and y with a value of 1 and a crossed-out value of 0.
    • Return Value (RV) with a value of “yx”.

    The g function frame has:

    • Return Address (RA) pointing to line 14.
    • Variables x has id 2, new_list has id 3 which is list object on the Heap with type list[str].
    • Variable z has the crossed-out string “xx”, with a final value of “yx”.
    • Return Value (RV) has id 3.

    The Heap section shows two list objects and two string objects:

    • The first list on the heap has two values. The first value is “xx” with a crossed-out value of “x”. The second value is “yx” with a crossed-out value of “y”.
    • The second list on the heap has two values. The first value is “xx” and the second value is “yx”.

    The Output section at the top first prints “yx”, then the list [“xx”,”yx”].

  4. Image Description Here

  5. Image Description Here

Dictionaries

  1. Create a memory diagram for the following code listing.
1     """Practice diagram."""
2 
3     def count(xs: list[int]) -> dict[int, int]:
4         counts: dict[int, int] = {}
5         for x in xs:
6             if x in counts:
7                 counts[x] += 1
8             else:
9                 counts[x] = 1
10        return counts
11
12
13    numbers: list[int] = [1, 1, 0]
14    print(count(numbers))
  1. Create a memory diagram for the following code listing.
1     """Practice diagram."""
2 
3     def artist_counts(playlist: dict[str, str]) -> dict[str, int]:
4         artists: dict[str, int] = dict()
5         for track in playlist:
6             art: str = playlist[track]
7             if playlist[track] not in artists:
8                 artists[art] = 1
9             else:
10                artists[art] += 1
11        return artists
12
13    songs: dict[str, str] = {
14        "B2b": "Charli",
15        "Hello": "Erykah",
16        "Fiat": "Butcher",
17        "Woo": "Erykah"
18    }
19
20    print(artist_counts(songs))
  1. Create a memory diagram for the following code listing.
1     """Practice diagram."""
2
3     def f(x: dict[str,int]) -> int:
4         for y in x:
5             x[y] += 1
6         return x[y]
7 
8     def g(x: dict[str,int]) -> dict[str,str]:
9         new_dict: dict[str,str] = {}
10        for z in x:
11            new_dict[z] = str(z)
12        return new_dict
13
14    record: dict[str, int] = {"x": 20, "y": 40}
15    print(f(record))
16    print(g(record))
  1. Create a memory diagram for the following code listing.
1     """Practice diagram."""
2
3     def mystery(x: dict[str,float], y: str) -> str:
4         if y in x:
5             return str(x[y])
6         else:
7             return "not in dictionary"
8
9     x = "y"
10    y = "z"
11    test: dict[str,float] = {"z": 3.14}
12    print(mystery(test, y))
  1. Create a memory diagram for the following code listing.
1     """Practice diagram."""
2
3     starting = dict[str, list[str]] = {}
4     starting["2017"] = ["Berry", "Meeks", "Jackson"]
5     starting["2023"] = ["Love", "Bacot", "Black"]
6
7     print(starting["2017"][2])
8     print(starting["2023"])
9     starting["2023"][2] = "Johnson"
10    print(starting["2023"])
  1. Create a memory diagram for the following code listing.
1     """Practice diagram."""
2 
3     def add_item(inventory, item, quantity) -> None:
4         item_found = False
5         for key in inventory:
6             if key == item:
7                 inventory[key] += quantity
8                 item_found = True
9 
10        if not item_found:
11            inventory[item] = quantity
12
13    def remove_item(inventory, item, quantity) -> None:
14        item_found = False
15        for key in inventory:
16            if key == item:
17                inventory[key] -= quantity
18                if inventory[key] < 0:
19                    inventory[key] = 0
20                item_found = True
21
22    def main():
23        inventory = {
24            'Apples': 30,
25            'Oranges': 15,
26            'Bananas': 20
27        }
28
29        add_item(inventory, 'Apples', 10)
30        remove_item(inventory, 'Bananas', 25)
31
32        print("Current inventory:", inventory)
33
34    if __name__ == "__main__":
35        main()

SHOW SOLUTIONS

  1. Memory diagram of code listing with count function

  2. Memory diagram of code listing with artist_counts function

  3. Video

    Image Description: The memory diagram is divided into three segments: Output, Stack, and Heap.

    Under the stack, the Globals frame contains references to three objects:

    • Function f points to a function on the Heap defined from lines 1 to 4.
    • Function g points to a function on the Heap defined from lines 6 to 10.
    • The variable record points to a dictionary object on the Heap with string keys and integer values.

    The F frame has:

    • Return Address (RA) at line 13.
    • Return Value (RV) is the integer 41.
    • Variable x points to a the same dictionary object on the heap as record.
    • Variable y with a crossed-out value of “x” and updated to “y”.

    The G frame has:

    • Return Address (RA) at line 14.
    • Variable x points to the same dictionary object as record.
    • Variable new_dict to a second dictionary object on the Heap.
    • Variable z with a crossed-out value of “x” updated to “y”.

    The heap has two dictionary objects:

    • The first dictionary object is associated with the variable record in Globals frame and the variable x in the F and G frames. It contains two string keys, ‘x’ with the integer value 20 crossed out and updated to 21, and ‘y’ with the integer value 40 crossed out and updated to 41.
    • The second dictionary object is associated with the variable new_dict in the G frame, with string keys ‘x’ and ‘y’ and string values ‘x’ and ‘y’ respectively.

    Output: The output displays the integer 41 and a dictionary object with keys ‘x’ and ‘y’, each paired with their respective values ‘x’ and ‘y’ as strings.

  4. Video

    Image Description: The memory diagram provided displays elements in the Output, Stack, and Heap sections.

    Stack:

    The Globals frame contains three variables and a function:

    • Function mystery points to a function definition on the Heap spanning lines 1 to 5.
    • Variable x with the string value “y”.
    • Variable y with the string value “z”.
    • Variable test points to a dictionary on the Heap.

    The mystery frame has:

    • Return Address (RA) at line 10.
    • Return Value (RV) is the string “3.14”.
    • Variable x points to the same dictionary object as test
    • Variable y has a value of “z”.

    Heap:

    • A dictionary object with string keys and a floating-point value is present. It contains a single entry where the key is the string “z” and the value is the floating-point number 3.14.

    Output: The output section shows the floating-point number 3.14.

  5. Video

Image Description Here

Image Description: The memory diagram provided contains three main components: Stack, Heap, and Output.

Stack: * The Stack section contains a single frame labeled “Globals.” * Inside Globals, there is a variable named starting pointing to a list on the Heap.

Heap: * The first part is a dictionary object with string keys and lists of strings for values. There are two keys: “2017” and “2023.” Each key points to a different list. * The second part consists of two lists of strings. Each list contains five elements with indices from 0 to 4. * The first list contains the following strings: “Berry”, “Meeks”, “Jackson”, “Pinson”, and “Hicks”. * The second list contains the strings: “Love”, “Bacot”, “Black”, “Johnson” (with “Nance” crossed-out), and “Davis”.

The output section has three outputs: * The string “Jackson” * The list [“Love”, “Bacot”, “Black”, “Nance”, “Davis”] * The list [“Love”, “Bacot”, “Black”, “Johnson”, “Davis”]

  1. Image Description Here
Contributor(s): Alyssa Lytle, Kris Jordan, Navya Katraju, Olivia Xiao, Viktorya Hunanyan, Coralee Rogers, Benjamin Eldridge