Skip to content

Instantly share code, notes, and snippets.

@nakulj
Last active August 29, 2015 14:13
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 nakulj/61f75bdfbeaf3c5c4c05 to your computer and use it in GitHub Desktop.
Save nakulj/61f75bdfbeaf3c5c4c05 to your computer and use it in GitHub Desktop.
Polynomial Class
def superscript(num):
superscripts = dict(zip(u"0123456789", u"⁰¹²³⁴⁵⁶⁷⁸⁹"))
return u''.join(superscripts[c] for c in unicode(num))
def str_term(coeff, (p,q)):
if coeff is 0:
return ''
if coeff is 1:
coeff = ''
if p is q is 0:
return coeff
p = '' if p is 0 else u'p'+('' if p is 1 else superscript(p))
q = '' if q is 0 else u'q'+('' if q is 1 else superscript(q))
pre = u'{} {} {}'.format(coeff, p, q)
return u' '.join(pre.split())
class TwoPolynomial(dict):
"""A polynomial in two variables"""
def __repr__(self):
return 'TwoPolynomial({})'.format(dict(self))
def __unicode__(self):
sorted_keys = sorted(dict(self), reverse= True)
return u' + '.join(str_term(self[k],k) for k in sorted_keys)
def __str__(self):
return unicode(self).encode('utf-8')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment