LearnFrenzy
Sign in Take a free test

Iterators and Generators · Find the Error · Question 10

Bug: prices use the new rate instead of the old one Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

The prices should use the 2% rate in force when the generator was created: [102.0, 204.0]. Which statement correctly identifies the bug?

main.py
rate = 0.02
prices = (p * (1 + rate) for p in [100, 200])
rate = 0.10                         # the rate changes later
print(list(prices))
  • A The multiplication is done in the wrong order
  • B Floats cannot be used in generators
  • C list() recalculates the prices twice
  • D A generator expression is lazy: it reads rate when each value is produced, after rate has changed; build a list immediately or capture the rate (e.g. pass it to a function) Correct
Correct Answer: Option D

Only the first iterable ([100, 200]) is evaluated when the generator is created; everything else runs later. (The odd decimals are ordinary float rounding.)

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links