Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Write an endless generator squares() that gives 1, 4, 9, 16, ... Use itertools.islice to show the first 6, and a loop to find the first square over 500.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. An endless while True loop with a yield. islice takes the first few. A for loop with break stops at the answer.
Check. The first six squares are 1, 4, 9, 16, 25, 36. The first square over 500 is 529, which is 23 times 23 (22 times 22 is only 484).
Answer: [1, 4, 9, 16, 25, 36] and 529.
Log in to join the discussion.
Loading…