function
stringlengths
18
3.86k
intent_category
stringlengths
5
24
def __len__(self) -> int: return len(self.bodies)
physics
def update_system(self, delta_time: float) -> None: for body1 in self.bodies: force_x = 0.0 force_y = 0.0 for body2 in self.bodies: if body1 != body2: dif_x = body2.position_x - body1.position_x dif_y = body2.position_y - body1.position_y # Calculation of the distance using Pythagoras's theorem # Extra factor due to the softening technique distance = (dif_x**2 + dif_y**2 + self.softening_factor) ** ( 1 / 2 ) # Newton's law of universal gravitation. force_x += ( self.gravitation_constant * body2.mass * dif_x / distance**3 ) force_y += ( self.gravitation_constant * body2.mass * dif_y / distance**3 ) # Update the body's velocity once all the force components have been added body1.update_velocity(force_x, force_y, delta_time * self.time_factor) # Update the positions only after all the velocities have been updated for body in self.bodies: body.update_position(delta_time * self.time_factor)
physics
def update_step( body_system: BodySystem, delta_time: float, patches: list[plt.Circle] ) -> None: # Update the positions of the bodies body_system.update_system(delta_time) # Update the positions of the patches for patch, body in zip(patches, body_system.bodies): patch.center = (body.position_x, body.position_y)
physics
def update(frame: int) -> list[plt.Circle]: update_step(body_system, DELTA_TIME, patches) return patches
physics
def example_1() -> BodySystem: position_x = 0.9700436 position_y = -0.24308753 velocity_x = 0.466203685 velocity_y = 0.43236573 bodies1 = [ Body(position_x, position_y, velocity_x, velocity_y, size=0.2, color="red"), Body(-position_x, -position_y, velocity_x, velocity_y, size=0.2, color="green"), Body(0, 0, -2 * velocity_x, -2 * velocity_y, size=0.2, color="blue"), ] return BodySystem(bodies1, time_factor=3)
physics
def example_2() -> BodySystem: moon_mass = 7.3476e22 earth_mass = 5.972e24 velocity_dif = 1022 earth_moon_distance = 384399000 gravitation_constant = 6.674e-11 # Calculation of the respective velocities so that total impulse is zero, # i.e. the two bodies together don't move moon_velocity = earth_mass * velocity_dif / (earth_mass + moon_mass) earth_velocity = moon_velocity - velocity_dif moon = Body(-earth_moon_distance, 0, 0, moon_velocity, moon_mass, 10000000, "grey") earth = Body(0, 0, 0, earth_velocity, earth_mass, 50000000, "blue") return BodySystem([earth, moon], gravitation_constant, time_factor=1000000)
physics
def example_3() -> BodySystem: bodies = [] for _ in range(10): velocity_x = random.uniform(-0.5, 0.5) velocity_y = random.uniform(-0.5, 0.5) # Bodies are created pairwise with opposite velocities so that the # total impulse remains zero bodies.append( Body( random.uniform(-0.5, 0.5), random.uniform(-0.5, 0.5), velocity_x, velocity_y, size=0.05, ) ) bodies.append( Body( random.uniform(-0.5, 0.5), random.uniform(-0.5, 0.5), -velocity_x, -velocity_y, size=0.05, ) ) return BodySystem(bodies, 0.01, 10, 0.1)
physics
def _is_matrix_spd(matrix: np.ndarray) -> bool: # Ensure matrix is square. assert np.shape(matrix)[0] == np.shape(matrix)[1] # If matrix not symmetric, exit right away. if np.allclose(matrix, matrix.T) is False: return False # Get eigenvalues and eignevectors for a symmetric matrix. eigen_values, _ = np.linalg.eigh(matrix) # Check sign of all eigenvalues. # np.all returns a value of type np.bool_ return bool(np.all(eigen_values > 0))
linear_algebra
def _create_spd_matrix(dimension: int) -> Any: random_matrix = np.random.randn(dimension, dimension) spd_matrix = np.dot(random_matrix, random_matrix.T) assert _is_matrix_spd(spd_matrix) return spd_matrix
linear_algebra
def conjugate_gradient( spd_matrix: np.ndarray, load_vector: np.ndarray, max_iterations: int = 1000, tol: float = 1e-8, ) -> Any: # Ensure proper dimensionality. assert np.shape(spd_matrix)[0] == np.shape(spd_matrix)[1] assert np.shape(load_vector)[0] == np.shape(spd_matrix)[0] assert _is_matrix_spd(spd_matrix) # Initialize solution guess, residual, search direction. x0 = np.zeros((np.shape(load_vector)[0], 1)) r0 = np.copy(load_vector) p0 = np.copy(r0) # Set initial errors in solution guess and residual. error_residual = 1e9 error_x_solution = 1e9 error = 1e9 # Set iteration counter to threshold number of iterations. iterations = 0 while error > tol: # Save this value so we only calculate the matrix-vector product once. w = np.dot(spd_matrix, p0) # The main algorithm. # Update search direction magnitude. alpha = np.dot(r0.T, r0) / np.dot(p0.T, w) # Update solution guess. x = x0 + alpha * p0 # Calculate new residual. r = r0 - alpha * w # Calculate new Krylov subspace scale. beta = np.dot(r.T, r) / np.dot(r0.T, r0) # Calculate new A conjuage search direction. p = r + beta * p0 # Calculate errors. error_residual = np.linalg.norm(r - r0) error_x_solution = np.linalg.norm(x - x0) error = np.maximum(error_residual, error_x_solution) # Update variables. x0 = np.copy(x) r0 = np.copy(r) p0 = np.copy(p) # Update number of iterations. iterations += 1 if iterations > max_iterations: break return x
linear_algebra
def test_conjugate_gradient() -> None: # Create linear system with SPD matrix and known solution x_true. dimension = 3 spd_matrix = _create_spd_matrix(dimension) x_true = np.random.randn(dimension, 1) b = np.dot(spd_matrix, x_true) # Numpy solution. x_numpy = np.linalg.solve(spd_matrix, b) # Our implementation. x_conjugate_gradient = conjugate_gradient(spd_matrix, b) # Ensure both solutions are close to x_true (and therefore one another). assert np.linalg.norm(x_numpy - x_true) <= 1e-6 assert np.linalg.norm(x_conjugate_gradient - x_true) <= 1e-6
linear_algebra
def points_to_polynomial(coordinates: list[list[int]]) -> str: if len(coordinates) == 0 or not all(len(pair) == 2 for pair in coordinates): raise ValueError("The program cannot work out a fitting polynomial.") if len({tuple(pair) for pair in coordinates}) != len(coordinates): raise ValueError("The program cannot work out a fitting polynomial.") set_x = {x for x, _ in coordinates} if len(set_x) == 1: return f"x={coordinates[0][0]}" if len(set_x) != len(coordinates): raise ValueError("The program cannot work out a fitting polynomial.") x = len(coordinates) count_of_line = 0 matrix: list[list[float]] = [] # put the x and x to the power values in a matrix while count_of_line < x: count_in_line = 0 a = coordinates[count_of_line][0] count_line: list[float] = [] while count_in_line < x: count_line.append(a ** (x - (count_in_line + 1))) count_in_line += 1 matrix.append(count_line) count_of_line += 1 count_of_line = 0 # put the y values into a vector vector: list[float] = [] while count_of_line < x: vector.append(coordinates[count_of_line][1]) count_of_line += 1 count = 0 while count < x: zahlen = 0 while zahlen < x: if count == zahlen: zahlen += 1 if zahlen == x: break bruch = matrix[zahlen][count] / matrix[count][count] for counting_columns, item in enumerate(matrix[count]): # manipulating all the values in the matrix matrix[zahlen][counting_columns] -= item * bruch # manipulating the values in the vector vector[zahlen] -= vector[count] * bruch zahlen += 1 count += 1 count = 0 # make solutions solution: list[str] = [] while count < x: solution.append(str(vector[count] / matrix[count][count])) count += 1 count = 0 solved = "f(x)=" while count < x: remove_e: list[str] = solution[count].split("E") if len(remove_e) > 1: solution[count] = f"{remove_e[0]}*10^{remove_e[1]}" solved += f"x^{x - (count + 1)}*{solution[count]}" if count + 1 != x: solved += "+" count += 1 return solved
linear_algebra
def __init__(self, components: Collection[float] | None = None) -> None: if components is None: components = [] self.__components = list(components)
linear_algebra
def __len__(self) -> int: return len(self.__components)
linear_algebra
def __str__(self) -> str: return "(" + ",".join(map(str, self.__components)) + ")"
linear_algebra
def __add__(self, other: Vector) -> Vector: size = len(self) if size == len(other): result = [self.__components[i] + other.component(i) for i in range(size)] return Vector(result) else: raise Exception("must have the same size")
linear_algebra
def __sub__(self, other: Vector) -> Vector: size = len(self) if size == len(other): result = [self.__components[i] - other.component(i) for i in range(size)] return Vector(result) else: # error case raise Exception("must have the same size")
linear_algebra
def __mul__(self, other: float) -> Vector: ...
linear_algebra
def __mul__(self, other: Vector) -> float: ...
linear_algebra
def __mul__(self, other: float | Vector) -> float | Vector: if isinstance(other, (float, int)): ans = [c * other for c in self.__components] return Vector(ans) elif isinstance(other, Vector) and len(self) == len(other): size = len(self) prods = [self.__components[i] * other.component(i) for i in range(size)] return sum(prods) else: # error case raise Exception("invalid operand!")
linear_algebra
def copy(self) -> Vector: return Vector(self.__components)
linear_algebra
def component(self, i: int) -> float: if isinstance(i, int) and -len(self.__components) <= i < len(self.__components): return self.__components[i] else: raise Exception("index out of range")
linear_algebra
def change_component(self, pos: int, value: float) -> None: # precondition assert -len(self.__components) <= pos < len(self.__components) self.__components[pos] = value
linear_algebra
def euclidean_length(self) -> float: if len(self.__components) == 0: raise Exception("Vector is empty") squares = [c**2 for c in self.__components] return math.sqrt(sum(squares))
linear_algebra
def angle(self, other: Vector, deg: bool = False) -> float: num = self * other den = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den)) else: return math.acos(num / den)
linear_algebra
def zero_vector(dimension: int) -> Vector: # precondition assert isinstance(dimension, int) return Vector([0] * dimension)
linear_algebra
def unit_basis_vector(dimension: int, pos: int) -> Vector: # precondition assert isinstance(dimension, int) and (isinstance(pos, int)) ans = [0] * dimension ans[pos] = 1 return Vector(ans)
linear_algebra
def axpy(scalar: float, x: Vector, y: Vector) -> Vector: # precondition assert ( isinstance(x, Vector) and isinstance(y, Vector) and (isinstance(scalar, (int, float))) ) return x * scalar + y
linear_algebra
def random_vector(n: int, a: int, b: int) -> Vector: random.seed(None) ans = [random.randint(a, b) for _ in range(n)] return Vector(ans)
linear_algebra
def __init__(self, matrix: list[list[float]], w: int, h: int) -> None: self.__matrix = matrix self.__width = w self.__height = h
linear_algebra
def __str__(self) -> str: ans = "" for i in range(self.__height): ans += "|" for j in range(self.__width): if j < self.__width - 1: ans += str(self.__matrix[i][j]) + "," else: ans += str(self.__matrix[i][j]) + "|\n" return ans
linear_algebra
def __add__(self, other: Matrix) -> Matrix: if self.__width == other.width() and self.__height == other.height(): matrix = [] for i in range(self.__height): row = [ self.__matrix[i][j] + other.component(i, j) for j in range(self.__width) ] matrix.append(row) return Matrix(matrix, self.__width, self.__height) else: raise Exception("matrix must have the same dimension!")
linear_algebra
def __sub__(self, other: Matrix) -> Matrix: if self.__width == other.width() and self.__height == other.height(): matrix = [] for i in range(self.__height): row = [ self.__matrix[i][j] - other.component(i, j) for j in range(self.__width) ] matrix.append(row) return Matrix(matrix, self.__width, self.__height) else: raise Exception("matrices must have the same dimension!")
linear_algebra
def __mul__(self, other: float) -> Matrix: ...
linear_algebra
def __mul__(self, other: Vector) -> Vector: ...
linear_algebra
def __mul__(self, other: float | Vector) -> Vector | Matrix: if isinstance(other, Vector): # matrix-vector if len(other) == self.__width: ans = zero_vector(self.__height) for i in range(self.__height): prods = [ self.__matrix[i][j] * other.component(j) for j in range(self.__width) ] ans.change_component(i, sum(prods)) return ans else: raise Exception( "vector must have the same size as the " "number of columns of the matrix!" ) elif isinstance(other, (int, float)): # matrix-scalar matrix = [ [self.__matrix[i][j] * other for j in range(self.__width)] for i in range(self.__height) ] return Matrix(matrix, self.__width, self.__height) return None
linear_algebra
def height(self) -> int: return self.__height
linear_algebra
def width(self) -> int: return self.__width
linear_algebra
def component(self, x: int, y: int) -> float: if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception("change_component: indices out of bounds")
linear_algebra
def change_component(self, x: int, y: int, value: float) -> None: if 0 <= x < self.__height and 0 <= y < self.__width: self.__matrix[x][y] = value else: raise Exception("change_component: indices out of bounds")
linear_algebra
def minor(self, x: int, y: int) -> float: if self.__height != self.__width: raise Exception("Matrix is not square") minor = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(minor)): minor[i] = minor[i][:y] + minor[i][y + 1 :] return Matrix(minor, self.__width - 1, self.__height - 1).determinant()
linear_algebra
def cofactor(self, x: int, y: int) -> float: if self.__height != self.__width: raise Exception("Matrix is not square") if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(x, y) else: raise Exception("Indices out of bounds")
linear_algebra
def determinant(self) -> float: if self.__height != self.__width: raise Exception("Matrix is not square") if self.__height < 1: raise Exception("Matrix has no element") elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: cofactor_prods = [ self.__matrix[0][y] * self.cofactor(0, y) for y in range(self.__width) ] return sum(cofactor_prods)
linear_algebra
def square_zero_matrix(n: int) -> Matrix: ans: list[list[float]] = [[0] * n for _ in range(n)] return Matrix(ans, n, n)
linear_algebra
def power_iteration( input_matrix: np.ndarray, vector: np.ndarray, error_tol: float = 1e-12, max_iterations: int = 100, ) -> tuple[float, np.ndarray]: # Ensure matrix is square. assert np.shape(input_matrix)[0] == np.shape(input_matrix)[1] # Ensure proper dimensionality. assert np.shape(input_matrix)[0] == np.shape(vector)[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(input_matrix) == np.iscomplexobj(vector) is_complex = np.iscomplexobj(input_matrix) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(input_matrix, input_matrix.conj().T) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. convergence = False lambda_previous = 0 iterations = 0 error = 1e12 while not convergence: # Multiple matrix by the vector. w = np.dot(input_matrix, vector) # Normalize the resulting output vector. vector = w / np.linalg.norm(w) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) vector_h = vector.conj().T if is_complex else vector.T lambda_ = np.dot(vector_h, np.dot(input_matrix, vector)) # Check convergence. error = np.abs(lambda_ - lambda_previous) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: convergence = True lambda_previous = lambda_ if is_complex: lambda_ = np.real(lambda_) return lambda_, vector
linear_algebra
def test_power_iteration() -> None: real_input_matrix = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]]) real_vector = np.array([41, 4, 20]) complex_input_matrix = real_input_matrix.astype(np.complex128) imag_matrix = np.triu(1j * complex_input_matrix, 1) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T complex_vector = np.array([41, 4, 20]).astype(np.complex128) for problem_type in ["real", "complex"]: if problem_type == "real": input_matrix = real_input_matrix vector = real_vector elif problem_type == "complex": input_matrix = complex_input_matrix vector = complex_vector # Our implementation. eigen_value, eigen_vector = power_iteration(input_matrix, vector) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). eigen_values, eigen_vectors = np.linalg.eigh(input_matrix) # Last eigenvalue is the maximum one. eigen_value_max = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. eigen_vector_max = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max) <= 1e-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(eigen_vector) - np.abs(eigen_vector_max)) <= 1e-6
linear_algebra
def schur_complement( mat_a: np.ndarray, mat_b: np.ndarray, mat_c: np.ndarray, pseudo_inv: np.ndarray | None = None, ) -> np.ndarray: shape_a = np.shape(mat_a) shape_b = np.shape(mat_b) shape_c = np.shape(mat_c) if shape_a[0] != shape_b[0]: raise ValueError( f"Expected the same number of rows for A and B. \ Instead found A of size {shape_a} and B of size {shape_b}" ) if shape_b[1] != shape_c[1]: raise ValueError( f"Expected the same number of columns for B and C. \ Instead found B of size {shape_b} and C of size {shape_c}" ) a_inv = pseudo_inv if a_inv is None: try: a_inv = np.linalg.inv(mat_a) except np.linalg.LinAlgError: raise ValueError( "Input matrix A is not invertible. Cannot compute Schur complement." ) return mat_c - mat_b.T @ a_inv @ mat_b
linear_algebra
def test_schur_complement(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1], [6, 3]]) s = schur_complement(a, b, c) input_matrix = np.block([[a, b], [b.T, c]]) det_x = np.linalg.det(input_matrix) det_a = np.linalg.det(a) det_s = np.linalg.det(s) self.assertAlmostEqual(det_x, det_a * det_s)
linear_algebra
def test_improper_a_b_dimensions(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1], [6, 3]]) with self.assertRaises(ValueError): schur_complement(a, b, c)
linear_algebra
def test_improper_b_c_dimensions(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1, 3], [6, 3, 5]]) with self.assertRaises(ValueError): schur_complement(a, b, c)
linear_algebra
def test_component(self) -> None: x = Vector([1, 2, 3]) self.assertEqual(x.component(0), 1) self.assertEqual(x.component(2), 3) _ = Vector()
linear_algebra
def test_str(self) -> None: x = Vector([0, 0, 0, 0, 0, 1]) self.assertEqual(str(x), "(0,0,0,0,0,1)")
linear_algebra
def test_size(self) -> None: x = Vector([1, 2, 3, 4]) self.assertEqual(len(x), 4)
linear_algebra
def test_euclidean_length(self) -> None: x = Vector([1, 2]) y = Vector([1, 2, 3, 4, 5]) z = Vector([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) w = Vector([1, -1, 1, -1, 2, -3, 4, -5]) self.assertAlmostEqual(x.euclidean_length(), 2.236, 3) self.assertAlmostEqual(y.euclidean_length(), 7.416, 3) self.assertEqual(z.euclidean_length(), 0) self.assertAlmostEqual(w.euclidean_length(), 7.616, 3)
linear_algebra
def test_add(self) -> None: x = Vector([1, 2, 3]) y = Vector([1, 1, 1]) self.assertEqual((x + y).component(0), 2) self.assertEqual((x + y).component(1), 3) self.assertEqual((x + y).component(2), 4)
linear_algebra
def test_sub(self) -> None: x = Vector([1, 2, 3]) y = Vector([1, 1, 1]) self.assertEqual((x - y).component(0), 0) self.assertEqual((x - y).component(1), 1) self.assertEqual((x - y).component(2), 2)
linear_algebra
def test_mul(self) -> None: x = Vector([1, 2, 3]) a = Vector([2, -1, 4]) # for test of dot product b = Vector([1, -2, -1]) self.assertEqual(str(x * 3.0), "(3.0,6.0,9.0)") self.assertEqual((a * b), 0)
linear_algebra
def test_zero_vector(self) -> None: self.assertEqual(str(zero_vector(10)).count("0"), 10)
linear_algebra
def test_unit_basis_vector(self) -> None: self.assertEqual(str(unit_basis_vector(3, 1)), "(0,1,0)")
linear_algebra
def test_axpy(self) -> None: x = Vector([1, 2, 3]) y = Vector([1, 0, 1]) self.assertEqual(str(axpy(2, x, y)), "(3,4,7)")
linear_algebra
def test_copy(self) -> None: x = Vector([1, 0, 0, 0, 0, 0]) y = x.copy() self.assertEqual(str(x), str(y))
linear_algebra
def test_change_component(self) -> None: x = Vector([1, 0, 0]) x.change_component(0, 0) x.change_component(1, 1) self.assertEqual(str(x), "(0,1,0)")
linear_algebra
def test_str_matrix(self) -> None: a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) self.assertEqual("|1,2,3|\n|2,4,5|\n|6,7,8|\n", str(a))
linear_algebra
def test_minor(self) -> None: a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) minors = [[-3, -14, -10], [-5, -10, -5], [-2, -1, 0]] for x in range(a.height()): for y in range(a.width()): self.assertEqual(minors[x][y], a.minor(x, y))
linear_algebra
def test_cofactor(self) -> None: a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) cofactors = [[-3, 14, -10], [5, -10, 5], [-2, 1, 0]] for x in range(a.height()): for y in range(a.width()): self.assertEqual(cofactors[x][y], a.cofactor(x, y))
linear_algebra
def test_determinant(self) -> None: a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) self.assertEqual(-5, a.determinant())
linear_algebra
def test__mul__matrix(self) -> None: a = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3, 3) x = Vector([1, 2, 3]) self.assertEqual("(14,32,50)", str(a * x)) self.assertEqual("|2,4,6|\n|8,10,12|\n|14,16,18|\n", str(a * 2))
linear_algebra
def test_change_component_matrix(self) -> None: a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) a.change_component(0, 2, 5) self.assertEqual("|1,2,5|\n|2,4,5|\n|6,7,8|\n", str(a))
linear_algebra
def test_component_matrix(self) -> None: a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) self.assertEqual(7, a.component(2, 1), 0.01)
linear_algebra
def test__add__matrix(self) -> None: a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) b = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]], 3, 3) self.assertEqual("|2,4,10|\n|4,8,10|\n|12,14,18|\n", str(a + b))
linear_algebra
def test__sub__matrix(self) -> None: a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) b = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]], 3, 3) self.assertEqual("|0,0,-4|\n|0,0,0|\n|0,0,-2|\n", str(a - b))
linear_algebra
def test_square_zero_matrix(self) -> None: self.assertEqual( "|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n", str(square_zero_matrix(5)), )
linear_algebra
def scaling(scaling_factor: float) -> list[list[float]]: scaling_factor = float(scaling_factor) return [[scaling_factor * int(x == y) for x in range(2)] for y in range(2)]
linear_algebra
def rotation(angle: float) -> list[list[float]]: c, s = cos(angle), sin(angle) return [[c, -s], [s, c]]
linear_algebra
def projection(angle: float) -> list[list[float]]: c, s = cos(angle), sin(angle) cs = c * s return [[c * c, cs], [cs, s * s]]
linear_algebra
def reflection(angle: float) -> list[list[float]]: c, s = cos(angle), sin(angle) cs = c * s return [[2 * c - 1, 2 * cs], [2 * cs, 2 * s - 1]]
linear_algebra
def is_hermitian(matrix: np.ndarray) -> bool: return np.array_equal(matrix, matrix.conjugate().T)
linear_algebra
def rayleigh_quotient(a: np.ndarray, v: np.ndarray) -> Any: v_star = v.conjugate().T v_star_dot = v_star.dot(a) assert isinstance(v_star_dot, np.ndarray) return (v_star_dot.dot(v)) / (v_star.dot(v))
linear_algebra
def tests() -> None: a = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]]) v = np.array([[1], [2], [3]]) assert is_hermitian(a), f"{a} is not hermitian." print(rayleigh_quotient(a, v)) a = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]]) assert is_hermitian(a), f"{a} is not hermitian." assert rayleigh_quotient(a, v) == float(3)
linear_algebra
def __init__(self, list_of_points: list[tuple[float, float]]): self.list_of_points = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. self.degree = len(list_of_points) - 1
graphics
def basis_function(self, t: float) -> list[float]: assert 0 <= t <= 1, "Time t must be between 0 and 1." output_values: list[float] = [] for i in range(len(self.list_of_points)): # basis function for each i output_values.append( comb(self.degree, i) * ((1 - t) ** (self.degree - i)) * (t**i) ) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(output_values), 5) == 1 return output_values
graphics
def bezier_curve_function(self, t: float) -> tuple[float, float]: assert 0 <= t <= 1, "Time t must be between 0 and 1." basis_function = self.basis_function(t) x = 0.0 y = 0.0 for i in range(len(self.list_of_points)): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y)
graphics
def plot_curve(self, step_size: float = 0.01): from matplotlib import pyplot as plt # type: ignore to_plot_x: list[float] = [] # x coordinates of points to plot to_plot_y: list[float] = [] # y coordinates of points to plot t = 0.0 while t <= 1: value = self.bezier_curve_function(t) to_plot_x.append(value[0]) to_plot_y.append(value[1]) t += step_size x = [i[0] for i in self.list_of_points] y = [i[1] for i in self.list_of_points] plt.plot( to_plot_x, to_plot_y, color="blue", label="Curve of Degree " + str(self.degree), ) plt.scatter(x, y, color="red", label="Control Points") plt.legend() plt.show()
graphics
def convert_to_2d( x: float, y: float, z: float, scale: float, distance: float ) -> tuple[float, float]: if not all(isinstance(val, (float, int)) for val in locals().values()): raise TypeError( "Input values must either be float or int: " f"{list(locals().values())}" ) projected_x = ((x * distance) / (z + distance)) * scale projected_y = ((y * distance) / (z + distance)) * scale return projected_x, projected_y
graphics
def rotate( x: float, y: float, z: float, axis: str, angle: float ) -> tuple[float, float, float]: if not isinstance(axis, str): raise TypeError("Axis must be a str") input_variables = locals() del input_variables["axis"] if not all(isinstance(val, (float, int)) for val in input_variables.values()): raise TypeError( "Input values except axis must either be float or int: " f"{list(input_variables.values())}" ) angle = (angle % 360) / 450 * 180 / math.pi if axis == "z": new_x = x * math.cos(angle) - y * math.sin(angle) new_y = y * math.cos(angle) + x * math.sin(angle) new_z = z elif axis == "x": new_y = y * math.cos(angle) - z * math.sin(angle) new_z = z * math.cos(angle) + y * math.sin(angle) new_x = x elif axis == "y": new_x = x * math.cos(angle) - z * math.sin(angle) new_z = z * math.cos(angle) + x * math.sin(angle) new_y = y else: raise ValueError("not a valid axis, choose one of 'x', 'y', 'z'") return new_x, new_y, new_z
graphics
def covid_stats(url: str = "https://www.worldometers.info/coronavirus/") -> covid_data: xpath_str = '//div[@class = "maincounter-number"]/span/text()' return covid_data(*html.fromstring(requests.get(url).content).xpath(xpath_str))
web_programming
def get_hackernews_story(story_id: str) -> dict: url = f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty" return requests.get(url).json()
web_programming
def hackernews_top_stories(max_stories: int = 10) -> list[dict]: url = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty" story_ids = requests.get(url).json()[:max_stories] return [get_hackernews_story(story_id) for story_id in story_ids]
web_programming
def hackernews_top_stories_as_markdown(max_stories: int = 10) -> str: stories = hackernews_top_stories(max_stories) return "\n".join("* [{title}]({url})".format(**story) for story in stories)
web_programming
def get_imdb_top_250_movies(url: str = "") -> dict[str, float]: url = url or "https://www.imdb.com/chart/top/?ref_=nv_mv_250" soup = BeautifulSoup(requests.get(url).text, "html.parser") titles = soup.find_all("td", attrs="titleColumn") ratings = soup.find_all("td", class_="ratingColumn imdbRating") return { title.a.text: float(rating.strong.text) for title, rating in zip(titles, ratings) }
web_programming
def write_movies(filename: str = "IMDb_Top_250_Movies.csv") -> None: movies = get_imdb_top_250_movies() with open(filename, "w", newline="") as out_file: writer = csv.writer(out_file) writer.writerow(["Movie title", "IMDb rating"]) for title, rating in movies.items(): writer.writerow([title, rating])
web_programming
def quote_of_the_day() -> list: return requests.get(API_ENDPOINT_URL + "/today").json()
web_programming
def random_quotes() -> list: return requests.get(API_ENDPOINT_URL + "/random").json()
web_programming
def fetch_jobs(location: str = "mumbai") -> Generator[tuple[str, str], None, None]: soup = BeautifulSoup(requests.get(url + location).content, "html.parser") # This attribute finds out all the specifics listed in a job for job in soup.find_all("div", attrs={"data-tn-component": "organicJob"}): job_title = job.find("a", attrs={"data-tn-element": "jobTitle"}).text.strip() company_name = job.find("span", {"class": "company"}).text.strip() yield job_title, company_name
web_programming
def get_amazon_product_data(product: str = "laptop") -> DataFrame: url = f"https://www.amazon.in/laptop/s?k={product}" header = { "Accept-Language": "en-US, en;q=0.5", } soup = BeautifulSoup(requests.get(url, headers=header).text) # Initialize a Pandas dataframe with the column titles data_frame = DataFrame( columns=[ "Product Title", "Product Link", "Current Price of the product", "Product Rating", "MRP of the product", "Discount", ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( "div", attrs={"class": "s-result-item", "data-component-type": "s-search-result"}, ), soup.find_all("div", attrs={"class": "a-row a-size-base a-color-base"}), ): try: product_title = item.h2.text product_link = "https://www.amazon.in/" + item.h2.a["href"] product_price = item.find("span", attrs={"class": "a-offscreen"}).text try: product_rating = item.find("span", attrs={"class": "a-icon-alt"}).text except AttributeError: product_rating = "Not available" try: product_mrp = ( "₹" + item.find( "span", attrs={"class": "a-price a-text-price"} ).text.split("₹")[1] ) except AttributeError: product_mrp = "" try: discount = float( ( ( float(product_mrp.strip("₹").replace(",", "")) - float(product_price.strip("₹").replace(",", "")) ) / float(product_mrp.strip("₹").replace(",", "")) ) * 100 ) except ValueError: discount = float("nan") except AttributeError: pass data_frame.loc[len(data_frame.index)] = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] data_frame.loc[ data_frame["Current Price of the product"] > data_frame["MRP of the product"], "MRP of the product", ] = " " data_frame.loc[ data_frame["Current Price of the product"] > data_frame["MRP of the product"], "Discount", ] = " " data_frame.index += 1 return data_frame
web_programming
def convert(number: int) -> str: if number == 0: words = "Zero" return words else: digits = math.log10(number) digits = digits + 1 singles = {} singles[0] = "" singles[1] = "One" singles[2] = "Two" singles[3] = "Three" singles[4] = "Four" singles[5] = "Five" singles[6] = "Six" singles[7] = "Seven" singles[8] = "Eight" singles[9] = "Nine" doubles = {} doubles[0] = "" doubles[2] = "Twenty" doubles[3] = "Thirty" doubles[4] = "Forty" doubles[5] = "Fifty" doubles[6] = "Sixty" doubles[7] = "Seventy" doubles[8] = "Eighty" doubles[9] = "Ninety" teens = {} teens[0] = "Ten" teens[1] = "Eleven" teens[2] = "Twelve" teens[3] = "Thirteen" teens[4] = "Fourteen" teens[5] = "Fifteen" teens[6] = "Sixteen" teens[7] = "Seventeen" teens[8] = "Eighteen" teens[9] = "Nineteen" placevalue = {} placevalue[2] = "Hundred," placevalue[3] = "Thousand," placevalue[5] = "Lakh," placevalue[7] = "Crore," temp_num = number words = "" counter = 0 digits = int(digits) while counter < digits: current = temp_num % 10 if counter % 2 == 0: addition = "" if counter in placevalue and current != 0: addition = placevalue[counter] if counter == 2: words = singles[current] + addition + words elif counter == 0: if ((temp_num % 100) // 10) == 1: words = teens[current] + addition + words temp_num = temp_num // 10 counter += 1 else: words = singles[current] + addition + words else: words = doubles[current] + addition + words else: if counter == 1: if current == 1: words = teens[number % 10] + words else: addition = "" if counter in placevalue: addition = placevalue[counter] words = doubles[current] + addition + words else: addition = "" if counter in placevalue: if current == 0 and ((temp_num % 100) // 10) == 0: addition = "" else: addition = placevalue[counter] if ((temp_num % 100) // 10) == 1: words = teens[current] + addition + words temp_num = temp_num // 10 counter += 1 else: words = singles[current] + addition + words counter += 1 temp_num = temp_num // 10 return words
web_programming
def __init__(self, content) -> None: assert isinstance(content, (bytes, str)) self.content = content
web_programming
def json(self): return json.loads(self.content)
web_programming
def mock_response(*args, **kwargs): assert args[0] == AUTHENTICATED_USER_ENDPOINT assert "Authorization" in kwargs["headers"] assert kwargs["headers"]["Authorization"].startswith("token ") assert "Accept" in kwargs["headers"] return FakeResponse(b'{"login":"test","id":1}')
web_programming
def get_movie_data_from_soup(soup: bs4.element.ResultSet) -> dict[str, str]: return { "name": soup.h3.a.text, "genre": soup.find("span", class_="genre").text.strip(), "rating": soup.strong.text, "page_link": f"https://www.imdb.com{soup.a.get('href')}", }
web_programming