Skip to content

Commit bb8857f

Browse files
committed
Added exercise for enumerate in loops lesson
1 parent aa7c316 commit bb8857f

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

_episodes/02-loop.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,3 +299,47 @@ so we should always use it when we can.
299299
> > {: .python}
300300
> {: .solution}
301301
{: .challenge}
302+
> ## Computing the Value of a Polynomial
303+
>
304+
> The built-in function `enumerate` takes a sequence (e.g. a list) and generates a
305+
> new sequence of the same length. Each element of the new sequence contains the index
306+
> (0,1,2,...) and the value from the original sequence:
307+
>
308+
> ~~~
309+
> for i, x in enumerate(xs):
310+
> # Do something with i and x
311+
> ~~~
312+
> {: .python}
313+
>
314+
> The loop above assigns the index to `i` and the value to `x`.
315+
>
316+
> Suppose you have encoded a polynomial as a list of coefficients in
317+
> the following way: the first element is the constant term, the
318+
> second element is the coefficient of the linear term, the third is the
319+
> coefficient of the quadratic term, etc.
320+
>
321+
> ~~~
322+
> x = 5
323+
> cc = [2, 4, 3]
324+
> ~~~
325+
> {: .python}
326+
>
327+
> ~~~
328+
> y = cc[0] * x**0 + cc[1] * x**1 + cc[2] * x**2
329+
> y = 97
330+
> ~~~
331+
> {: .output}
332+
>
333+
> Write a loop using `enumerate(cc)` which computes the value `y` of any
334+
> polynomial, given `x` and `cc`.
335+
>
336+
> > ## Solution
337+
> > ~~~
338+
> > y = 0
339+
> > for i, c in enumerate(cc):
340+
> > y = y + x**i * c
341+
> > ~~~
342+
> > {: .python}
343+
> {: .solution}
344+
{: .challenge}
345+

0 commit comments

Comments
 (0)