Skip to content

Implement a class for allowing combined string / number variables. #36

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions polynomial/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -698,3 +698,43 @@ def __complex__(self):
def __repr__(self):
"""Return repr(self)."""
return "ZeroPolynomial()"

class Term:
"""A term defines constants and unknown variables together"""

__slots__ = ("variables", "number")

def __init__(self, variables, num):
"""Create a term with the given variables and constant num."""
self.variables = [variables]
self.number = num

def __repr__(self):
"""Return repr(self)."""
return "Term({0!r}, {1!r})".format(self.variables, self.number)

def __str__(self):
"""Return str(self)."""
from collections import Counter
self.variables = sorted(self.variables)

def to_word(char, counts):
if counts == 1:
return char
return "{0}^{1}".format(char, counts)

if self.number == 0:
return "0"

_str = "".join([
to_word(char, counts) for char, counts
in Counter(self.variables).items()]
)

if self.number == 1:
return _str
if self.number == -1:
return "-" + _str
if isinstance(self.number, complex):
return "({}){}".format(self.number, _str)
return str(self.number) + _str