pythondictionarymathpolynomialspolynomial-math# Multiplying polynomials using dictionaries in Python

I want to multiply polynomials as a dictionary without the use of numpy and classes as easily as possible without using external libraries. Saw some posts about it on here but they either use lists, classes or numpy :/

A polynomial is represented by a dict mapping degree to coefficient. For instance:

`{0: 7, 2: 5, 4: 3}`

represents 3x^4 + 5x^2 + 7.

I tried using the following code:

```
def mlpt(p1,p2):
p1_times_p2 = {}
for i in p1:
erg_coeff = p1[i]
erg_exp = i
for j in p2:
erg_coeff = erg_coeff * p2[j]
erg_exp = erg_exp + j
p1_times_p2[erg_exp] = erg_coeff
for i in p2:
erg_coeff = p2[i]
erg_exp = i
for j in p1:
erg_coeff = erg_coeff * p1[j]
erg_exp = erg_exp + j
p1_times_p2[erg_exp] = erg_coeff
return p1_times_p2
```

However, when I multiply two arbitrary polynomials, I don't seem to get the right result:

```
# (x^2)(x^2 + x) == x^4 + x^3
p1 = {2: 1} # x^2
p2 = {1: 1, 2: 1} # x^2 + x
print( mlpt(p1,p2) )
# EXPECTED OUT: {4: 1, 3: 1}
# ACTUAL OUT: {5: 1, 3: 1, 4: 1}
```

Does anyone have an idea how to fix it? Any help would be greatly appreciated!

Solution

Assuming your dicts are `{exponent: coefficient}`

, a simple option would be to have two nested loops which populate the result dict:

```
def multiply(p1, p2):
res = {}
for e1, c1 in p1.items():
for e2, c2 in p2.items():
e = e1 + e2
res[e] = res.get(e, 0) + c1 * c2
return res
```

An exercise to the reader: adapt this to perform *symbolic* computations as in `multiply({2:'a',1:'b'},{2:'c'})`

- Python Jinja2 LaTeX Table
- Getting attributes of a class
- How can I print many significant figures in Python?
- How to allow list append() method to return the new list
- Calculate Last Friday of Month in Pandas
- Python type hint for Iterable[str] that isn't str
- How to iterate over a list in chunks
- How to exit the entire application from a Python thread?
- Running shell command and capturing the output
- How do I pass a variable by reference?
- Convert range(r) to list of strings of length 2 in python
- How can I get the start and end dates for each week?
- how to use send_message() in python-telegram-bot
- Python conditional replacement based on element type
- How can I count the number of items in an arbitrary iterable (such as a generator)?
- Find longest consecutive range of numbers in list
- Insert text in braces with asyncpg
- How does one put a link / url to the web-site's home page in Django?
- How to determine if a path is a subdirectory of another?
- Custom Keybindings for Ipython terminal
- FastAPI asynchronous background tasks blocks other requests?
- How to make sure that information from one file is duplicated into several text documents, without specific lines
- Installing a Python environment with Anaconda
- sklearn pipeline model predicting same results for all input
- Brew command not found after installing Anaconda Python
- How to get an XPath from selenium webelement or from lxml?
- Pipe PuTTY console to Python script
- How to align the axes of a figure in matplotlib?
- Persist ParentDocumentRetriever of langchain
- How to reset index in a pandas dataframe?