File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff 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+
You can’t perform that action at this time.
0 commit comments