-3

Use map to evaluate a given polynomial at a specific x-value.

Input:

  • p: A list of coefficients for increasing powers of x
  • x: The value of x to evaluate

Output: Number representing the value of the evaluated polynomial

Example: poly_eval([1, 2, 3], 2) = 1(2)^0 + 2(2)^1 + 3(2)^2 = 17

martineau
  • 119,623
  • 25
  • 170
  • 301
Silent
  • 11
  • 1
    so what have you tried? People on SO should not be solving homework questions for you – Gilad Green Sep 23 '21 at 19:55
  • Welcome to Stack Overflow! You seem to be asking for someone to write some code for you. Stack Overflow is a question and answer site, not a code-writing service. Please [see here](https://stackoverflow.com/help/how-to-ask) to learn how to write effective questions – azro Sep 23 '21 at 19:56
  • Please see [How do I ask and answer homework questions?](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – martineau Sep 23 '21 at 19:58
  • Please provide enough code so others can better understand or reproduce the problem. – Community Oct 01 '21 at 13:33

2 Answers2

0
def poly_eval(coeff_list, x):
    total = 0
    for i, coeff in enumerate(coeff_list):
        total += coeff * x**i
    return total

or if you really want to use map :

def poly_eval(coeff_list, x):
    n = len(coeff_list)
    return sum(map(lambda coeff, x, y: coeff*x**y, coeff_list, [x]*n, range(n)))
patate1684
  • 639
  • 3
  • 17
0

This is actually an interesting question. Since the answer is relatively simple and the pen and paper solution is known by everybody the real thing is kind of overlooked.

As mentioned, normally most people would approach like how it's done by pen and paper. However there is a better way which is more suitable for coding purposes, known as the Ruffini Horner method. This is a perfect case for reducing.

Write your polynomial in an array. So y = x^3-7x+7 would be var y = [1,0,-7,7].

Then a simple function;

var calcP = (y,x) => y.reduce((p,c) => p*x+c);

That's it.

Redu
  • 25,060
  • 6
  • 56
  • 76