function
stringlengths
18
3.86k
intent_category
stringlengths
5
24
def __len__(self) -> int: return self.nodes
graphs
def add_node(self, node: T) -> None: # Add a node in the graph if it is not in the graph if node not in self.connections: self.connections[node] = {} self.nodes += 1
graphs
def add_edge(self, node1: T, node2: T, weight: int) -> None: # Add an edge between 2 nodes in the graph self.add_node(node1) self.add_node(node2) self.connections[node1][node2] = weight self.connections[node2][node1] = weight
graphs
def find_parent(i): if i != parent[i]: parent[i] = find_parent(parent[i]) return parent[i]
graphs
def __init__(self, graph, sources, sinks): self.source_index = None self.sink_index = None self.graph = graph self._normalize_graph(sources, sinks) self.vertices_count = len(graph) self.maximum_flow_algorithm = None
graphs
def _normalize_graph(self, sources, sinks): if sources is int: sources = [sources] if sinks is int: sinks = [sinks] if len(sources) == 0 or len(sinks) == 0: return self.source_index = sources[0] self.sink_index = sinks[0] # make fake vertex if there are more # than one source or sink if len(sources) > 1 or len(sinks) > 1: max_input_flow = 0 for i in sources: max_input_flow += sum(self.graph[i]) size = len(self.graph) + 1 for room in self.graph: room.insert(0, 0) self.graph.insert(0, [0] * size) for i in sources: self.graph[0][i + 1] = max_input_flow self.source_index = 0 size = len(self.graph) + 1 for room in self.graph: room.append(0) self.graph.append([0] * size) for i in sinks: self.graph[i + 1][size - 1] = max_input_flow self.sink_index = size - 1
graphs
def find_maximum_flow(self): if self.maximum_flow_algorithm is None: raise Exception("You need to set maximum flow algorithm before.") if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow()
graphs
def set_maximum_flow_algorithm(self, algorithm): self.maximum_flow_algorithm = algorithm(self)
graphs
def __init__(self, flow_network): self.flow_network = flow_network self.verticies_count = flow_network.verticesCount self.source_index = flow_network.sourceIndex self.sink_index = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that self.graph = flow_network.graph self.executed = False
graphs
def execute(self): if not self.executed: self._algorithm() self.executed = True
graphs
def _algorithm(self): pass
graphs
def __init__(self, flow_network): super().__init__(flow_network) # use this to save your result self.maximum_flow = -1
graphs
def get_maximum_flow(self): if not self.executed: raise Exception("You should execute algorithm before using its result!") return self.maximum_flow
graphs
def __init__(self, flow_network): super().__init__(flow_network) self.preflow = [[0] * self.verticies_count for i in range(self.verticies_count)] self.heights = [0] * self.verticies_count self.excesses = [0] * self.verticies_count
graphs
def _algorithm(self): self.heights[self.source_index] = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index]): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule vertices_list = [ i for i in range(self.verticies_count) if i != self.source_index and i != self.sink_index ] # move through list i = 0 while i < len(vertices_list): vertex_index = vertices_list[i] previous_height = self.heights[vertex_index] self.process_vertex(vertex_index) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0, vertices_list.pop(i)) i = 0 else: i += 1 self.maximum_flow = sum(self.preflow[self.source_index])
graphs
def process_vertex(self, vertex_index): while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(vertex_index, neighbour_index) self.relabel(vertex_index)
graphs
def push(self, from_index, to_index): preflow_delta = min( self.excesses[from_index], self.graph[from_index][to_index] - self.preflow[from_index][to_index], ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta
graphs
def relabel(self, vertex_index): min_height = None for to_index in range(self.verticies_count): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): min_height = self.heights[to_index] if min_height is not None: self.heights[vertex_index] = min_height + 1
graphs
def __init__(self, graph: dict[str, list[str]], source_vertex: str) -> None: self.graph = graph # mapping node to its parent in resulting breadth first tree self.parent: dict[str, str | None] = {} self.source_vertex = source_vertex
graphs
def breath_first_search(self) -> None: visited = {self.source_vertex} self.parent[self.source_vertex] = None queue = [self.source_vertex] # first in first out queue while queue: vertex = queue.pop(0) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(adjacent_vertex) self.parent[adjacent_vertex] = vertex queue.append(adjacent_vertex)
graphs
def shortest_path(self, target_vertex: str) -> str: if target_vertex == self.source_vertex: return self.source_vertex target_vertex_parent = self.parent.get(target_vertex) if target_vertex_parent is None: raise ValueError( f"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" ) return self.shortest_path(target_vertex_parent) + f"->{target_vertex}"
graphs
def __init__(self): self.cur_size = 0 self.array = [] self.pos = {} # To store the pos of node in array
graphs
def is_empty(self): return self.cur_size == 0
graphs
def min_heapify(self, idx): lc = self.left(idx) rc = self.right(idx) if lc < self.cur_size and self.array(lc)[0] < self.array(idx)[0]: smallest = lc else: smallest = idx if rc < self.cur_size and self.array(rc)[0] < self.array(smallest)[0]: smallest = rc if smallest != idx: self.swap(idx, smallest) self.min_heapify(smallest)
graphs
def insert(self, tup): # Inserts a node into the Priority Queue self.pos[tup[1]] = self.cur_size self.cur_size += 1 self.array.append((sys.maxsize, tup[1])) self.decrease_key((sys.maxsize, tup[1]), tup[0])
graphs
def extract_min(self): # Removes and returns the min element at top of priority queue min_node = self.array[0][1] self.array[0] = self.array[self.cur_size - 1] self.cur_size -= 1 self.min_heapify(1) del self.pos[min_node] return min_node
graphs
def left(self, i): # returns the index of left child return 2 * i + 1
graphs
def right(self, i): # returns the index of right child return 2 * i + 2
graphs
def par(self, i): # returns the index of parent return math.floor(i / 2)
graphs
def swap(self, i, j): # swaps array elements at indices i and j # update the pos{} self.pos[self.array[i][1]] = j self.pos[self.array[j][1]] = i temp = self.array[i] self.array[i] = self.array[j] self.array[j] = temp
graphs
def decrease_key(self, tup, new_d): idx = self.pos[tup[1]] # assuming the new_d is atmost old_d self.array[idx] = (new_d, tup[1]) while idx > 0 and self.array[self.par(idx)][0] > self.array[idx][0]: self.swap(idx, self.par(idx)) idx = self.par(idx)
graphs
def __init__(self, num): self.adjList = {} # To store graph: u -> (v,w) self.num_nodes = num # Number of nodes in graph # To store the distance from source vertex self.dist = [0] * self.num_nodes self.par = [-1] * self.num_nodes # To store the path
graphs
def add_edge(self, u, v, w): # Edge going from node u to v and v to u with weight w # u (w)-> v, v (w) -> u # Check if u already in graph if u in self.adjList: self.adjList[u].append((v, w)) else: self.adjList[u] = [(v, w)] # Assuming undirected graph if v in self.adjList: self.adjList[v].append((u, w)) else: self.adjList[v] = [(u, w)]
graphs
def show_graph(self): # u -> v(w) for u in self.adjList: print(u, "->", " -> ".join(str(f"{v}({w})") for v, w in self.adjList[u]))
graphs
def dijkstra(self, src): # Flush old junk values in par[] self.par = [-1] * self.num_nodes # src is the source node self.dist[src] = 0 q = PriorityQueue() q.insert((0, src)) # (dist from src, node) for u in self.adjList: if u != src: self.dist[u] = sys.maxsize # Infinity self.par[u] = -1 while not q.is_empty(): u = q.extract_min() # Returns node with the min dist from source # Update the distance of all the neighbours of u and # if their prev dist was INFINITY then push them in Q for v, w in self.adjList[u]: new_dist = self.dist[u] + w if self.dist[v] > new_dist: if self.dist[v] == sys.maxsize: q.insert((new_dist, v)) else: q.decrease_key((self.dist[v], v), new_dist) self.dist[v] = new_dist self.par[v] = u # Show the shortest distances from src self.show_distances(src)
graphs
def show_distances(self, src): print(f"Distance from node: {src}") for u in range(self.num_nodes): print(f"Node {u} has distance: {self.dist[u]}")
graphs
def show_path(self, src, dest): # To show the shortest path from src to dest # WARNING: Use it *after* calling dijkstra path = [] cost = 0 temp = dest # Backtracking from dest to src while self.par[temp] != -1: path.append(temp) if temp != src: for v, w in self.adjList[temp]: if v == self.par[temp]: cost += w break temp = self.par[temp] path.append(src) path.reverse() print(f"----Path to reach {dest} from {src}----") for u in path: print(f"{u}", end=" ") if u != dest: print("-> ", end="") print("\nTotal cost of path: ", cost)
graphs
def topological_sort(graph): indegree = [0] * len(graph) queue = [] topo = [] cnt = 0 for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(indegree)): if indegree[i] == 0: queue.append(i) while queue: vertex = queue.pop(0) cnt += 1 topo.append(vertex) for x in graph[vertex]: indegree[x] -= 1 if indegree[x] == 0: queue.append(x) if cnt != len(graph): print("Cycle exists") else: print(topo)
graphs
def __init__(self, directed: bool = True) -> None: self.adj_list: dict[T, list[T]] = {} # dictionary of lists self.directed = directed
graphs
def add_edge( self, source_vertex: T, destination_vertex: T ) -> GraphAdjacencyList[T]: if not self.directed: # For undirected graphs # if both source vertex and destination vertex are both present in the # adjacency list, add destination vertex to source vertex list of adjacent # vertices and add source vertex to destination vertex list of adjacent # vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(destination_vertex) self.adj_list[destination_vertex].append(source_vertex) # if only source vertex is present in adjacency list, add destination vertex # to source vertex list of adjacent vertices, then create a new vertex with # destination vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(destination_vertex) self.adj_list[destination_vertex] = [source_vertex] # if only destination vertex is present in adjacency list, add source vertex # to destination vertex list of adjacent vertices, then create a new vertex # with source vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif destination_vertex in self.adj_list: self.adj_list[destination_vertex].append(source_vertex) self.adj_list[source_vertex] = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and assign a list # containing the destination vertex as it's first adjacent vertex also # create a new vertex with destination vertex as key and assign a list # containing the source vertex as it's first adjacent vertex. else: self.adj_list[source_vertex] = [destination_vertex] self.adj_list[destination_vertex] = [source_vertex] else: # For directed graphs # if both source vertex and destination vertex are present in adjacency # list, add destination vertex to source vertex list of adjacent vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(destination_vertex) # if only source vertex is present in adjacency list, add destination # vertex to source vertex list of adjacent vertices and create a new vertex # with destination vertex as key, which has no adjacent vertex elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(destination_vertex) self.adj_list[destination_vertex] = [] # if only destination vertex is present in adjacency list, create a new # vertex with source vertex as key and assign a list containing destination # vertex as first adjacent vertex elif destination_vertex in self.adj_list: self.adj_list[source_vertex] = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and a list containing # destination vertex as it's first adjacent vertex. Then create a new vertex # with destination vertex as key, which has no adjacent vertex else: self.adj_list[source_vertex] = [destination_vertex] self.adj_list[destination_vertex] = [] return self
graphs
def __init__(self, vertex): self.vertex = vertex self.graph = [[0] * vertex for i in range(vertex)]
graphs
def add_edge(self, u, v): self.graph[u - 1][v - 1] = 1 self.graph[v - 1][u - 1] = 1
graphs
def show(self): for i in self.graph: for j in i: print(j, end=" ") print(" ")
graphs
def longest_distance(graph): indegree = [0] * len(graph) queue = [] long_dist = [1] * len(graph) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(indegree)): if indegree[i] == 0: queue.append(i) while queue: vertex = queue.pop(0) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: long_dist[x] = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(x) print(max(long_dist))
graphs
def _print_dist(dist, v): print("\nThe shortest path matrix using Floyd Warshall algorithm\n") for i in range(v): for j in range(v): if dist[i][j] != float("inf"): print(int(dist[i][j]), end="\t") else: print("INF", end="\t") print()
graphs
def floyd_warshall(graph, v): dist = [[float("inf") for _ in range(v)] for _ in range(v)] for i in range(v): for j in range(v): dist[i][j] = graph[i][j] # check vertex k against all other vertices (i, j) for k in range(v): # looping through rows of graph array for i in range(v): # looping through columns of graph array for j in range(v): if ( dist[i][k] != float("inf") and dist[k][j] != float("inf") and dist[i][k] + dist[k][j] < dist[i][j] ): dist[i][j] = dist[i][k] + dist[k][j] _print_dist(dist, v) return dist, v
graphs
def __init__(self, vertices: int) -> None: self.vertices = vertices self.graph = [[0] * vertices for _ in range(vertices)]
graphs
def print_solution(self, distances_from_source: list[int]) -> None: print("Vertex \t Distance from Source") for vertex in range(self.vertices): print(vertex, "\t\t", distances_from_source[vertex])
graphs
def minimum_distance( self, distances_from_source: list[int], visited: list[bool] ) -> int: # Initialize minimum distance for next node minimum = 1e7 min_index = 0 # Search not nearest vertex not in the shortest path tree for vertex in range(self.vertices): if distances_from_source[vertex] < minimum and visited[vertex] is False: minimum = distances_from_source[vertex] min_index = vertex return min_index
graphs
def dijkstra(self, source: int) -> None: distances = [int(1e7)] * self.vertices # distances from the source distances[source] = 0 visited = [False] * self.vertices for _ in range(self.vertices): u = self.minimum_distance(distances, visited) visited[u] = True # Update dist value of the adjacent vertices # of the picked vertex only if the current # distance is greater than new distance and # the vertex in not in the shortest path tree for v in range(self.vertices): if ( self.graph[u][v] > 0 and visited[v] is False and distances[v] > distances[u] + self.graph[u][v] ): distances[v] = distances[u] + self.graph[u][v] self.print_solution(distances)
graphs
def __init__(self, data: T) -> None: self.data = data self.parent = self self.rank = 0
graphs
def __init__(self) -> None: # map from node name to the node object self.map: dict[T, DisjointSetTreeNode[T]] = {}
graphs
def make_set(self, data: T) -> None: # create a new set with x as its member self.map[data] = DisjointSetTreeNode(data)
graphs
def find_set(self, data: T) -> DisjointSetTreeNode[T]: # find the set x belongs to (with path-compression) elem_ref = self.map[data] if elem_ref != elem_ref.parent: elem_ref.parent = self.find_set(elem_ref.parent.data) return elem_ref.parent
graphs
def link( self, node1: DisjointSetTreeNode[T], node2: DisjointSetTreeNode[T] ) -> None: # helper function for union operation if node1.rank > node2.rank: node2.parent = node1 else: node1.parent = node2 if node1.rank == node2.rank: node2.rank += 1
graphs
def union(self, data1: T, data2: T) -> None: # merge 2 disjoint sets self.link(self.find_set(data1), self.find_set(data2))
graphs
def __init__(self) -> None: # connections: map from the node to the neighbouring nodes (with weights) self.connections: dict[T, dict[T, int]] = {}
graphs
def add_node(self, node: T) -> None: # add a node ONLY if its not present in the graph if node not in self.connections: self.connections[node] = {}
graphs
def add_edge(self, node1: T, node2: T, weight: int) -> None: # add an edge with the given weight self.add_node(node1) self.add_node(node2) self.connections[node1][node2] = weight self.connections[node2][node1] = weight
graphs
def format_ruleset(ruleset: int) -> list[int]: return [int(c) for c in f"{ruleset:08}"[:8]]
cellular_automata
def new_generation(cells: list[list[int]], rule: list[int], time: int) -> list[int]: population = len(cells[0]) # 31 next_generation = [] for i in range(population): # Get the neighbors of each cell # Handle neighbours outside bounds by using 0 as their value left_neighbor = 0 if i == 0 else cells[time][i - 1] right_neighbor = 0 if i == population - 1 else cells[time][i + 1] # Define a new cell and add it to the new generation situation = 7 - int(f"{left_neighbor}{cells[time][i]}{right_neighbor}", 2) next_generation.append(rule[situation]) return next_generation
cellular_automata
def generate_image(cells: list[list[int]]) -> Image.Image: # Create the output image img = Image.new("RGB", (len(cells[0]), len(cells))) pixels = img.load() # Generates image for w in range(img.width): for h in range(img.height): color = 255 - int(255 * cells[h][w]) pixels[w, h] = (color, color, color) return img
cellular_automata
def new_generation(cells: list[list[int]]) -> list[list[int]]: next_generation = [] for i in range(len(cells)): next_generation_row = [] for j in range(len(cells[i])): # Get the number of live neighbours neighbour_count = 0 if i > 0 and j > 0: neighbour_count += cells[i - 1][j - 1] if i > 0: neighbour_count += cells[i - 1][j] if i > 0 and j < len(cells[i]) - 1: neighbour_count += cells[i - 1][j + 1] if j > 0: neighbour_count += cells[i][j - 1] if j < len(cells[i]) - 1: neighbour_count += cells[i][j + 1] if i < len(cells) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(cells) - 1: neighbour_count += cells[i + 1][j] if i < len(cells) - 1 and j < len(cells[i]) - 1: neighbour_count += cells[i + 1][j + 1] # Rules of the game of life (excerpt from Wikipedia): # 1. Any live cell with two or three live neighbours survives. # 2. Any dead cell with three live neighbours becomes a live cell. # 3. All other live cells die in the next generation. # Similarly, all other dead cells stay dead. alive = cells[i][j] == 1 if ( (alive and 2 <= neighbour_count <= 3) or not alive and neighbour_count == 3 ): next_generation_row.append(1) else: next_generation_row.append(0) next_generation.append(next_generation_row) return next_generation
cellular_automata
def generate_images(cells: list[list[int]], frames: int) -> list[Image.Image]: images = [] for _ in range(frames): # Create output image img = Image.new("RGB", (len(cells[0]), len(cells))) pixels = img.load() # Save cells to image for x in range(len(cells)): for y in range(len(cells[0])): colour = 255 - cells[y][x] * 255 pixels[x, y] = (colour, colour, colour) # Save image images.append(img) cells = new_generation(cells) return images
cellular_automata
def create_canvas(size: int) -> list[list[bool]]: canvas = [[False for i in range(size)] for j in range(size)] return canvas
cellular_automata
def seed(canvas: list[list[bool]]) -> None: for i, row in enumerate(canvas): for j, _ in enumerate(row): canvas[i][j] = bool(random.getrandbits(1))
cellular_automata
def run(canvas: list[list[bool]]) -> list[list[bool]]: current_canvas = np.array(canvas) next_gen_canvas = np.array(create_canvas(current_canvas.shape[0])) for r, row in enumerate(current_canvas): for c, pt in enumerate(row): next_gen_canvas[r][c] = __judge_point( pt, current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) current_canvas = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. return_canvas: list[list[bool]] = current_canvas.tolist() return return_canvas
cellular_automata
def __judge_point(pt: bool, neighbours: list[list[bool]]) -> bool: dead = 0 alive = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. state = pt if pt: if alive < 2: state = False elif alive == 2 or alive == 3: state = True elif alive > 3: state = False else: if alive == 3: state = True return state
cellular_automata
def construct_highway( number_of_cells: int, frequency: int, initial_speed: int, random_frequency: bool = False, random_speed: bool = False, max_speed: int = 5, ) -> list: highway = [[-1] * number_of_cells] # Create a highway without any car i = 0 initial_speed = max(initial_speed, 0) while i < number_of_cells: highway[0][i] = ( randint(0, max_speed) if random_speed else initial_speed ) # Place the cars i += ( randint(1, max_speed * 2) if random_frequency else frequency ) # Arbitrary number, may need tuning return highway
cellular_automata
def get_distance(highway_now: list, car_index: int) -> int: distance = 0 cells = highway_now[car_index + 1 :] for cell in range(len(cells)): # May need a better name for this if cells[cell] != -1: # If the cell is not empty then return distance # we have the distance we wanted distance += 1 # Here if the car is near the end of the highway return distance + get_distance(highway_now, -1)
cellular_automata
def update(highway_now: list, probability: float, max_speed: int) -> list: number_of_cells = len(highway_now) # Beforce calculations, the highway is empty next_highway = [-1] * number_of_cells for car_index in range(number_of_cells): if highway_now[car_index] != -1: # Add 1 to the current speed of the car and cap the speed next_highway[car_index] = min(highway_now[car_index] + 1, max_speed) # Number of empty cell before the next car dn = get_distance(highway_now, car_index) - 1 # We can't have the car causing an accident next_highway[car_index] = min(next_highway[car_index], dn) if random() < probability: # Randomly, a driver will slow down next_highway[car_index] = max(next_highway[car_index] - 1, 0) return next_highway
cellular_automata
def simulate( highway: list, number_of_update: int, probability: float, max_speed: int ) -> list: number_of_cells = len(highway[0]) for i in range(number_of_update): next_speeds_calculated = update(highway[i], probability, max_speed) real_next_speeds = [-1] * number_of_cells for car_index in range(number_of_cells): speed = next_speeds_calculated[car_index] if speed != -1: # Change the position based on the speed (with % to create the loop) index = (car_index + speed) % number_of_cells # Commit the change of position real_next_speeds[index] = speed highway.append(real_next_speeds) return highway
cellular_automata
def newtons_second_law_of_motion(mass: float, acceleration: float) -> float: force = float() try: force = mass * acceleration except Exception: return -0.0 return force
physics
def shear_stress( stress: float, tangential_force: float, area: float, ) -> tuple[str, float]: if (stress, tangential_force, area).count(0) != 1: raise ValueError("You cannot supply more or less than 2 values") elif stress < 0: raise ValueError("Stress cannot be negative") elif tangential_force < 0: raise ValueError("Tangential Force cannot be negative") elif area < 0: raise ValueError("Area cannot be negative") elif stress == 0: return ( "stress", tangential_force / area, ) elif tangential_force == 0: return ( "tangential_force", stress * area, ) else: return ( "area", tangential_force / stress, )
physics
def malus_law(initial_intensity: float, angle: float) -> float: if initial_intensity < 0: raise ValueError("The value of intensity cannot be negative") # handling of negative values of initial intensity if angle < 0 or angle > 360: raise ValueError("In Malus Law, the angle is in the range 0-360 degrees") # handling of values out of allowed range return initial_intensity * (math.cos(math.radians(angle)) ** 2)
physics
def kinetic_energy(mass: float, velocity: float) -> float: if mass < 0: raise ValueError("The mass of a body cannot be negative") return 0.5 * mass * abs(velocity) * abs(velocity)
physics
def beta(velocity: float) -> float: if velocity > c: raise ValueError("Speed must not exceed light speed 299,792,458 [m/s]!") elif velocity < 1: # Usually the speed should be much higher than 1 (c order of magnitude) raise ValueError("Speed must be greater than or equal to 1!") return velocity / c
physics
def gamma(velocity: float) -> float: return 1 / sqrt(1 - beta(velocity) ** 2)
physics
def transformation_matrix(velocity: float) -> np.ndarray: return np.array( [ [gamma(velocity), -gamma(velocity) * beta(velocity), 0, 0], [-gamma(velocity) * beta(velocity), gamma(velocity), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] )
physics
def transform(velocity: float, event: np.ndarray | None = None) -> np.ndarray: # Ensure event is not empty if event is None: event = np.array([ct, x, y, z]) # Symbolic four vector else: event[0] *= c # x0 is ct (speed of light * time) return transformation_matrix(velocity) @ event
physics
def archimedes_principle( fluid_density: float, volume: float, gravity: float = g ) -> float: if fluid_density <= 0: raise ValueError("Impossible fluid density") if volume < 0: raise ValueError("Impossible Object volume") if gravity <= 0: raise ValueError("Impossible Gravity") return fluid_density * gravity * volume
physics
def casimir_force(force: float, area: float, distance: float) -> dict[str, float]: if (force, area, distance).count(0) != 1: raise ValueError("One and only one argument must be 0") if force < 0: raise ValueError("Magnitude of force can not be negative") if distance < 0: raise ValueError("Distance can not be negative") if area < 0: raise ValueError("Area can not be negative") if force == 0: force = (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / ( 240 * (distance) ** 4 ) return {"force": force} elif area == 0: area = (240 * force * (distance) ** 4) / ( REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 ) return {"area": area} elif distance == 0: distance = ( (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (240 * force) ) ** (1 / 4) return {"distance": distance} raise ValueError("One and only one argument must be 0")
physics
def check_args(init_velocity: float, angle: float) -> None: # Ensure valid instance if not isinstance(init_velocity, (int, float)): raise TypeError("Invalid velocity. Should be a positive number.") if not isinstance(angle, (int, float)): raise TypeError("Invalid angle. Range is 1-90 degrees.") # Ensure valid angle if angle > 90 or angle < 1: raise ValueError("Invalid angle. Range is 1-90 degrees.") # Ensure valid velocity if init_velocity < 0: raise ValueError("Invalid velocity. Should be a positive number.")
physics
def horizontal_distance(init_velocity: float, angle: float) -> float: check_args(init_velocity, angle) radians = angle_to_radians(2 * angle) return round(init_velocity**2 * sin(radians) / g, 2)
physics
def max_height(init_velocity: float, angle: float) -> float: check_args(init_velocity, angle) radians = angle_to_radians(angle) return round(init_velocity**2 * sin(radians) ** 2 / (2 * g), 2)
physics
def total_time(init_velocity: float, angle: float) -> float: check_args(init_velocity, angle) radians = angle_to_radians(angle) return round(2 * init_velocity * sin(radians) / g, 2)
physics
def test_motion() -> None: v0, angle = 25, 20 assert horizontal_distance(v0, angle) == 40.97 assert max_height(v0, angle) == 3.73 assert total_time(v0, angle) == 1.74
physics
def gravitational_law( force: float, mass_1: float, mass_2: float, distance: float ) -> dict[str, float]: product_of_mass = mass_1 * mass_2 if (force, mass_1, mass_2, distance).count(0) != 1: raise ValueError("One and only one argument must be 0") if force < 0: raise ValueError("Gravitational force can not be negative") if distance < 0: raise ValueError("Distance can not be negative") if mass_1 < 0 or mass_2 < 0: raise ValueError("Mass can not be negative") if force == 0: force = GRAVITATIONAL_CONSTANT * product_of_mass / (distance**2) return {"force": force} elif mass_1 == 0: mass_1 = (force) * (distance**2) / (GRAVITATIONAL_CONSTANT * mass_2) return {"mass_1": mass_1} elif mass_2 == 0: mass_2 = (force) * (distance**2) / (GRAVITATIONAL_CONSTANT * mass_1) return {"mass_2": mass_2} elif distance == 0: distance = (GRAVITATIONAL_CONSTANT * product_of_mass / (force)) ** 0.5 return {"distance": distance} raise ValueError("One and only one argument must be 0")
physics
def rms_speed_of_molecule(temperature: float, molar_mass: float) -> float: if temperature < 0: raise Exception("Temperature cannot be less than 0 K") if molar_mass <= 0: raise Exception("Molar mass cannot be less than or equal to 0 kg/mol") else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5
physics
def hubble_parameter( hubble_constant: float, radiation_density: float, matter_density: float, dark_energy: float, redshift: float, ) -> float: parameters = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters): raise ValueError("All input parameters must be positive") if any(p > 1 for p in parameters[1:4]): raise ValueError("Relative densities cannot be greater than one") else: curvature = 1 - (matter_density + radiation_density + dark_energy) e_2 = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) hubble = hubble_constant * e_2 ** (1 / 2) return hubble
physics
def centripetal(mass: float, velocity: float, radius: float) -> float: if mass < 0: raise ValueError("The mass of the body cannot be negative") if radius <= 0: raise ValueError("The radius is always a positive non zero integer") return (mass * (velocity) ** 2) / radius
physics
def pressure_of_gas_system(moles: float, kelvin: float, volume: float) -> float: if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("Invalid inputs. Enter positive value.") return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume
physics
def volume_of_gas_system(moles: float, kelvin: float, pressure: float) -> float: if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value.") return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure
physics
def potential_energy(mass: float, height: float) -> float: # function will accept mass and height as parameters and return potential energy if mass < 0: # handling of negative values of mass raise ValueError("The mass of a body cannot be negative") if height < 0: # handling of negative values of height raise ValueError("The height above the ground cannot be negative") return mass * g * height
physics
def __init__( self, position_x: float, position_y: float, velocity_x: float, velocity_y: float, mass: float = 1.0, size: float = 1.0, color: str = "blue", ) -> None: self.position_x = position_x self.position_y = position_y self.velocity_x = velocity_x self.velocity_y = velocity_y self.mass = mass self.size = size self.color = color
physics
def position(self) -> tuple[float, float]: return self.position_x, self.position_y
physics
def velocity(self) -> tuple[float, float]: return self.velocity_x, self.velocity_y
physics
def update_velocity( self, force_x: float, force_y: float, delta_time: float ) -> None: self.velocity_x += force_x * delta_time self.velocity_y += force_y * delta_time
physics
def update_position(self, delta_time: float) -> None: self.position_x += self.velocity_x * delta_time self.position_y += self.velocity_y * delta_time
physics
def __init__( self, bodies: list[Body], gravitation_constant: float = 1.0, time_factor: float = 1.0, softening_factor: float = 0.0, ) -> None: self.bodies = bodies self.gravitation_constant = gravitation_constant self.time_factor = time_factor self.softening_factor = softening_factor
physics