Created
October 18, 2018 16:53
-
-
Save izanbf1803/b48861096d15ebca896a2b3b04756cba to your computer and use it in GitHub Desktop.
Sample of generating functions implementation using Sympy.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Problem: | |
Cody has 4 types of onions. | |
The number of purple onions can be any non-negative integer. | |
The number of green onions is a multiple of 2. | |
The number of red onions is a multiple of 3. | |
The number of blue onions is a multiple of 5. | |
If Cody has N onions, how many different distributions of colors can there be? | |
""" | |
from sympy import poly | |
from sympy.abc import x | |
R = poly(1, x) | |
P = [poly(0, x)] * 4 | |
M = [1, 2, 3, 5] | |
N = 1000 | |
for i in range(4): | |
for k in range(0, N//M[i]+1): | |
P[i] += poly(x**(M[i]*k), x) | |
R *= P[i] | |
print("Answer:", R.coeffs()[N]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment