CS FundamentalsVery hardTCS NQT · Infosys · product-company placement

Counting each if, loop header, and/or operator, conditional expression and except clause as one decision (V(G) = decisions + 1), what is the cyclomatic complexity of f, and what does f([3, -1, 4], 5) return?

Counting each if, loop header, and/or operator, conditional expression and except clause as one decision (V(G) = decisions + 1), what is the cyclomatic complexity of f, and what does f([3, -1, 4], 5) return?
def f(items, limit):
    total = 0
    for x in items:
        if x < 0 or x > limit:
            continue
        total += x if x % 2 == 0 else 2 * x
    else:
        total += 1
    try:
        r = 100 // total
    except ZeroDivisionError:
        r = -1
    return r
  1. A. 7 and 9
  2. B. 6 and 10
  3. C. 6 and 9
  4. D. 7 and 10

Correct answer: C. 6 and 9

Decisions: for, if, or, the conditional expression and except = 5, so V(G) = 6; the loop's else adds nothing because there is no break, so it always runs. total = 6 (3 doubled) + 4 = 10, then the else makes it 11 and 100 // 11 = 9. Forgetting the else gives 10.

More Software Engineering, Git and Cloud Basics questions

Exams that ask this topic