Skip to content

Instantly share code, notes, and snippets.

@AvocadosConstant
Last active June 26, 2017 14:14
Show Gist options
  • Save AvocadosConstant/c46c6418a4f8e9e32f4e4c2c54a1fda0 to your computer and use it in GitHub Desktop.
Save AvocadosConstant/c46c6418a4f8e9e32f4e4c2c54a1fda0 to your computer and use it in GitHub Desktop.
import sys
from math import factorial
from collections import Counter
from functools import reduce
"""
Solution to http://100.70.19.162:8000/contest/32/9
"""
""" Counts number of permutations of a given multiset
let m be the number of items in a multiset with n unique items
let each ith item of the multiset occur m_i times (multiplicity of m_i)
such that \sum_{i=1}^{n} m_i = m
then the number of unique permutations of the multiset is
\frac{m!}{\Pi_{i=1}^{n} m_i!}
The multiset will be given as a list of multiplicities
numer = m!
denom = \Pi_{i=1}^{n} m_i!
"""
def multiset_perms(multiset):
numer = factorial(sum(multiset))
# product of all permutations of each multiplicity
multiplicity_perms = map(lambda v: factorial(v), multiset)
denom = reduce(lambda x, y: x * y, multiplicity_perms)
return numer // denom
""" Counts number of possible unique palindromes from a Counter representing distribution of chars """
def count_unique_pals(counter):
if len([v for v in counter.values() if v % 2 == 1]) > 1:
# more than 1 character with odd occurrences
return 0
# partition into one side of the pivot
side = list(map(lambda v: v // 2, counter.values()))
return multiset_perms(side)
chars = sys.stdin.read().splitlines()[0]
print(count_unique_pals(Counter(chars)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment