Practice Notes: Lesson 8

1) What is the counter variable and the condition?

    for (var i = 10; i > 0; i--) {
   println(i);
}

The counter variable is i, which according to a web search keeps track of the number of times commands associated with the for loop are executed. This is essentially an index.

The condition that the for loop would keep running is that i > 0 given that as long as this remains true, the for loop will keep executing. Keep in mind that every time the for loop executes, the value of the counter variable decreases by one.

2) How many times will printIn be called?

   for (var i = 1; i <= 10; i++) {
  for (var j = 1; j <= 10; j++) {
    printIn(i * j);
  }
}

Not the best formatting… I’ll assume this second for loop is nested inside of the first for loop.

Both for loops will execute with the index starting at one and increasing by one each time until the index is over 10. Since the j for loop is nested inside the i for loop, printIn() will be executed 10 * 10 or 100 times.

3) What is the initial value? What does the while loop check?

   var numRabbits = 2;
var numYears = 0;
while (numRabbits <= 100) {
    numRabbits += (numRabbits/2 * 30);
    numYears++;
}

The initial value of the variable numRabbits is 2 simply because that’s what it was defined as on the first line.

The initial value of the variable numYears is 0 since this was how it was defined on the second line.

The while loop checks if the value of numRabbits is less than or equal to 100. If this condition is satisfied, the executed command will be executed. These commands will increase the variable of numRabbits by 15 times its original value (essentially multiplying its value by 16 due to the original value also being additively present) and will increase the variable numYears by 1.

Notes After Checking

Practice Notes: Lesson 10

1) What is the output?

{
    lst =  ["your", "a", "very", "skilled", "individual"]
    lst.append("Person")
    lst.pop()
    lst.remove("your")
    lst.insert(0, "you're")
    print(lst)
}

Checker’s note: I’ll have to test if using single quotes and double quotes for string elements in the same list is compatible.

2) Using Lists

  1. A sequence of children in order should be represented by a list with each of the children’s names in the list as string elements in order.
  2. The number of animals in a zoo does not need a list; only an integer variable numAnimals is required.
  3. A list would not be required to repeatedly derive a number because this falls under the function of iteration/loops. This is true unless perhaps each of those derivatives needed to be stored. In that case, a list with float/integer elements would be useful and an append command would be added to the loop. Any such list would be pointless, however, because the derivative of a number (constant) is zero. This would result in a list with many zeros.
  4. Pairs of school classes and the grades of each class would need a special form of list, where each element is a dictionary. This dictionary would probably match the class (type and period) with a corresponding string element and the average grade with a float element. Each class would be one dictionary element in the list.

Note: The fourth part of this question was a little bit vague. I took a bit of creative liberty with it (usually class grades rather than classroom grades are averaged). After a check, it turns out the fourth part was a fourth and fifth part jammed together.

To be honest, I’m not sure what the context of the quantities and key value pairs in this question are. This question doesn’t really make too much sense to me so I can’t answer it.

This makes a bit more sense. It seems we want to have a collection of the grades of all the students in a classroom. A list would be appropriate to store the student’s grades.

3) Find the missing line. This is pseudocode

{
mgAmounts ← [50, 230, 63, 98, 80, 120, 71, 158, 41]
bestAmounts ← []
mgPerDay ← 360
mgMin ← mgPerDay * 0.3
FOR EACH mgAmount IN mgAmounts
{
    IF (mgAmount ≥ mgMin)
    {
        <MISSING CODE>
    }
} 
}

INSERT(aList, i, value) inserts value at index i in aList. All INSERT commands in the answer choices have incorrect syntax (as they have only two arguments)

APPEND(aList, value) inserts value as the final position of aList.

Option B (which appends any mgAmount satisfying the condition of being less than 120 to bestAmounts) functions correctly.

4) Find sevenWonders

{
sevenWonders ← ["Aurora", "Grand Canyon", "Great Barrier Reef", "Guanabara Bay", "Mount Everest", "Parícutin", "Victoria Falls"]

sevenWonders[4] ← "Komodo"
sevenWonders[6] ← "Table Mountain"
}

CollegeBoard pseudocode is 1-indexed (the first element of a list has index 1)

Answer: sevenWonders ← [“Aurora”, “Grand Canyon”, “Great Barrier Reef”, “Komodo”, “Mount Everest”, “Table Mountain”, “Victoria Falls”]

5) Find the output

{

lst = [12,3,4,5,14,6,1,234]

lst.pop()
lst.append('x')
lst.insert(lst[0])

print(lst.pop())
print(lst)

}

I initially though print(lst.pop()) would return an error. But according to some documentation, this actually returns None.

Otherwise, knowing list contents will involve incorporating the steps

ANSWER: (no output)

Now I’m fairly certain that in-class someone argued there would be actual output. I’m willing to hold a contrary position due to me running the code in a .ipynb file.

New Question: Programs intended to display total hours. Do they work?


totalMins ← 0
durations ← [32, 56, 28, 27]
FOR EACH duration IN durations
{
   totalMins ← totalMins + duration
}
totalHours ← totalMins / 60
DISPLAY(totalHours)
}
{
totalMins ← 0
durations ← [32, 56, 28, 27]
FOR EACH duration IN durations
{
   totalMins ← totalMins + duration
   totalHours ← totalMins / 60
}
DISPLAY(totalHours)
}

Therefore, Answer is D

Javelin thrower writing code to track distance of throws from target. Complexity can be reduced. Choose the best.

{
totalDistance ← 0
targetDistance ← 90
throw1 ←  85.2
DISPLAY(targetDistance - throw1)
totalDistance ← totalDistance + throw1
throw2 ←  82.8
DISPLAY(targetDistance - throw2)
totalDistance ← totalDistance + throw2
throw3 ←  87.3
DISPLAY(targetDistance - throw3)
totalDistance ← totalDistance + throw3
avgDistance ← totalDistance / 3
DISPLAY(avgDistance)

A)

targetDistance ← 90
throws ← [85.2, 82.8, 87.3]
totalDistance ← 0
FOR EACH throw IN throws
{
DISPLAY(targetDistance - throw)
totalDistance ← totalDistance + throw
}
avgDistance ← totalDistance / LENGTH(throws)
DISPLAY(avgDistance)

B)

targetDistance ← 90
throws ← [85.2, 82.8, 87.3]
totalDistance ← 0
FOR EACH throw IN throws
{
DISPLAY(targetDistance - throw)
totalDistance ← totalDistance + throw
}
avgDistance ← totalDistance / 3
DISPLAY(avgDistance)

C)

targetDistance ← 90
throws ← [85.2, 82.8, 87.3]
totalDistance ← 0
FOR EACH throw IN throws
{
DISPLAY(targetDistance - throw)
totalDistance ← totalDistance + throw
avgDistance ← totalDistance / LENGTH(throws)
}
DISPLAY(avgDistance)

D)

targetDistance ← 90
throws ← [85.2, 82.8, 87.3]
FOR EACH throw IN throws
{
totalDistance ← 0
DISPLAY(targetDistance - throw)
totalDistance ← totalDistance + throw
avgDistance ← totalDistance / LENGTH(throws)
}
DISPLAY(avgDistance)

E)

targetDistance ← 90
throws ← [85.2, 82.8, 87.3]
FOR EACH throw IN throws
{
totalDistance ← 0
DISPLAY(targetDistance - throw)
totalDistance ← totalDistance + throw
}
avgDistance ← totalDistance / LENGTH(throws)
DISPLAY(avgDistance)

Option A is the best

Option B is similar to A, except that the avgDistance is calculated by dividing 3. This is not as versatile as Option A (ie it doesn’t work for lists with lengths different than 3)

Options C and D recalculate the avgDistance on each execution of the for loop (with variations similar to A and B). This would produce the same result but is not as efficient.

Option E has a logic error which sets totalDistance equal to zero at the start of each execution of the for loop. This will result in the avgDistance being a third of the final element in the list, 87.3/3 = 29.1. This is unquestionably the worst option.

Hacks

MCQ Quiz

Question 9 was fun because I managed to prove that all three loops are actually possible! This was the one where a loop should be made to iterate until a user inputs ‘quit’

I have selected the WHILE loops answer and the Recursive loops answer, which were both marked incorrect. I can rebut the claim these answers are incorrect since I have examples of both in python that actually function. The first is recursive (which was the first solution I came up with), and the second is a while loop.

They essentially do the exact same thing: for a list with integer elements 1 through 5, it checks if the index is less than the length; if so, it prints the corresponding element. It executes an opportunity to stop iterating through the list through checking the input for “quit” and executing return if it does. It also increases i by one for each execution and uses a conditional statement to make sure the index does not stray out of range and iteration can continue.

List = [1, 2, 3, 4, 5]

def hrar(i):
    # makes sure index does not leave
    # range
    if i == 5:
        i = 0
    # prints list elements. Honestly if
    # statement not needed since
    # commands executed to guard the index
    if i < len(List):
        temp = List[i]
        print(temp)
    # allows user to exit iteration if input "quit"
    hi = input("Input quit to stop the code. This is case-sensitive")
    if (hi == "quit"):
            return
    # Iteration!
    hrar(i + 1)

hrar(0)
    

This is the while loop. At first I thought this wouldn’t work since I believed the variable used in the comparison statement (hi) would fail to update… but apparently it works in my notebook file.

# Variables!
List = [1, 2, 3, 4, 5]

hi = "hi"
i = 0
# Iteration!
while hi != "quit":
    # prints element corresponding to index, increases index
    if i < len(List):
        temp = List[i]
        print(temp)
        i = i + 1
    # Ensures index does not leave range
    if i == 5:
        i = 0
    # Opportunity to terminate iteration
    hi = input("Input quit to stop the code. This is case-sensitive")

The intended answer, the for loop, was actually the hardest for me. I needed to come up with a way to prevent the loop from terminating. There was also lots of output errors whenever I changed the contents of the list. Nevertheless, I managed to find a method. However, it does not have infinite capacity; rather, it has a capacity unlikely to be exhausted by human means.

# Variables!
List = [1, 2, 3, 4, 5]
hi = "hi"

# Has a finite but very high range. Doubt a 
# human is going to exhaust this. A computer might.
for i in range(999999999999999):
    # i resets to 0, 1, 2, 3, 4, 5, 6... on each execution.
    # This prevents i from leaving the list range.
    mod = i % 5
    i = mod
    # Prints list entry. If statement may not be required.
    if i < len(List):
        temp = List[i]
        print(temp)
    # Gives an opportunity to terminate the iteration.
    # break is required since this is not a function.
    hi = input("Input quit to stop the code. This is case-sensitive")
    if (hi == "quit"):
            break

Coding Hacks: See the .ipynb file

ipynb file

Hack Flowchart: This is here