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+
303+ > ## Computing the Value of a Polynomial
304+ >
305+ > The built-in function `enumerate` takes a sequence (e.g. a list) and generates a
306+ > new sequence of the same length. Each element of the new sequence contains the index
307+ > (0,1,2,...) and the value from the original sequence:
308+ >
309+ > ~~~
310+ > for i, x in enumerate(xs):
311+ > # Do something with i and x
312+ > ~~~
313+ > {: .python}
314+ >
315+ > The loop above assigns the index to `i` and the value to `x`.
316+ >
317+ > Suppose you have encoded a polynomial as a list of coefficients in
318+ > the following way: the first element is the constant term, the
319+ > second element is the coefficient of the linear term, the third is the
320+ > coefficient of the quadratic term, etc.
321+ >
322+ > ~~~
323+ > x = 5
324+ > cc = [2, 4, 3]
325+ > ~~~
326+ > {: .python}
327+ >
328+ > ~~~
329+ > y = cc[0] * x**0 + cc[1] * x**1 + cc[2] * x**2
330+ > y = 97
331+ > ~~~
332+ > {: .output}
333+ >
334+ > Write a loop using `enumerate(cc)` which computes the value `y` of any
335+ > polynomial, given `x` and `cc`.
336+ >
337+ > > ## Solution
338+ > > ~~~
339+ > > y = 0
340+ > > for i, c in enumerate(cc):
341+ > > y = y + x**i * c
342+ > > ~~~
343+ > > {: .python}
344+ > {: .solution}
345+ {: .challenge}
You can’t perform that action at this time.
0 commit comments