ProgrammingHardTCS NQT · Infosys

What is printed?

What is printed?
h = 0
for ch in 'abc':
    h = (h * 31 + ord(ch)) % 1000
print(h, (-7) % 1000, (-7 * 31) % 1000)
  1. A. 354 993 217
  2. B. 354 -7 783
  3. C. 354 993 783
  4. D. 353 993 783

Correct answer: C. 354 993 783

The rolling hash ends at 354 after three steps. Python's % always returns a non-negative result for a positive modulus, so -7 gives 993 and -217 gives 783.

More Python Programming questions

Exams that ask this topic