Quiz 01 Practice Problems

Quiz 01 Practice

Boolean Expressions

  1. What are the results of the following boolean expressions?

    1.1 ((not False) and True) == True

    1.2 (not False) or (True and False)

    1.3 True and (7 < 3 * 4 / 6)

    1.4 (not False) != True

    1.5 not (True and False) and (False or not False)

    1.6. "XYz" == "XYZ" or "B" == "C"

    1.7. 5 ** 2 >= 5 * 5 and 110 % 10 == 0

SHOW SOLUTIONS

1.1. True

1.2. True

1.3. False

1.4. False

1.5. True

1.6. False

1.7. True

 

Conditionals

True/False

  1. Every if statement must be followed by a paired else branch. (T/F)

  2. Lines contained in an else branch in Python do not have to be indented. (T/F)

  3. You can name a variable else in your program without Python confusing your variable’s name and the else keyword. (If you are unsure, this is a good one to try yourself!) (T/F)

SHOW SOLUTIONS

  1. False

  2. False

  3. False

 

Conceptual

  1. What does the condition of a conditional have to evaluate to in order to enter its then block?

  2. What does the condition of a conditional have to evaluate to in order to enter its else block?

  3. What happens when a return statement is encountered?

SHOW SOLUTIONS

  1. The condition must evaluate to True.

  2. The condition must evaluate to False.

  3. The return value is recorded in memory and the function is immediately exited.

 

Code Snippet

1    def main() -> None: 
2       x: str = "x"
3       y: str = "y"
4       z: str = x
5       y = x
6       x = "y"
7
8       if not(x != y and x != "y"):
9           print(f"x: {x}")
10      else:
11          print("'if' condition not met.")
12 
13   main()
  1. What is the condition in this code?

  2. What does the condition evaluate to? (Don’t do it in your head, draw a memory diagram!)

  3. What values should x, y, and/or z have to be assigned to in order for the else block to run?

  4. What other values can x, y, and/or z be assigned in order for the if block to run?

SHOW SOLUTIONS

  1. not(x != y and x != "y")

  2. The condition evaluates to True.

  3. To ensure the else block runs in the given code, the condition x != y and x != "y" must be true. This means x should be different from y and x should also be different from the string "y". For example, setting x = "a" and y = "b" will satisfy this condition, making the else block execute.

  4. To make the if block run, the condition not(x != y and x != "y") must be true, which happens when x is either the same as y or the same as "y", or both. In the original code where x = "y", y = "x", and z = "x", the if block runs as not(x != y and x != "y") evaluates to True.

 

Recursion

Conceptual

  1. Which of the following are required in a recursive function that does not infinitely recur?

    1. A base case without a recursive function call

    2. Recursive case that progresses toward the base case

    3. Arguments changing in the recursive case

    4. All of the above

SHOW SOLUTIONS

    1. All of the above

 

Memory Diagram

  1. Create a memory diagram for the following code snippet. Additionally, identify the lines where the edge case, base case, and recursive case occur (this will generally consist of a conditional statement, a return statement, and possibly more lines of code in between).
1     """Recursion practice!"""
2 
3     def factorial(num: int) -> int:
4         """Calculate the factorial of num."""
5         if num <= 0:
6             return 1
7         elif num == 1:
8             return 1
9         else:
10            return num * factorial(num=num - 1)
11
12    def main() -> None:
13        """The main function."""
14        print(factorial(num=3))
15
16    main()
  1. Challenge Question: Create a memory diagram for the following code snippet. Identify which lines that base case(s) or recursive case(s) occur on.
"""Recursion practice with palindromes."""

def is_palindrome(word: str, index: int) -> bool:
    """Returns True if word is a palindrome and False otherwise."""
    if index >= int(len(word) / 2):
        return True
    elif word[index] == word[len(word) - (index + 1)]:
        return is_palindrome(word=word, index=index + 1)
    else:
        return False

def main() -> None:
    """The main function."""
    print(is_palindrome(word="noon", index=0))
    print(is_palindrome(word="110", index=0))

main()

SHOW SOLUTIONS

  1. The edge case occurs on lines 5-6, the base case occurs on lines 7-8, and the recursive case on lines 9-10.

Memory diagram of code listing with factorial and main functions

  1. The base cases occur on lines 5-6 and 9-10. If you reach the base case on lines 5-6 that means you made it through the whole word without finding any differences between letters that should be the same, so you can return True as the final result. If you make it to lines 9-10, that means a difference was found between letters that should be the same, so word is not a palindrome. The recursive case is on lines 7-8.

Memory diagram of code listing with palindrome function

 

Code Writing

  1. Write a recursive function named sum that has an int parameter number and returns an int that is the sum of all nonnegative integers up to and including number (1 + 2 + ... + number). For example, sum(number=4) should evaluate to 1 + 2 + 3 + 4 = 10. If a negative argument for number is given, just return -1 (What case is this?). It may help to come up with your base case and recursive case before beginning to write any code.

SHOW SOLUTIONS 1. The negative argument case is an edge case. Note: There are many equivalent ways this function could be written.

1    def sum(number: int) -> int:
2        """Sum of all nonnegative integers up to and including number."""
3        if number < 0: # Edge case
4            return -1
5        elif number > 0: # Recursive case
6            return number + sum(number=number - 1)
7        else: # Base case
8            return 0

 

f-strings

  1. What are the printed outputs for the following print function calls?

    1.1. print(f"{1 + 1}")

    1.2. print(f"C{'OM'}P {100 + 10}")

    1.3. print(f"This statement is {not (True or False)}!")

    1.4. print(f"Question: Is {55} even? Answer: {55 % 2 == 0}")

SHOW SOLUTIONS

1.1. 2

1.2. COMP 110

1.3. This statement is False!

1.4. Question: Is 55 even? Answer: False

 

Local Variables

  1. Which of the following properly declares a variable?

    1. "Michael Jordan" = name

    2. large_number = 2 ** 2025

    3. name: str = "Michael Jordan"

    4. int: large_number = 2 ** 2025

  2. Which of the following properly updates or assigns a value to a variable (if it has already been declared)?

    1. "Michael Jordan" = name

    2. large_number = 2 ** 2025

    3. name: str = "Michael Jordan"

    4. int: large_number = 2 ** 2025

  3. Refer to the following code snippet to answer this question. Describe what will happen if we run this code. Feel free to create a memory diagram to assist you.

1     def foo(num: int) -> None:
2         """Fooey."""
3         x: int = num * -1
4         print(x)
5 
6     def main() -> None:
7         """The main function."""
8         foo(4)
9         print(x)
10
11    main()

SHOW SOLUTIONS

  1. c: name: str = "Michael Jordan" The important part to notice is that we are giving it a type, which we only do during declaration.

    1. large_number = 2 ** 2025 Updating or assigning a value to a variable that has already been declared just uses the equal sign with the variable name on the left and the value on the right, and does not redeclare the type.
  2. When this code is run, you will first enter the main function since it is called on line 11, then you will enter the foo function when it is called on line 8. Then the foo function will declare a local variable x and print it, outputting -4. Then we will return to line 8, then move on to line 9 where we attempt to print x. However, x was a local variable only in the foo frame, not in the main frame, so we will get a NameError.

 

While Loops

Conceptual

  1. What happens if the condition of a while loop is initially False?

    1. The loop will run once.

    2. The loop will not run at all.

    3. The loop will run infinitely.

    4. The loop will throw an error.

  2. If a while loop statement starts with, while condition:, what must condition evaluate to for the following while loop to execute at least once? What type is condition?

SHOW SOLUTIONS

  1. B: The loop will not run at all.
  2. condition must be True to enter the loop. Its type is a bool.

 

Memory Diagram

  1. Produce a memory diagram for the following code snippet, being sure to include its stack and output.

    1     def main() -> None:
    2         """Main Function"""
    3         y: int = g(1)
    4         f(y)
    5         print(g(f(3)))
    6         
    7     def f(x: int) -> int:
    8         """Function 0"""
    9         if x % 2 == 0:
    10            print(str(x) + " is even")
    11        else:
    12            x = x + 1
    13        return x
    14        
    15    def g(x: int) -> int:
    16        """Function 1"""
    17        while x % 2 == 1:
    18            x = x + 1
    19        return x
    20 
    21    main()

    1.1. Why is it that main() is defined above f() and g(), but we are able to call f() and g() inside main() without errors?

    1.2. On line 5, when print(g(f(3))) is called, is the code block inside of the while loop ever entered? Why or why not?

    1.3. What would happen if a line was added to the end of the snippet that said print(x). Why?

SHOW SOLUTIONS

Memory diagram of functions main, f, and g

1.1 Even though main is defined before f and g, it isn't called until after f and g are defined.

1.2 No because x = 4, so x % 2 == 1 is False, and therefore the code block inside is never run.

1.3 There would be an error because x is a local variable inside both f and g. Therefore, the program does not recognize that x exists in this context.

 

Code Writing

  1. Write a function named sum_or_factorial using while loops that has an int parameter number and behaves in the following way:

    If number is negative, return -1.

    If number is even, return the sum of all positive integers up to and including number.

    If number is odd, return the product of all positive integers up to and including number (the factorial of number).

SHOW SOLUTIONS

Note: There are many ways you could write this function.

1     def sum_or_factorial(number: int) -> int:
2         """Returns the sum up to number if even or the factorial of number if odd."""
3         result: int
4         if number < 0:
5             return -1
6         elif number % 2 == 0:
7             result = 0
8             idx: int = 0
9             while idx <= number:
10                result = result + idx
11                idx = idx + 1
12        else:
13            result = 1
14            idx: int = 1
15            while idx <= number:
16                result = result * idx
17                idx = idx + 1
18        return result

 

Contributor(s): Alyssa Lytle, Izzi Hinks, Megan Zhang, David Karash, Viktorya Hunanyan, Benjamin Eldridge