Skip to content

Instantly share code, notes, and snippets.

@izanbf1803
Created October 18, 2018 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save izanbf1803/b48861096d15ebca896a2b3b04756cba to your computer and use it in GitHub Desktop.
Save izanbf1803/b48861096d15ebca896a2b3b04756cba to your computer and use it in GitHub Desktop.
Sample of generating functions implementation using Sympy.
"""
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