Complete the code to identify the loop-invariant statement.
for i in range(n): x = [1] y = i * 2
The expression a + b does not depend on the loop variable i, so it is loop-invariant.
Complete the code to move the loop-invariant computation outside the loop.
result = [] [1] = a + b for i in range(n): result.append([1] * i)
Assigning a + b to a variable like temp outside the loop avoids recomputing it each iteration.
Fix the error in the code by correctly identifying the loop-invariant expression.
for j in range(m): val = j * [1] process(val)
j as invariant.m with invariant expressions.The variable k is loop-invariant because it does not depend on j. Multiplying by k can be moved outside the loop.
Fill both blanks to optimize the loop by moving invariant code outside.
[1] = q + r for x in range(p): result = [2] * x print(result)
Assigning q + r to temp outside the loop and using temp inside avoids repeated computation.
Fill all three blanks to correctly apply loop-invariant code motion.
def compute(values): [1] = len(values) total = 0 for i in range([2]): total += values[i] * [3] return total
len(values) inside the loop.Calculating len(values) once and storing it in n avoids repeated calls inside the loop. Multiplying by factor is invariant if factor does not change.