Advertisement
Guest User

Challenge 3 Submissions

a guest
Mar 8th, 2016
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 14.21 KB | None | 0 0
  1. class Matrix:
  2.     def __init__(self, a, b, c, d):
  3.         self.a = a
  4.         self.b = b
  5.         self.c = c
  6.         self.d = d
  7.         self.det = a * d - b * c
  8.  
  9.     def isInvert(self):
  10.         return self.det != 0
  11.  
  12.     def printMatrix(self):
  13.         print("| {} {} |\n| {} {} |".format(self.a, self.b, self.c, self.d))
  14.  
  15.     def inverse(self):
  16.         if not self.isInvert():
  17.             return None
  18.         new_a = float(self.d) / self.det
  19.         new_b = -float(self.b) / self.det
  20.         new_c = -float(self.c) / self.det
  21.         new_d = float(self.a) / self.det
  22.         return Matrix(new_a, new_b, new_c, new_d)
  23.  
  24.     @staticmethod
  25.     def __quadratic_solver(a, b, c):
  26.         import math
  27.         d = pow(b, 2) - 4 * a * c
  28.  
  29.         if d < 0:
  30.             return []
  31.         elif not d:
  32.             return [(- b + math.sqrt(d)) / (2 * a)]
  33.         return [(-b + math.sqrt(d)) / (2 * a), (-b - math.sqrt(d)) / (2 * a)]
  34.  
  35.     def eigenvalue(self):
  36.         return self.__quadratic_solver(1, -(self.a + self.d), self.det)
  37.  
  38.     # Make matrix printable so that we can call print(matrix) instead of matrix.printMatrix()
  39.     def __str__(self):
  40.         return "| {} {} |\n| {} {} |".format(self.a, self.b, self.c, self.d)
  41.  
  42.     # Allows us to add to matrices with the "+" operator
  43.     def __add__(self, other):
  44.         return Matrix(self.a + other.a, self.b + other.b, self.c + other.c, self.d + other.d)
  45.  
  46.     # Allows us to subtract to matrices with the "-" operator
  47.     def __sub__(self, other):
  48.         return Matrix(self.a - other.a, self.b - other.b, self.c - other.c, self.d - other.d)
  49.  
  50.     # The matrix can now have a negativ sign. This is the same as multiplying with -1
  51.     def __neg__(self):
  52.         return -1 * self
  53.  
  54.     # Allows us to multiply a matrix with a constant or another matrix with the "*" operator
  55.     def __mul__(self, other):
  56.         if isinstance(other, int) or isinstance(other, float):
  57.             return Matrix(other * self.a, other * self.b, other * self.c, other * self.d)
  58.         new_a = self.a * other.a + self.b * other.c
  59.         new_b = self.a * other.b + self.b * other.d
  60.         new_c = self.c * other.a + self.d * other.c
  61.         new_d = self.c * other.b + self.d * other.d
  62.         return Matrix(new_a, new_b, new_c, new_d)
  63.  
  64.     # Without this "constant * matrix" would throw an exception, while "matrix * constant" would not
  65.     __rmul__ = __mul__
  66.  
  67.  
  68.  
  69.  
  70.  
  71.  
  72.  
  73.  
  74. class Matrix:
  75.     def __init__(self, a, b, c, d):
  76.         self.a = float(a)
  77.         self.b = float(b)
  78.         self.c = float(c)
  79.         self.d = float(d)
  80.         self.determinant = (a * d) - (b * c)
  81.  
  82.     def isInvert(self):
  83.         return self.determinant != 0
  84.  
  85.     def printMatrix(self):
  86.         print(str.format("| {} {} |", self.a, self.b))
  87.         print(str.format("| {} {} |", self.c, self.d))
  88.  
  89.     def inverse(self):
  90.         if not self.isInvert():
  91.             return None
  92.         return Matrix(self.d  / self.determinant,
  93.                       -self.b / self.determinant,
  94.                       -self.c / self.determinant,
  95.                       self.a  / self.determinant)
  96.  
  97.  
  98.  
  99.  
  100.  
  101.  
  102.  
  103. #!/usr/bin/python3
  104. # Design a class called Matrix() that accepts four parameters to create a 2x2
  105. # matrix. This class should have five member variables: the four numerical
  106. # entries and also its determinant.
  107.  
  108.  
  109. class Matrix(object):
  110.     def __init__(self, values):
  111.         self.a = float(values[0])
  112.         self.b = float(values[1])
  113.         self.c = float(values[2])
  114.         self.d = float(values[3])
  115.         # This won't change if you change one of the values after creation.
  116.         self.determinant = (self.a * self.d - self.b * self.c)
  117.  
  118.     def is_invertable(self):
  119.         return self.determinant != 0
  120.  
  121.     def print_matrix(self):
  122.         print("| {0} {1} |\n| {2} {3} |".format(self.a, self.b, self.c, self.d))
  123.  
  124.     def inverse(self):
  125.         if self.is_invertable():
  126.             inverted = []
  127.  
  128.             def invert(x):
  129.                 return x / self.determinant
  130.  
  131.             inverted = [invert(x) for x in [self.d, -self.b, -self.c, self.a]]
  132.             return Matrix(inverted)
  133.         else:
  134.             return None
  135.  
  136.  
  137. if __name__ == "__main__":
  138.     example = Matrix([1.0, 2.0, 3.0, 4.0])
  139.     print(example.determinant)
  140.     print(example.is_invertable())
  141.     inverted = example.inverse()
  142.     inverted.print_matrix()
  143.     example.print_matrix()
  144.  
  145.  
  146.  
  147.  
  148.  
  149.  
  150.  
  151.  
  152. class Matrix:
  153.     def __init__(self, *args, **kwargs):
  154.         if not all(map(lambda n: isinstance(n, float), args)):
  155.             raise TypeError("All arguments must be of type float")
  156.         elif len(args) != 4:
  157.             raise NotImplementedError("Support for 2x2 matrix only")
  158.         self.a, self.b, self.c, self.d = args
  159.         self.determinant = self.a * self.d - self.b * self.c
  160.  
  161.     def __str__(self):
  162.         max_length = max(len(str(v)) for k, v in self.__dict__.items() if k != 'determinant')
  163.         return "| {a:>{max_length}} {b:>{max_length}} |\n| {c:>{max_length}} {d:>{max_length}} |".format(max_length=max_length, **self.__dict__)
  164.  
  165.     def is_invert(self):
  166.         return bool(self.determinant)
  167.  
  168.     def inverse(self):
  169.         if self.is_invert():
  170.             return Matrix(self.d / self.determinant,
  171.                           self.b * -1 / self.determinant,
  172.                           self.c * -1 / self.determinant,
  173.                           self.a / self.determinant)
  174.         else:
  175.             return "Can't invert an uninvertible matrix."
  176.  
  177.  
  178. matrix = Matrix(1.0, 2.0, 3.0, 4.0)
  179. print("determinant:", matrix.determinant)
  180. print("matrix is invertible:", matrix.is_invert())
  181. print("matrix")
  182. print(matrix)
  183. print("inverse matrix")
  184. print(matrix.inverse())
  185.  
  186.  
  187.  
  188.  
  189.  
  190.  
  191.  
  192.  
  193.  
  194. # over all documentation is a bit incomplete since I'm pretty bad with the
  195. # matrix topic.
  196.  
  197.  
  198. class Matrix:
  199.     """
  200.    Create simple 2x2 matrixs with each instance.
  201.    attributes:
  202.        a (float)       point a of the matrix.
  203.        b (float)       point b of the matrix.
  204.        c (float)       point c of the matrix.
  205.        d (float)       point d of the matrix.
  206.        determinant     determinant of the matrix.
  207.    """
  208.  
  209.     def __init__(self, a, b, c, d):
  210.         """
  211.        called when creating new instance of the Matrix class. Accepts int and
  212.        float input. All input is converted to float.
  213.        args:
  214.            a (int/float)       point a of the matrix.
  215.            b (int/float)       point b of the matrix.
  216.            c (int/float)       point c of the matrix.
  217.            d (int/float)       point d of the matrix.
  218.        rasies:
  219.            TypeError           All inputs need to be ints or floats.
  220.        """
  221.         self.a = float(a)
  222.         self.b = float(b)
  223.         self.c = float(c)
  224.         self.d = float(d)
  225.         self.determinant = (a * d) - (b * c)
  226.  
  227.     def print_matrix(self):
  228.         """
  229.        Prints out representation of the the matrix.
  230.        """
  231.         print("| {} {} |\n| {} {} |".format(self.a, self.b, self.c, self.d))
  232.  
  233.     def is_invert(self):
  234.         """
  235.        Returns if the matrix is invertible.
  236.        return:
  237.            bool        True if matrix is invertible and False otherwise.
  238.        """
  239.         return self.determinant != 0
  240.  
  241.     def inverse(self):
  242.         """
  243.        Creates a inverted matrix.
  244.        return:
  245.            Matrix      Returns new instance of the Matrix class if invertible.
  246.            None        Returns None if not invertible.
  247.        """
  248.         if self.is_invert:
  249.             a = self.d / self.determinant
  250.             b = self.b / self.determinant * -1
  251.             c = self.c / self.determinant * -1
  252.             d = self.a / self.determinant
  253.             return Matrix(a, b, c, d)
  254.         else:
  255.             return None
  256.  
  257.  
  258. if __name__ == '__main__':
  259.     new_matrix = Matrix(1, 2, 3, 4)
  260.     new_matrix.print_matrix()
  261.     print(new_matrix.determinant)
  262.     print(new_matrix.is_invert())
  263.     matrix2 = new_matrix.inverse()
  264.     matrix2.print_matrix()
  265.     print(new_matrix == matrix2)
  266.  
  267.  
  268.  
  269.  
  270.  
  271.  
  272.  
  273.  
  274. import numbers
  275.  
  276. """Matrix class
  277.  By: TheFueley (Renegade_Pythons)
  278. """
  279.  
  280. class Matrix:
  281.     """creates Matrix object
  282.   Args: a, b, c, d
  283.   Raises: ValueError if a,b,c, or d are not numbers
  284.   """
  285.  
  286.     def __init__(self, a, b, c, d):
  287.         if not isinstance(a, numbers.Real):
  288.             raise ValueError("Not a digit '{}'".format(a))
  289.         elif not isinstance(b, numbers.Real):
  290.             raise ValueError("Not a digit '{}'".format(b))
  291.         elif not isinstance(c, numbers.Real):
  292.             raise ValueError("Not a digit '{}'".format(c))
  293.         elif not isinstance(d, numbers.Real):
  294.             raise ValueError("Not a digit '{}'".format(d))
  295.         else:
  296.             self._a = a
  297.             self._b = b
  298.             self._c = c
  299.             self._d = d
  300.             self.deter = self._findDeter()
  301.  
  302.     def isInvert(self):
  303.         """Checks if matrix is invertible
  304.       Returns: True if invertible, false otherwise
  305.       """
  306.         if self._findDeter() == 0:
  307.             return False
  308.         else:
  309.             return True
  310.  
  311.     def printMatrix(self):
  312.         """Prints values of matrix
  313.       """
  314.         print("| " + str(self._a) + " " + str(self._b) + " |")
  315.         print("| " + str(self._c) + " " + str(self._d) + " |")
  316.  
  317.     def inverse(self):
  318.         """inverts the matrix
  319.       Returns: a new matrix, inverted from one that was supplied
  320.       """
  321.         if self.isInvert():
  322.             a = self._a / self.deter
  323.             b = self._b / self.deter * -1
  324.             c = self._c / self.deter * -1
  325.             d = self._d / self.deter
  326.             return Matrix(d, b, c, a)
  327.         else:
  328.             return None
  329.  
  330.     def _findDeter(self):
  331.         """find's the determinant of the matrix
  332.       Returns: determinant
  333.       """
  334.         return (self._a * self._d) - (self._b * self._c)
  335.  
  336.  
  337.  
  338.  
  339.  
  340.  
  341. class Matrix():
  342.     def __init__(self, a, b, c, d):
  343.         self.a = a
  344.         self.b = b
  345.         self.c = c
  346.         self.d = d
  347.         Matrix.determinant = (a*d) - (b*c)
  348.  
  349.     def isInvert(self):
  350.         return Matrix.determinant != 0
  351.  
  352.     def printMatrix(self):
  353.         print('| %F %F |' % (self.a, self.b))
  354.         print('| %F %F |' % (self.c, self.d))
  355.  
  356.  
  357.     def inverse(self):
  358.         if Matrix.isInvert(self) is True:
  359.             return Matrix((self.d / Matrix.determinant),
  360.                             (-self.b / Matrix.determinant),
  361.                             (-self.c / Matrix.determinant),
  362.                             (self.a / Matrix.determinant))
  363.         elif Matrix.isInvert(self) is False:
  364.             print("Wrong, not invertible.")
  365.  
  366.  
  367.  
  368.  
  369.  
  370.  
  371.  
  372.  
  373.  
  374. # elcrawfodor
  375.  
  376. class Matrix():
  377.     """
  378.    creates a 2 x 2 matrix with entries
  379.    a   b
  380.    c   d
  381.    """
  382.     def __init__(self, a, b, c, d):
  383.         self.a = float(a)
  384.         self.b = float(b)
  385.         self.c = float(c)
  386.         self.d = float(d)
  387.         self.determinant = float(a*d) - float(b*c)
  388.  
  389.     def isInvert(self):
  390.         """
  391.        checks to see if matrix is invertible
  392.        :return: Boolean
  393.        """
  394.         return self.determinant != 0
  395.  
  396.     def printMatrix(self):
  397.         """
  398.        prints out the matrix with format
  399.        | a b |
  400.        | c d |
  401.        """
  402.         print("| {} {} |".format(self.a, self.b))
  403.         print("| {} {} |".format(self.c, self.d))
  404.  
  405.     def inverse(self):
  406.         """
  407.        if invertible, returns the inverse matrix; else returns None
  408.        """
  409.         if self.isInvert():
  410.             a_invert = self.d / self.determinant
  411.             b_invert = (self.b * -1) / self.determinant
  412.             c_invert = (self.c * -1) / self.determinant
  413.             d_invert = self.a / self.determinant
  414.             return Matrix(a_invert, b_invert, c_invert, d_invert)
  415.         else:
  416.             return None
  417.  
  418.     def eigenvalue(self):
  419.         """
  420.        if real e-values exist, returns them as a tuple with two floats; else returns a tuple with 2 ComplexNum objects;
  421.        the formulas came from plugging parts of the characteristic equation of 2x2 matrix into the quadratic formula
  422.        """
  423.         import math
  424.         d = (self.a ** 2) - (2*self.a*self.d) + (4*self.b*self.c) + (self.d ** 2)
  425.         if d < 0:
  426.             # returns complex roots as tuple of ComplexNum objects
  427.             d= math.sqrt(-1 * d)
  428.             eigen1 = ComplexNum((self.a + self.d) / 2,
  429.                                 d / 2)
  430.             eigen2 = ComplexNum((self.a + self.d) / 2,
  431.                                 d / -2)
  432.             return eigen1, eigen2
  433.  
  434.         else:
  435.             # returns real roots as tuple of floats
  436.             d = math.sqrt(d)
  437.             eigen1 = 0.5*((self.a + self.d) + d)
  438.             eigen2 = 0.5*((self.a + self.d) - d)
  439.             return eigen1, eigen2
  440.  
  441.     def __add__(self, other):
  442.         return Matrix(self.a + other.a,
  443.                       self.b + other.b,
  444.                       self.c + other.c,
  445.                       self.d + other.d)
  446.  
  447.     def __sub__(self, other):
  448.         return Matrix(self.a - other.a,
  449.                       self.b - other.b,
  450.                       self.c - other.c,
  451.                       self.d - other.d)
  452.  
  453.     def __mul__(self, other):
  454.         return Matrix(self.a * other.a + self.b * other.c,
  455.                       self.a * other.b + self.b * other.d,
  456.                       self.c * other.a + self.d * other.c,
  457.                       self.c * other.b + self.d * other.d)
  458.  
  459.     def __str__(self):
  460.         """
  461.        prints out the matrix with format
  462.        | a b |
  463.        | c d |
  464.        """
  465.         return "| {} {} |\n| {} {} |".format(self.a, self.b, self.c, self.d)
  466.  
  467. class ComplexNum():
  468.     """
  469.    creates a complex number of the form a + bi, where i represents sqrt(-1)
  470.    """
  471.     def __init__(self, a, b):
  472.         self.a = float(a)
  473.         self.b = float(b)
  474.  
  475.     def __add__(self, other):
  476.         return ComplexNum(self.a + other.a,
  477.                           self.b + other.b)
  478.  
  479.     def __sub__(self, other):
  480.         return ComplexNum(self.a - other.a,
  481.                           self.b - other.b)
  482.  
  483.     def __mul__(self, other):
  484.         return ComplexNum(self.a * other.a - self.b * other.b,
  485.                           self.a * other.b + self.b * other.a)
  486.  
  487.     def __str__(self):
  488.         return "{} + {}i".format(self.a, self.b)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement