Ad
Fundamentals
Code
Diff
  • class OrdinalNumeral:
        def __init__(self, n: int):
            if n < 0: raise ValueError("n must be positive or 0")
            self.n = n
            self.numeral = self._numeral()
        
        def __repr__(self):
            """representation that can be used to recreate the object"""
            return f"OrdinalNumeral(self.n)"
        
        def __str__(self):
            """the 'nice' string version of the class"""
            return self.numeral
    
        def __int__(self):
            return self.n
        
        def __add__(self, other):
            """can implement arithmetic operations if desired"""
            if (isinstance(other, OrdinalNumeral)): return OrdinalNumeral(self.n + other.n)
            elif (isinstance(other, int)): return OrdinalNumeral(self.n + other)
            else: raise TypeError(f"Unable to add {type(other)} with OrdinalNumeral")
            
        def _numeral(self):
            """define the ordinal numeral string"""
            if 11 <= (self.n % 100) <= 13: return str(self.n)+"th"
            return str(self.n)+("th", "st", "nd", "rd", "th")[min(4, self.n % 10)]
    
    • class OrdinalNumeral:
    • def __init__(self, n: int):
    • if n < 0:
    • raise ValueError("n must be positive or 0")
    • if n < 0: raise ValueError("n must be positive or 0")
    • self.n = n
    • self.numeral = self._numeral()
    • def __repr__(self):
    • """
    • representation that can be used to recreate the object
    • """
    • return f"OrdinalNumeral({self.n})"
    • """representation that can be used to recreate the object"""
    • return f"OrdinalNumeral(self.n)"
    • def __str__(self):
    • """
    • the 'nice' string version of the class
    • """
    • """the 'nice' string version of the class"""
    • return self.numeral
    • def __int__(self):
    • return self.n
    • def __add__(self, other):
    • """
    • can implement arithmetic operations if desired
    • """
    • if (isinstance(other, OrdinalNumeral)):
    • return OrdinalNumeral(self.n + other.n)
    • elif (isinstance(other, int)):
    • return OrdinalNumeral(self.n + other)
    • else:
    • raise TypeError(f"Unable to add {type(other)} with OrdinalNumeral")
    • """can implement arithmetic operations if desired"""
    • if (isinstance(other, OrdinalNumeral)): return OrdinalNumeral(self.n + other.n)
    • elif (isinstance(other, int)): return OrdinalNumeral(self.n + other)
    • else: raise TypeError(f"Unable to add {type(other)} with OrdinalNumeral")
    • def _numeral(self):
    • """
    • define the ordinal numeral string
    • """
    • if 11 <= (self.n % 100) <= 13:
    • return str(self.n)+"th"
    • """define the ordinal numeral string"""
    • if 11 <= (self.n % 100) <= 13: return str(self.n)+"th"
    • return str(self.n)+("th", "st", "nd", "rd", "th")[min(4, self.n % 10)]