How to use other method in Slash

Best Python code snippet using slash

Vec3d.py

Source:Vec3d.py Github

copy

Full Screen

1########################################################################2import operator3import math4class Vec3d(object):5 """3d vector class, supports vector and scalar operators,6 and also provides a bunch of high level functions.7 reproduced from the vec2d class on the pygame wiki site.8 """9 __slots__ = ['x', 'y', 'z']10 def __init__(self, x_or_triple, y=None, z=None):11 if y is None:12 self.x = x_or_triple[0]13 self.y = x_or_triple[1]14 self.z = x_or_triple[2]15 else:16 self.x = x_or_triple17 self.y = y18 self.z = z19 def __len__(self):20 return 321 def __getitem__(self, key):22 if key == 0:23 return self.x24 elif key == 1:25 return self.y26 elif key == 2:27 return self.z28 else:29 raise IndexError("Invalid subscript " + str(key) + " to Vec3d")30 def __setitem__(self, key, value):31 if key == 0:32 self.x = value33 elif key == 1:34 self.y = value35 elif key == 2:36 self.z = value37 else:38 raise IndexError("Invalid subscript " + str(key) + " to Vec3d")39 # String representaion (for debugging)40 def __repr__(self):41 return 'Vec3d(%s, %s, %s)' % (self.x, self.y, self.z)42 # Comparison43 def __eq__(self, other):44 if hasattr(other, "__getitem__") and len(other) == 3:45 return self.x == other[0] and self.y == other[1] and self.z == other[2]46 else:47 return False48 def __ne__(self, other):49 if hasattr(other, "__getitem__") and len(other) == 3:50 return self.x != other[0] or self.y != other[1] or self.z != other[2]51 else:52 return True53 def __nonzero__(self):54 return self.x or self.y or self.z55 # Generic operator handlers56 def _o2(self, other, f):57 "Any two-operator operation where the left operand is a Vec3d"58 if isinstance(other, Vec3d):59 return Vec3d(f(self.x, other.x),60 f(self.y, other.y),61 f(self.z, other.z))62 elif (hasattr(other, "__getitem__")):63 return Vec3d(f(self.x, other[0]),64 f(self.y, other[1]),65 f(self.z, other[2]))66 else:67 return Vec3d(f(self.x, other),68 f(self.y, other),69 f(self.z, other))70 def _r_o2(self, other, f):71 "Any two-operator operation where the right operand is a Vec3d"72 if (hasattr(other, "__getitem__")):73 return Vec3d(f(other[0], self.x),74 f(other[1], self.y),75 f(other[2], self.z))76 else:77 return Vec3d(f(other, self.x),78 f(other, self.y),79 f(other, self.z))80 def _io(self, other, f):81 "inplace operator"82 if (hasattr(other, "__getitem__")):83 self.x = f(self.x, other[0])84 self.y = f(self.y, other[1])85 self.z = f(self.z, other[2])86 else:87 self.x = f(self.x, other)88 self.y = f(self.y, other)89 self.z = f(self.z, other)90 return self91 # Addition92 def __add__(self, other):93 if isinstance(other, Vec3d):94 return Vec3d(self.x + other.x, self.y + other.y, self.z + other.z)95 elif hasattr(other, "__getitem__"):96 return Vec3d(self.x + other[0], self.y + other[1], self.z + other[2])97 else:98 return Vec3d(self.x + other, self.y + other, self.z + other)99 __radd__ = __add__100 def __iadd__(self, other):101 if isinstance(other, Vec3d):102 self.x += other.x103 self.y += other.y104 self.z += other.z105 elif hasattr(other, "__getitem__"):106 self.x += other[0]107 self.y += other[1]108 self.z += other[2]109 else:110 self.x += other111 self.y += other112 self.z += other113 return self114 # Subtraction115 def __sub__(self, other):116 if isinstance(other, Vec3d):117 return Vec3d(self.x - other.x, self.y - other.y, self.z - other.z)118 elif (hasattr(other, "__getitem__")):119 return Vec3d(self.x - other[0], self.y - other[1], self.z - other[2])120 else:121 return Vec3d(self.x - other, self.y - other, self.z - other)122 def __rsub__(self, other):123 if isinstance(other, Vec3d):124 return Vec3d(other.x - self.x, other.y - self.y, other.z - self.z)125 if (hasattr(other, "__getitem__")):126 return Vec3d(other[0] - self.x, other[1] - self.y, other[2] - self.z)127 else:128 return Vec3d(other - self.x, other - self.y, other - self.z)129 def __isub__(self, other):130 if isinstance(other, Vec3d):131 self.x -= other.x132 self.y -= other.y133 self.z -= other.z134 elif (hasattr(other, "__getitem__")):135 self.x -= other[0]136 self.y -= other[1]137 self.z -= other[2]138 else:139 self.x -= other140 self.y -= other141 self.z -= other142 return self143 # Multiplication144 def __mul__(self, other):145 if isinstance(other, Vec3d):146 return Vec3d(self.x * other.x, self.y * other.y, self.z * other.z)147 if (hasattr(other, "__getitem__")):148 return Vec3d(self.x * other[0], self.y * other[1], self.z * other[2])149 else:150 return Vec3d(self.x * other, self.y * other, self.z * other)151 __rmul__ = __mul__152 def __imul__(self, other):153 if isinstance(other, Vec3d):154 self.x *= other.x155 self.y *= other.y156 self.z *= other.z157 elif (hasattr(other, "__getitem__")):158 self.x *= other[0]159 self.y *= other[1]160 self.z *= other[2]161 else:162 self.x *= other163 self.y *= other164 self.z *= other165 return self166 # Division167 def __div__(self, other):168 return self._o2(other, operator.div)169 def __rdiv__(self, other):170 return self._r_o2(other, operator.div)171 def __idiv__(self, other):172 return self._io(other, operator.div)173 def __floordiv__(self, other):174 return self._o2(other, operator.floordiv)175 def __rfloordiv__(self, other):176 return self._r_o2(other, operator.floordiv)177 def __ifloordiv__(self, other):178 return self._io(other, operator.floordiv)179 def __truediv__(self, other):180 return self._o2(other, operator.truediv)181 def __rtruediv__(self, other):182 return self._r_o2(other, operator.truediv)183 def __itruediv__(self, other):184 return self._io(other, operator.floordiv)185 # Modulo186 def __mod__(self, other):187 return self._o2(other, operator.mod)188 def __rmod__(self, other):189 return self._r_o2(other, operator.mod)190 def __divmod__(self, other):191 return self._o2(other, operator.divmod)192 def __rdivmod__(self, other):193 return self._r_o2(other, operator.divmod)194 # Exponentation195 def __pow__(self, other):196 return self._o2(other, operator.pow)197 def __rpow__(self, other):198 return self._r_o2(other, operator.pow)199 # Bitwise operators200 def __lshift__(self, other):201 return self._o2(other, operator.lshift)202 def __rlshift__(self, other):203 return self._r_o2(other, operator.lshift)204 def __rshift__(self, other):205 return self._o2(other, operator.rshift)206 def __rrshift__(self, other):207 return self._r_o2(other, operator.rshift)208 def __and__(self, other):209 return self._o2(other, operator.and_)210 __rand__ = __and__211 def __or__(self, other):212 return self._o2(other, operator.or_)213 __ror__ = __or__214 def __xor__(self, other):215 return self._o2(other, operator.xor)216 __rxor__ = __xor__217 # Unary operations218 def __neg__(self):219 return Vec3d(operator.neg(self.x), operator.neg(self.y), operator.neg(self.z))220 def __pos__(self):221 return Vec3d(operator.pos(self.x), operator.pos(self.y), operator.pos(self.z))222 def __abs__(self):223 return Vec3d(abs(self.x), abs(self.y), abs(self.z))224 def __invert__(self):225 return Vec3d(-self.x, -self.y, -self.z)226 # vectory functions227 def get_length_sqrd(self):228 return self.x ** 2 + self.y ** 2 + self.z ** 2229 def get_length(self):230 return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)231 def __setlength(self, value):232 length = self.get_length()233 self.x *= value / length234 self.y *= value / length235 self.z *= value / length236 length = property(get_length, __setlength, None, "gets or sets the magnitude of the vector")237 def rotate_around_z(self, angle_degrees):238 radians = math.radians(angle_degrees)239 cos = math.cos(radians)240 sin = math.sin(radians)241 x = self.x * cos - self.y * sin242 y = self.x * sin + self.y * cos243 self.x = x244 self.y = y245 def rotate_around_x(self, angle_degrees):246 radians = math.radians(angle_degrees)247 cos = math.cos(radians)248 sin = math.sin(radians)249 y = self.y * cos - self.z * sin250 z = self.y * sin + self.z * cos251 self.y = y252 self.z = z253 def rotate_around_y(self, angle_degrees):254 radians = math.radians(angle_degrees)255 cos = math.cos(radians)256 sin = math.sin(radians)257 z = self.z * cos - self.x * sin258 x = self.z * sin + self.x * cos259 self.z = z260 self.x = x261 def rotated_around_z(self, angle_degrees):262 radians = math.radians(angle_degrees)263 cos = math.cos(radians)264 sin = math.sin(radians)265 x = self.x * cos - self.y * sin266 y = self.x * sin + self.y * cos267 return Vec3d(x, y, self.z)268 def rotated_around_x(self, angle_degrees):269 radians = math.radians(angle_degrees)270 cos = math.cos(radians)271 sin = math.sin(radians)272 y = self.y * cos - self.z * sin273 z = self.y * sin + self.z * cos274 return Vec3d(self.x, y, z)275 def rotated_around_y(self, angle_degrees):276 radians = math.radians(angle_degrees)277 cos = math.cos(radians)278 sin = math.sin(radians)279 z = self.z * cos - self.x * sin280 x = self.z * sin + self.x * cos281 return Vec3d(x, self.y, z)282 def get_angle_around_z(self):283 if (self.get_length_sqrd() == 0):284 return 0285 return math.degrees(math.atan2(self.y, self.x))286 def __setangle_around_z(self, angle_degrees):287 self.x = math.sqrt(self.x ** 2 + self.y ** 2)288 self.y = 0289 self.rotate_around_z(angle_degrees)290 angle_around_z = property(get_angle_around_z, __setangle_around_z, None,291 "gets or sets the angle of a vector in the XY plane")292 def get_angle_around_x(self):293 if (self.get_length_sqrd() == 0):294 return 0295 return math.degrees(math.atan2(self.z, self.y))296 def __setangle_around_x(self, angle_degrees):297 self.y = math.sqrt(self.y ** 2 + self.z ** 2)298 self.z = 0299 self.rotate_around_x(angle_degrees)300 angle_around_x = property(get_angle_around_x, __setangle_around_x, None,301 "gets or sets the angle of a vector in the YZ plane")302 def get_angle_around_y(self):303 if (self.get_length_sqrd() == 0):304 return 0305 return math.degrees(math.atan2(self.x, self.z))306 def __setangle_around_y(self, angle_degrees):307 self.z = math.sqrt(self.z ** 2 + self.x ** 2)308 self.x = 0309 self.rotate_around_y(angle_degrees)310 angle_around_y = property(get_angle_around_y, __setangle_around_y, None,311 "gets or sets the angle of a vector in the ZX plane")312 def get_angle_between(self, other):313 v1 = self.normalized()314 v2 = Vec3d(other)315 v2.normalize_return_length()316 return math.degrees(math.acos(v1.dot(v2)))317 def normalized(self):318 length = self.length319 if length != 0:320 return self / length321 return Vec3d(self)322 def normalize_return_length(self):323 length = self.length324 if length != 0:325 self.x /= length326 self.y /= length327 self.z /= length328 return length329 def dot(self, other):330 return float(self.x * other[0] + self.y * other[1] + self.z * other[2])331 def get_distance(self, other):332 return math.sqrt((self.x - other[0]) ** 2 + (self.y - other[1]) ** 2 + (self.z - other[2]) ** 2)333 def get_dist_sqrd(self, other):334 return (self.x - other[0]) ** 2 + (self.y - other[1]) ** 2 + (self.z - other[2]) ** 2335 def projection(self, other):336 other_length_sqrd = other[0] * other[0] + other[1] * other[1] + other[2] * other[2]337 projected_length_times_other_length = self.dot(other)338 return other * (projected_length_times_other_length / other_length_sqrd)339 def cross(self, other):340 return Vec3d(self.y * other[2] - self.z * other[1], self.z * other[0] - self.x * other[2],341 self.x * other[1] - self.y * other[0])342 def interpolate_to(self, other, range):343 return Vec3d(self.x + (other[0] - self.x) * range, self.y + (other[1] - self.y) * range,344 self.z + (other[2] - self.z) * range)345 def convert_to_basis(self, x_vector, y_vector, z_vector):346 return Vec3d(self.dot(x_vector) / x_vector.get_length_sqrd(),347 self.dot(y_vector) / y_vector.get_length_sqrd(),348 self.dot(z_vector) / z_vector.get_length_sqrd())349 def __getstate__(self):350 return [self.x, self.y, self.z]351 def __setstate__(self, dict):352 self.x, self.y, self.z = dict353########################################################################354## Unit Testing ##355########################################################################356if __name__ == "__main__":357 import unittest358 import pickle359 ####################################################################360 class UnitTestVec3d(unittest.TestCase):361 def setUp(self):362 pass363 def testCreationAndAccess(self):364 v = Vec3d(111, 222, 333)365 self.assert_(v.x == 111 and v.y == 222 and v.z == 333)366 v.x = 333367 v[1] = 444368 v.z = 555369 self.assert_(v[0] == 333 and v[1] == 444 and v[2] == 555)370 def testMath(self):371 v = Vec3d(111, 222, 333)372 self.assertEqual(v + 1, Vec3d(112, 223, 334))373 self.assert_(v - 2 == [109, 220, 331])374 self.assert_(v * 3 == (333, 666, 999))375 self.assert_(v / 2.0 == Vec3d(55.5, 111, 166.5))376 self.assert_(v / 2 == (55, 111, 166))377 self.assert_(v ** Vec3d(2, 3, 2) == [12321, 10941048, 110889])378 self.assert_(v + [-11, 78, 67] == Vec3d(100, 300, 400))379 self.assert_(v / [11, 2, 9] == [10, 111, 37])380 def testReverseMath(self):381 v = Vec3d(111, 222, 333)382 self.assert_(1 + v == Vec3d(112, 223, 334))383 self.assert_(2 - v == [-109, -220, -331])384 self.assert_(3 * v == (333, 666, 999))385 self.assert_([222, 999, 666] / v == [2, 4, 2])386 self.assert_([111, 222, 333] ** Vec3d(2, 3, 2) == [12321, 10941048, 110889])387 self.assert_([-11, 78, 67] + v == Vec3d(100, 300, 400))388 def testUnary(self):389 v = Vec3d(111, 222, 333)390 v = -v391 self.assert_(v == [-111, -222, -333])392 v = abs(v)393 self.assert_(v == [111, 222, 333])394 def testLength(self):395 v = Vec3d(1, 4, 8)396 self.assert_(v.length == 9)397 self.assert_(v.get_length_sqrd() == 81)398 self.assert_(v.normalize_return_length() == 9)399 self.assert_(v.length == 1)400 v.length = 9401 self.assert_(v == Vec3d(1, 4, 8))402 v2 = Vec3d(10, -2, 12)403 self.assert_(v.get_distance(v2) == (v - v2).get_length())404 def testAngles(self):405 v = Vec3d(0, 3, -3)406 self.assertEquals(v.angle_around_y, 180)407 self.assertEquals(v.angle_around_x, -45)408 self.assertEquals(v.angle_around_z, 90)409 v2 = Vec3d(v)410 v.rotate_around_x(-90)411 self.assertEqual(v.get_angle_between(v2), 90)412 v = Vec3d(v2)413 v.rotate_around_y(-90)414 self.assertAlmostEqual(v.get_angle_between(v2), 60)415 v = Vec3d(v2)416 v.rotate_around_z(-90)417 self.assertAlmostEqual(v.get_angle_between(v2), 60)418 v2.angle_around_z -= 90419 self.assertEqual(v.length, v2.length)420 self.assertEquals(v2.angle_around_z, 0)421 self.assertEqual(v2, [3, 0, -3])422 self.assert_((v - v2).length < .00001)423 self.assertEqual(v.length, v2.length)424 v2.rotate_around_y(300)425 self.assertAlmostEquals(v.get_angle_between(v2), 60)426 v2.rotate_around_y(v2.get_angle_between(v))427 angle = v.get_angle_between(v2)428 self.assertAlmostEquals(v.get_angle_between(v2), 0)429 def testHighLevel(self):430 basis0 = Vec3d(5.0, 0, 0)431 basis1 = Vec3d(0, .5, 0)432 basis2 = Vec3d(0, 0, 3)433 v = Vec3d(10, 1, 6)434 self.assert_(v.convert_to_basis(basis0, basis1, basis2) == [2, 2, 2])435 self.assert_(v.projection(basis0) == (10, 0, 0))436 self.assert_(basis0.dot(basis1) == 0)437 def testCross(self):438 lhs = Vec3d(1, .5, 3)439 rhs = Vec3d(4, 6, 1)440 self.assert_(lhs.cross(rhs) == [-17.5, 11, 4])441 def testComparison(self):442 int_vec = Vec3d(3, -2, 4)443 flt_vec = Vec3d(3.0, -2.0, 4.0)444 zero_vec = Vec3d(0, 0, 0)445 self.assert_(int_vec == flt_vec)446 self.assert_(int_vec != zero_vec)447 self.assert_((flt_vec == zero_vec) == False)448 self.assert_((flt_vec != int_vec) == False)449 self.assert_(int_vec == (3, -2, 4))450 self.assert_(int_vec != [0, 0, 0])451 self.assert_(int_vec != 5)452 self.assert_(int_vec != [3, -2, 4, 15])453 def testInplace(self):454 inplace_vec = Vec3d(5, 13, 17)455 inplace_ref = inplace_vec456 inplace_src = Vec3d(inplace_vec)457 inplace_vec *= .5458 inplace_vec += .5459 inplace_vec /= (3, 6, 9)460 inplace_vec += Vec3d(-1, -1, -1)461 alternate = (inplace_src * .5 + .5) / Vec3d(3, 6, 9) + [-1, -1, -1]462 self.assertEquals(inplace_vec, inplace_ref)463 self.assertEquals(inplace_vec, alternate)464 def testPickle(self):465 testvec = Vec3d(5, .3, 8.6)466 testvec_str = pickle.dumps(testvec)467 loaded_vec = pickle.loads(testvec_str)468 self.assertEquals(testvec, loaded_vec)469 ####################################################################470 unittest.main()...

Full Screen

Full Screen

test_binop.py

Source:test_binop.py Github

copy

Full Screen

1"""Tests for binary operators on subtypes of built-in types."""23import unittest4from test import test_support56def gcd(a, b):7 """Greatest common divisor using Euclid's algorithm."""8 while a:9 a, b = b%a, a10 return b1112def isint(x):13 """Test whether an object is an instance of int or long."""14 return isinstance(x, int) or isinstance(x, long)1516def isnum(x):17 """Test whether an object is an instance of a built-in numeric type."""18 for T in int, long, float, complex:19 if isinstance(x, T):20 return 121 return 02223def isRat(x):24 """Test wheter an object is an instance of the Rat class."""25 return isinstance(x, Rat)2627class Rat(object):2829 """Rational number implemented as a normalized pair of longs."""3031 __slots__ = ['_Rat__num', '_Rat__den']3233 def __init__(self, num=0L, den=1L):34 """Constructor: Rat([num[, den]]).3536 The arguments must be ints or longs, and default to (0, 1)."""37 if not isint(num):38 raise TypeError, "Rat numerator must be int or long (%r)" % num39 if not isint(den):40 raise TypeError, "Rat denominator must be int or long (%r)" % den41 # But the zero is always on42 if den == 0:43 raise ZeroDivisionError, "zero denominator"44 g = gcd(den, num)45 self.__num = long(num//g)46 self.__den = long(den//g)4748 def _get_num(self):49 """Accessor function for read-only 'num' attribute of Rat."""50 return self.__num51 num = property(_get_num, None)5253 def _get_den(self):54 """Accessor function for read-only 'den' attribute of Rat."""55 return self.__den56 den = property(_get_den, None)5758 def __repr__(self):59 """Convert a Rat to an string resembling a Rat constructor call."""60 return "Rat(%d, %d)" % (self.__num, self.__den)6162 def __str__(self):63 """Convert a Rat to a string resembling a decimal numeric value."""64 return str(float(self))6566 def __float__(self):67 """Convert a Rat to a float."""68 return self.__num*1.0/self.__den6970 def __int__(self):71 """Convert a Rat to an int; self.den must be 1."""72 if self.__den == 1:73 try:74 return int(self.__num)75 except OverflowError:76 raise OverflowError, ("%s too large to convert to int" %77 repr(self))78 raise ValueError, "can't convert %s to int" % repr(self)7980 def __long__(self):81 """Convert a Rat to an long; self.den must be 1."""82 if self.__den == 1:83 return long(self.__num)84 raise ValueError, "can't convert %s to long" % repr(self)8586 def __add__(self, other):87 """Add two Rats, or a Rat and a number."""88 if isint(other):89 other = Rat(other)90 if isRat(other):91 return Rat(self.__num*other.__den + other.__num*self.__den,92 self.__den*other.__den)93 if isnum(other):94 return float(self) + other95 return NotImplemented9697 __radd__ = __add__9899 def __sub__(self, other):100 """Subtract two Rats, or a Rat and a number."""101 if isint(other):102 other = Rat(other)103 if isRat(other):104 return Rat(self.__num*other.__den - other.__num*self.__den,105 self.__den*other.__den)106 if isnum(other):107 return float(self) - other108 return NotImplemented109110 def __rsub__(self, other):111 """Subtract two Rats, or a Rat and a number (reversed args)."""112 if isint(other):113 other = Rat(other)114 if isRat(other):115 return Rat(other.__num*self.__den - self.__num*other.__den,116 self.__den*other.__den)117 if isnum(other):118 return other - float(self)119 return NotImplemented120121 def __mul__(self, other):122 """Multiply two Rats, or a Rat and a number."""123 if isRat(other):124 return Rat(self.__num*other.__num, self.__den*other.__den)125 if isint(other):126 return Rat(self.__num*other, self.__den)127 if isnum(other):128 return float(self)*other129 return NotImplemented130131 __rmul__ = __mul__132133 def __truediv__(self, other):134 """Divide two Rats, or a Rat and a number."""135 if isRat(other):136 return Rat(self.__num*other.__den, self.__den*other.__num)137 if isint(other):138 return Rat(self.__num, self.__den*other)139 if isnum(other):140 return float(self) / other141 return NotImplemented142143 __div__ = __truediv__144145 def __rtruediv__(self, other):146 """Divide two Rats, or a Rat and a number (reversed args)."""147 if isRat(other):148 return Rat(other.__num*self.__den, other.__den*self.__num)149 if isint(other):150 return Rat(other*self.__den, self.__num)151 if isnum(other):152 return other / float(self)153 return NotImplemented154155 __rdiv__ = __rtruediv__156157 def __floordiv__(self, other):158 """Divide two Rats, returning the floored result."""159 if isint(other):160 other = Rat(other)161 elif not isRat(other):162 return NotImplemented163 x = self/other164 return x.__num // x.__den165166 def __rfloordiv__(self, other):167 """Divide two Rats, returning the floored result (reversed args)."""168 x = other/self169 return x.__num // x.__den170171 def __divmod__(self, other):172 """Divide two Rats, returning quotient and remainder."""173 if isint(other):174 other = Rat(other)175 elif not isRat(other):176 return NotImplemented177 x = self//other178 return (x, self - other * x)179180 def __rdivmod__(self, other):181 """Divide two Rats, returning quotient and remainder (reversed args)."""182 if isint(other):183 other = Rat(other)184 elif not isRat(other):185 return NotImplemented186 return divmod(other, self)187188 def __mod__(self, other):189 """Take one Rat modulo another."""190 return divmod(self, other)[1]191192 def __rmod__(self, other):193 """Take one Rat modulo another (reversed args)."""194 return divmod(other, self)[1]195196 def __eq__(self, other):197 """Compare two Rats for equality."""198 if isint(other):199 return self.__den == 1 and self.__num == other200 if isRat(other):201 return self.__num == other.__num and self.__den == other.__den202 if isnum(other):203 return float(self) == other204 return NotImplemented205206 def __ne__(self, other):207 """Compare two Rats for inequality."""208 return not self == other209210 # Silence Py3k warning211 __hash__ = None212213class RatTestCase(unittest.TestCase):214 """Unit tests for Rat class and its support utilities."""215216 def test_gcd(self):217 self.assertEqual(gcd(10, 12), 2)218 self.assertEqual(gcd(10, 15), 5)219 self.assertEqual(gcd(10, 11), 1)220 self.assertEqual(gcd(100, 15), 5)221 self.assertEqual(gcd(-10, 2), -2)222 self.assertEqual(gcd(10, -2), 2)223 self.assertEqual(gcd(-10, -2), -2)224 for i in range(1, 20):225 for j in range(1, 20):226 self.assertTrue(gcd(i, j) > 0)227 self.assertTrue(gcd(-i, j) < 0)228 self.assertTrue(gcd(i, -j) > 0)229 self.assertTrue(gcd(-i, -j) < 0)230231 def test_constructor(self):232 a = Rat(10, 15)233 self.assertEqual(a.num, 2)234 self.assertEqual(a.den, 3)235 a = Rat(10L, 15L)236 self.assertEqual(a.num, 2)237 self.assertEqual(a.den, 3)238 a = Rat(10, -15)239 self.assertEqual(a.num, -2)240 self.assertEqual(a.den, 3)241 a = Rat(-10, 15)242 self.assertEqual(a.num, -2)243 self.assertEqual(a.den, 3)244 a = Rat(-10, -15)245 self.assertEqual(a.num, 2)246 self.assertEqual(a.den, 3)247 a = Rat(7)248 self.assertEqual(a.num, 7)249 self.assertEqual(a.den, 1)250 try:251 a = Rat(1, 0)252 except ZeroDivisionError:253 pass254 else:255 self.fail("Rat(1, 0) didn't raise ZeroDivisionError")256 for bad in "0", 0.0, 0j, (), [], {}, None, Rat, unittest:257 try:258 a = Rat(bad)259 except TypeError:260 pass261 else:262 self.fail("Rat(%r) didn't raise TypeError" % bad)263 try:264 a = Rat(1, bad)265 except TypeError:266 pass267 else:268 self.fail("Rat(1, %r) didn't raise TypeError" % bad)269270 def test_add(self):271 self.assertEqual(Rat(2, 3) + Rat(1, 3), 1)272 self.assertEqual(Rat(2, 3) + 1, Rat(5, 3))273 self.assertEqual(1 + Rat(2, 3), Rat(5, 3))274 self.assertEqual(1.0 + Rat(1, 2), 1.5)275 self.assertEqual(Rat(1, 2) + 1.0, 1.5)276277 def test_sub(self):278 self.assertEqual(Rat(7, 2) - Rat(7, 5), Rat(21, 10))279 self.assertEqual(Rat(7, 5) - 1, Rat(2, 5))280 self.assertEqual(1 - Rat(3, 5), Rat(2, 5))281 self.assertEqual(Rat(3, 2) - 1.0, 0.5)282 self.assertEqual(1.0 - Rat(1, 2), 0.5)283284 def test_mul(self):285 self.assertEqual(Rat(2, 3) * Rat(5, 7), Rat(10, 21))286 self.assertEqual(Rat(10, 3) * 3, 10)287 self.assertEqual(3 * Rat(10, 3), 10)288 self.assertEqual(Rat(10, 5) * 0.5, 1.0)289 self.assertEqual(0.5 * Rat(10, 5), 1.0)290291 def test_div(self):292 self.assertEqual(Rat(10, 3) / Rat(5, 7), Rat(14, 3))293 self.assertEqual(Rat(10, 3) / 3, Rat(10, 9))294 self.assertEqual(2 / Rat(5), Rat(2, 5))295 self.assertEqual(3.0 * Rat(1, 2), 1.5)296 self.assertEqual(Rat(1, 2) * 3.0, 1.5)297298 def test_floordiv(self):299 self.assertEqual(Rat(10) // Rat(4), 2)300 self.assertEqual(Rat(10, 3) // Rat(4, 3), 2)301 self.assertEqual(Rat(10) // 4, 2)302 self.assertEqual(10 // Rat(4), 2)303304 def test_eq(self):305 self.assertEqual(Rat(10), Rat(20, 2))306 self.assertEqual(Rat(10), 10)307 self.assertEqual(10, Rat(10))308 self.assertEqual(Rat(10), 10.0)309 self.assertEqual(10.0, Rat(10))310311 def test_future_div(self):312 exec future_test313314 # XXX Ran out of steam; TO DO: divmod, div, future division315316future_test = """317from __future__ import division318self.assertEqual(Rat(10, 3) / Rat(5, 7), Rat(14, 3))319self.assertEqual(Rat(10, 3) / 3, Rat(10, 9))320self.assertEqual(2 / Rat(5), Rat(2, 5))321self.assertEqual(3.0 * Rat(1, 2), 1.5)322self.assertEqual(Rat(1, 2) * 3.0, 1.5)323self.assertEqual(eval('1/2'), 0.5)324"""325326def test_main():327 test_support.run_unittest(RatTestCase)328329330if __name__ == "__main__": ...

Full Screen

Full Screen

set.py

Source:set.py Github

copy

Full Screen

1# Copyright (C) 2003-2007, 2009, 2010 Nominum, Inc.2#3# Permission to use, copy, modify, and distribute this software and its4# documentation for any purpose with or without fee is hereby granted,5# provided that the above copyright notice and this permission notice6# appear in all copies.7#8# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES9# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF10# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR11# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES12# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN13# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT14# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.15"""A simple Set class."""16class Set(object):17 """A simple set class.18 Sets are not in Python until 2.3, and rdata are not immutable so19 we cannot use sets.Set anyway. This class implements subset of20 the 2.3 Set interface using a list as the container.21 @ivar items: A list of the items which are in the set22 @type items: list"""23 __slots__ = ['items']24 def __init__(self, items=None):25 """Initialize the set.26 @param items: the initial set of items27 @type items: any iterable or None28 """29 self.items = []30 if not items is None:31 for item in items:32 self.add(item)33 def __repr__(self):34 return "dns.simpleset.Set(%s)" % repr(self.items)35 def add(self, item):36 """Add an item to the set."""37 if not item in self.items:38 self.items.append(item)39 def remove(self, item):40 """Remove an item from the set."""41 self.items.remove(item)42 def discard(self, item):43 """Remove an item from the set if present."""44 try:45 self.items.remove(item)46 except ValueError:47 pass48 def _clone(self):49 """Make a (shallow) copy of the set.50 There is a 'clone protocol' that subclasses of this class51 should use. To make a copy, first call your super's _clone()52 method, and use the object returned as the new instance. Then53 make shallow copies of the attributes defined in the subclass.54 This protocol allows us to write the set algorithms that55 return new instances (e.g. union) once, and keep using them in56 subclasses.57 """58 cls = self.__class__59 obj = cls.__new__(cls)60 obj.items = list(self.items)61 return obj62 def __copy__(self):63 """Make a (shallow) copy of the set."""64 return self._clone()65 def copy(self):66 """Make a (shallow) copy of the set."""67 return self._clone()68 def union_update(self, other):69 """Update the set, adding any elements from other which are not70 already in the set.71 @param other: the collection of items with which to update the set72 @type other: Set object73 """74 if not isinstance(other, Set):75 raise ValueError('other must be a Set instance')76 if self is other:77 return78 for item in other.items:79 self.add(item)80 def intersection_update(self, other):81 """Update the set, removing any elements from other which are not82 in both sets.83 @param other: the collection of items with which to update the set84 @type other: Set object85 """86 if not isinstance(other, Set):87 raise ValueError('other must be a Set instance')88 if self is other:89 return90 # we make a copy of the list so that we can remove items from91 # the list without breaking the iterator.92 for item in list(self.items):93 if item not in other.items:94 self.items.remove(item)95 def difference_update(self, other):96 """Update the set, removing any elements from other which are in97 the set.98 @param other: the collection of items with which to update the set99 @type other: Set object100 """101 if not isinstance(other, Set):102 raise ValueError('other must be a Set instance')103 if self is other:104 self.items = []105 else:106 for item in other.items:107 self.discard(item)108 def union(self, other):109 """Return a new set which is the union of I{self} and I{other}.110 @param other: the other set111 @type other: Set object112 @rtype: the same type as I{self}113 """114 obj = self._clone()115 obj.union_update(other)116 return obj117 def intersection(self, other):118 """Return a new set which is the intersection of I{self} and I{other}.119 @param other: the other set120 @type other: Set object121 @rtype: the same type as I{self}122 """123 obj = self._clone()124 obj.intersection_update(other)125 return obj126 def difference(self, other):127 """Return a new set which I{self} - I{other}, i.e. the items128 in I{self} which are not also in I{other}.129 @param other: the other set130 @type other: Set object131 @rtype: the same type as I{self}132 """133 obj = self._clone()134 obj.difference_update(other)135 return obj136 def __or__(self, other):137 return self.union(other)138 def __and__(self, other):139 return self.intersection(other)140 def __add__(self, other):141 return self.union(other)142 def __sub__(self, other):143 return self.difference(other)144 def __ior__(self, other):145 self.union_update(other)146 return self147 def __iand__(self, other):148 self.intersection_update(other)149 return self150 def __iadd__(self, other):151 self.union_update(other)152 return self153 def __isub__(self, other):154 self.difference_update(other)155 return self156 def update(self, other):157 """Update the set, adding any elements from other which are not158 already in the set.159 @param other: the collection of items with which to update the set160 @type other: any iterable type"""161 for item in other:162 self.add(item)163 def clear(self):164 """Make the set empty."""165 self.items = []166 def __eq__(self, other):167 # Yes, this is inefficient but the sets we're dealing with are168 # usually quite small, so it shouldn't hurt too much.169 for item in self.items:170 if not item in other.items:171 return False172 for item in other.items:173 if not item in self.items:174 return False175 return True176 def __ne__(self, other):177 return not self.__eq__(other)178 def __len__(self):179 return len(self.items)180 def __iter__(self):181 return iter(self.items)182 def __getitem__(self, i):183 return self.items[i]184 def __delitem__(self, i):185 del self.items[i]186 def __getslice__(self, i, j):187 return self.items[i:j]188 def __delslice__(self, i, j):189 del self.items[i:j]190 def issubset(self, other):191 """Is I{self} a subset of I{other}?192 @rtype: bool193 """194 if not isinstance(other, Set):195 raise ValueError('other must be a Set instance')196 for item in self.items:197 if not item in other.items:198 return False199 return True200 def issuperset(self, other):201 """Is I{self} a superset of I{other}?202 @rtype: bool203 """204 if not isinstance(other, Set):205 raise ValueError('other must be a Set instance')206 for item in other.items:207 if not item in self.items:208 return False...

Full Screen

Full Screen

user_array.py

Source:user_array.py Github

copy

Full Screen

1"""2Standard container-class for easy multiple-inheritance.3Try to inherit from the ndarray instead of using this class as this is not4complete.5"""6from numpy.core import array, asarray, absolute, add, subtract, multiply, \7 divide, remainder, power, left_shift, right_shift, bitwise_and, \8 bitwise_or, bitwise_xor, invert, less, less_equal, not_equal, equal, \9 greater, greater_equal, shape, reshape, arange, sin, sqrt, transpose10class container(object):11 def __init__(self, data, dtype=None, copy=True):12 self.array = array(data, dtype, copy=copy)13 def __repr__(self):14 if len(self.shape) > 0:15 return self.__class__.__name__+repr(self.array)[len("array"):]16 else:17 return self.__class__.__name__+"("+repr(self.array)+")"18 def __array__(self,t=None):19 if t: return self.array.astype(t)20 return self.array21 # Array as sequence22 def __len__(self): return len(self.array)23 def __getitem__(self, index):24 return self._rc(self.array[index])25 def __getslice__(self, i, j):26 return self._rc(self.array[i:j])27 def __setitem__(self, index, value):28 self.array[index] = asarray(value,self.dtype)29 def __setslice__(self, i, j, value):30 self.array[i:j] = asarray(value,self.dtype)31 def __abs__(self):32 return self._rc(absolute(self.array))33 def __neg__(self):34 return self._rc(-self.array)35 def __add__(self, other):36 return self._rc(self.array+asarray(other))37 __radd__ = __add__38 def __iadd__(self, other):39 add(self.array, other, self.array)40 return self41 def __sub__(self, other):42 return self._rc(self.array-asarray(other))43 def __rsub__(self, other):44 return self._rc(asarray(other)-self.array)45 def __isub__(self, other):46 subtract(self.array, other, self.array)47 return self48 def __mul__(self, other):49 return self._rc(multiply(self.array,asarray(other)))50 __rmul__ = __mul__51 def __imul__(self, other):52 multiply(self.array, other, self.array)53 return self54 def __div__(self, other):55 return self._rc(divide(self.array,asarray(other)))56 def __rdiv__(self, other):57 return self._rc(divide(asarray(other),self.array))58 def __idiv__(self, other):59 divide(self.array, other, self.array)60 return self61 def __mod__(self, other):62 return self._rc(remainder(self.array, other))63 def __rmod__(self, other):64 return self._rc(remainder(other, self.array))65 def __imod__(self, other):66 remainder(self.array, other, self.array)67 return self68 def __divmod__(self, other):69 return (self._rc(divide(self.array,other)),70 self._rc(remainder(self.array, other)))71 def __rdivmod__(self, other):72 return (self._rc(divide(other, self.array)),73 self._rc(remainder(other, self.array)))74 def __pow__(self,other):75 return self._rc(power(self.array,asarray(other)))76 def __rpow__(self,other):77 return self._rc(power(asarray(other),self.array))78 def __ipow__(self,other):79 power(self.array, other, self.array)80 return self81 def __lshift__(self,other):82 return self._rc(left_shift(self.array, other))83 def __rshift__(self,other):84 return self._rc(right_shift(self.array, other))85 def __rlshift__(self,other):86 return self._rc(left_shift(other, self.array))87 def __rrshift__(self,other):88 return self._rc(right_shift(other, self.array))89 def __ilshift__(self,other):90 left_shift(self.array, other, self.array)91 return self92 def __irshift__(self,other):93 right_shift(self.array, other, self.array)94 return self95 def __and__(self, other):96 return self._rc(bitwise_and(self.array, other))97 def __rand__(self, other):98 return self._rc(bitwise_and(other, self.array))99 def __iand__(self, other):100 bitwise_and(self.array, other, self.array)101 return self102 def __xor__(self, other):103 return self._rc(bitwise_xor(self.array, other))104 def __rxor__(self, other):105 return self._rc(bitwise_xor(other, self.array))106 def __ixor__(self, other):107 bitwise_xor(self.array, other, self.array)108 return self109 def __or__(self, other):110 return self._rc(bitwise_or(self.array, other))111 def __ror__(self, other):112 return self._rc(bitwise_or(other, self.array))113 def __ior__(self, other):114 bitwise_or(self.array, other, self.array)115 return self116 def __neg__(self):117 return self._rc(-self.array)118 def __pos__(self):119 return self._rc(self.array)120 def __abs__(self):121 return self._rc(abs(self.array))122 def __invert__(self):123 return self._rc(invert(self.array))124 def _scalarfunc(self, func):125 if len(self.shape) == 0:126 return func(self[0])127 else:128 raise TypeError, "only rank-0 arrays can be converted to Python scalars."129 def __complex__(self): return self._scalarfunc(complex)130 def __float__(self): return self._scalarfunc(float)131 def __int__(self): return self._scalarfunc(int)132 def __long__(self): return self._scalarfunc(long)133 def __hex__(self): return self._scalarfunc(hex)134 def __oct__(self): return self._scalarfunc(oct)135 def __lt__(self,other): return self._rc(less(self.array,other))136 def __le__(self,other): return self._rc(less_equal(self.array,other))137 def __eq__(self,other): return self._rc(equal(self.array,other))138 def __ne__(self,other): return self._rc(not_equal(self.array,other))139 def __gt__(self,other): return self._rc(greater(self.array,other))140 def __ge__(self,other): return self._rc(greater_equal(self.array,other))141 def copy(self): return self._rc(self.array.copy())142 def tostring(self): return self.array.tostring()143 def byteswap(self): return self._rc(self.array.byteswap())144 def astype(self, typecode): return self._rc(self.array.astype(typecode))145 def _rc(self, a):146 if len(shape(a)) == 0: return a147 else: return self.__class__(a)148 def __array_wrap__(self, *args):149 return self.__class__(args[0])150 def __setattr__(self,attr,value):151 if attr == 'array':152 object.__setattr__(self, attr, value)153 return154 try:155 self.array.__setattr__(attr, value)156 except AttributeError:157 object.__setattr__(self, attr, value)158 # Only called after other approaches fail.159 def __getattr__(self,attr):160 if (attr == 'array'):161 return object.__getattribute__(self, attr)162 return self.array.__getattribute__(attr)163#############################################################164# Test of class container165#############################################################166if __name__ == '__main__':167 temp=reshape(arange(10000),(100,100))168 ua=container(temp)169 # new object created begin test170 print dir(ua)171 print shape(ua),ua.shape # I have changed Numeric.py172 ua_small=ua[:3,:5]173 print ua_small174 ua_small[0,0]=10 # this did not change ua[0,0], which is not normal behavior175 print ua_small[0,0],ua[0,0]176 print sin(ua_small)/3.*6.+sqrt(ua_small**2)177 print less(ua_small,103),type(less(ua_small,103))178 print type(ua_small*reshape(arange(15),shape(ua_small)))179 print reshape(ua_small,(5,3))...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Slash automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful