Python Program to Calculate Polynomial Derivative Using Enumerate
# Example 1
f = [4, 5, 0, 2]
dfdx = [i*f[i] for i in range(1, len(f))]
print(dfdx) # Output: [5, 0, 6]
# Example 2
f = [10, 1, 1, 1, 1, 1]
dfdx = [i*f[i] for i in range(1, len(f))]
print(dfdx) # Output: [1, 2, 3, 4, 5]
This code snippet efficiently calculates the derivative of a polynomial function represented as a list using Python's list comprehension and the enumerate function. Here's how it works:
- Polynomial Representation: The polynomial coefficients are stored in a list,
f, where the index corresponds to the power of the variable. - Derivative Calculation: The list comprehension
[i*f[i] for i in range(1, len(f))]iterates through the elements off(starting from index 1 to exclude the constant term) and multiplies each coefficient by its corresponding power (index). The result is stored in the listdfdx. - Output: The program prints the derivative list
dfdx.
This code provides a concise and efficient way to calculate the derivative of a polynomial function in Python, leveraging the power of list comprehension and the enumerate function.
原文地址: https://www.cveoy.top/t/topic/lfhP 著作权归作者所有。请勿转载和采集!