repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/knight_tour.py
backtracking/knight_tour.py
# Knight Tour Intro: https://www.youtube.com/watch?v=ab_dY3dZFHM from __future__ import annotations def get_valid_pos(position: tuple[int, int], n: int) -> list[tuple[int, int]]: """ Find all the valid positions a knight can move to from the current position. >>> get_valid_pos((1, 3), 4) [(2, 1), (0, 1), (3, 2)] """ y, x = position positions = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] permissible_positions = [] for inner_position in positions: y_test, x_test = inner_position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(inner_position) return permissible_positions def is_complete(board: list[list[int]]) -> bool: """ Check if the board (matrix) has been completely filled with non-zero values. >>> is_complete([[1]]) True >>> is_complete([[1, 2], [3, 0]]) False """ return not any(elem == 0 for row in board for elem in row) def open_knight_tour_helper( board: list[list[int]], pos: tuple[int, int], curr: int ) -> bool: """ Helper function to solve knight tour problem. """ if is_complete(board): return True for position in get_valid_pos(pos, len(board)): y, x = position if board[y][x] == 0: board[y][x] = curr + 1 if open_knight_tour_helper(board, position, curr + 1): return True board[y][x] = 0 return False def open_knight_tour(n: int) -> list[list[int]]: """ Find the solution for the knight tour problem for a board of size n. Raises ValueError if the tour cannot be performed for the given size. >>> open_knight_tour(1) [[1]] >>> open_knight_tour(2) Traceback (most recent call last): ... ValueError: Open Knight Tour cannot be performed on a board of size 2 """ board = [[0 for i in range(n)] for j in range(n)] for i in range(n): for j in range(n): board[i][j] = 1 if open_knight_tour_helper(board, (i, j), 1): return board board[i][j] = 0 msg = f"Open Knight Tour cannot be performed on a board of size {n}" raise ValueError(msg) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/word_break.py
backtracking/word_break.py
""" Word Break Problem is a well-known problem in computer science. Given a string and a dictionary of words, the task is to determine if the string can be segmented into a sequence of one or more dictionary words. Wikipedia: https://en.wikipedia.org/wiki/Word_break_problem """ def backtrack(input_string: str, word_dict: set[str], start: int) -> bool: """ Helper function that uses backtracking to determine if a valid word segmentation is possible starting from index 'start'. Parameters: input_string (str): The input string to be segmented. word_dict (set[str]): A set of valid dictionary words. start (int): The starting index of the substring to be checked. Returns: bool: True if a valid segmentation is possible, otherwise False. Example: >>> backtrack("leetcode", {"leet", "code"}, 0) True >>> backtrack("applepenapple", {"apple", "pen"}, 0) True >>> backtrack("catsandog", {"cats", "dog", "sand", "and", "cat"}, 0) False """ # Base case: if the starting index has reached the end of the string if start == len(input_string): return True # Try every possible substring from 'start' to 'end' for end in range(start + 1, len(input_string) + 1): if input_string[start:end] in word_dict and backtrack( input_string, word_dict, end ): return True return False def word_break(input_string: str, word_dict: set[str]) -> bool: """ Determines if the input string can be segmented into a sequence of valid dictionary words using backtracking. Parameters: input_string (str): The input string to segment. word_dict (set[str]): The set of valid words. Returns: bool: True if the string can be segmented into valid words, otherwise False. Example: >>> word_break("leetcode", {"leet", "code"}) True >>> word_break("applepenapple", {"apple", "pen"}) True >>> word_break("catsandog", {"cats", "dog", "sand", "and", "cat"}) False """ return backtrack(input_string, word_dict, 0)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/hamiltonian_cycle.py
backtracking/hamiltonian_cycle.py
""" A Hamiltonian cycle (Hamiltonian circuit) is a graph cycle through a graph that visits each node exactly once. Determining whether such paths and cycles exist in graphs is the 'Hamiltonian path problem', which is NP-complete. Wikipedia: https://en.wikipedia.org/wiki/Hamiltonian_path """ def valid_connection( graph: list[list[int]], next_ver: int, curr_ind: int, path: list[int] ) -> bool: """ Checks whether it is possible to add next into path by validating 2 statements 1. There should be path between current and next vertex 2. Next vertex should not be in path If both validations succeed we return True, saying that it is possible to connect this vertices, otherwise we return False Case 1:Use exact graph as in main function, with initialized values >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 1], ... [0, 1, 1, 1, 0]] >>> path = [0, -1, -1, -1, -1, 0] >>> curr_ind = 1 >>> next_ver = 1 >>> valid_connection(graph, next_ver, curr_ind, path) True Case 2: Same graph, but trying to connect to node that is already in path >>> path = [0, 1, 2, 4, -1, 0] >>> curr_ind = 4 >>> next_ver = 1 >>> valid_connection(graph, next_ver, curr_ind, path) False """ # 1. Validate that path exists between current and next vertices if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path) def util_hamilton_cycle(graph: list[list[int]], path: list[int], curr_ind: int) -> bool: """ Pseudo-Code Base Case: 1. Check if we visited all of vertices 1.1 If last visited vertex has path to starting vertex return True either return False Recursive Step: 2. Iterate over each vertex Check if next vertex is valid for transiting from current vertex 2.1 Remember next vertex as next transition 2.2 Do recursive call and check if going to this vertex solves problem 2.3 If next vertex leads to solution return True 2.4 Else backtrack, delete remembered vertex Case 1: Use exact graph as in main function, with initialized values >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 1], ... [0, 1, 1, 1, 0]] >>> path = [0, -1, -1, -1, -1, 0] >>> curr_ind = 1 >>> util_hamilton_cycle(graph, path, curr_ind) True >>> path [0, 1, 2, 4, 3, 0] Case 2: Use exact graph as in previous case, but in the properties taken from middle of calculation >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 1], ... [0, 1, 1, 1, 0]] >>> path = [0, 1, 2, -1, -1, 0] >>> curr_ind = 3 >>> util_hamilton_cycle(graph, path, curr_ind) True >>> path [0, 1, 2, 4, 3, 0] """ # Base Case if curr_ind == len(graph): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(len(graph)): if valid_connection(graph, next_ver, curr_ind, path): # Insert current vertex into path as next transition path[curr_ind] = next_ver # Validate created path if util_hamilton_cycle(graph, path, curr_ind + 1): return True # Backtrack path[curr_ind] = -1 return False def hamilton_cycle(graph: list[list[int]], start_index: int = 0) -> list[int]: r""" Wrapper function to call subroutine called util_hamilton_cycle, which will either return array of vertices indicating hamiltonian cycle or an empty list indicating that hamiltonian cycle was not found. Case 1: Following graph consists of 5 edges. If we look closely, we can see that there are multiple Hamiltonian cycles. For example one result is when we iterate like: (0)->(1)->(2)->(4)->(3)->(0) (0)---(1)---(2) | / \ | | / \ | | / \ | |/ \| (3)---------(4) >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 1], ... [0, 1, 1, 1, 0]] >>> hamilton_cycle(graph) [0, 1, 2, 4, 3, 0] Case 2: Same Graph as it was in Case 1, changed starting index from default to 3 (0)---(1)---(2) | / \ | | / \ | | / \ | |/ \| (3)---------(4) >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 1], ... [0, 1, 1, 1, 0]] >>> hamilton_cycle(graph, 3) [3, 0, 1, 2, 4, 3] Case 3: Following Graph is exactly what it was before, but edge 3-4 is removed. Result is that there is no Hamiltonian Cycle anymore. (0)---(1)---(2) | / \ | | / \ | | / \ | |/ \| (3) (4) >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 0], ... [0, 1, 1, 0, 0]] >>> hamilton_cycle(graph,4) [] """ # Initialize path with -1, indicating that we have not visited them yet path = [-1] * (len(graph) + 1) # initialize start and end of path with starting index path[0] = path[-1] = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(graph, path, 1) else []
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/crossword_puzzle_solver.py
backtracking/crossword_puzzle_solver.py
# https://www.geeksforgeeks.org/solve-crossword-puzzle/ def is_valid( puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool ) -> bool: """ Check if a word can be placed at the given position. >>> puzzle = [ ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''] ... ] >>> is_valid(puzzle, 'word', 0, 0, True) True >>> puzzle = [ ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''] ... ] >>> is_valid(puzzle, 'word', 0, 0, False) True """ for i in range(len(word)): if vertical: if row + i >= len(puzzle) or puzzle[row + i][col] != "": return False elif col + i >= len(puzzle[0]) or puzzle[row][col + i] != "": return False return True def place_word( puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool ) -> None: """ Place a word at the given position. >>> puzzle = [ ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''] ... ] >>> place_word(puzzle, 'word', 0, 0, True) >>> puzzle [['w', '', '', ''], ['o', '', '', ''], ['r', '', '', ''], ['d', '', '', '']] """ for i, char in enumerate(word): if vertical: puzzle[row + i][col] = char else: puzzle[row][col + i] = char def remove_word( puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool ) -> None: """ Remove a word from the given position. >>> puzzle = [ ... ['w', '', '', ''], ... ['o', '', '', ''], ... ['r', '', '', ''], ... ['d', '', '', ''] ... ] >>> remove_word(puzzle, 'word', 0, 0, True) >>> puzzle [['', '', '', ''], ['', '', '', ''], ['', '', '', ''], ['', '', '', '']] """ for i in range(len(word)): if vertical: puzzle[row + i][col] = "" else: puzzle[row][col + i] = "" def solve_crossword(puzzle: list[list[str]], words: list[str]) -> bool: """ Solve the crossword puzzle using backtracking. >>> puzzle = [ ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''] ... ] >>> words = ['word', 'four', 'more', 'last'] >>> solve_crossword(puzzle, words) True >>> puzzle = [ ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''] ... ] >>> words = ['word', 'four', 'more', 'paragraphs'] >>> solve_crossword(puzzle, words) False """ for row in range(len(puzzle)): for col in range(len(puzzle[0])): if puzzle[row][col] == "": for word in words: for vertical in [True, False]: if is_valid(puzzle, word, row, col, vertical): place_word(puzzle, word, row, col, vertical) words.remove(word) if solve_crossword(puzzle, words): return True words.append(word) remove_word(puzzle, word, row, col, vertical) return False return True if __name__ == "__main__": PUZZLE = [[""] * 3 for _ in range(3)] WORDS = ["cat", "dog", "car"] if solve_crossword(PUZZLE, WORDS): print("Solution found:") for row in PUZZLE: print(" ".join(row)) else: print("No solution found:")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/n_queens.py
backtracking/n_queens.py
""" The nqueens problem is of placing N queens on a N * N chess board such that no queen can attack any other queens placed on that chess board. This means that one queen cannot have any other queen on its horizontal, vertical and diagonal lines. """ from __future__ import annotations solution = [] def is_safe(board: list[list[int]], row: int, column: int) -> bool: """ This function returns a boolean value True if it is safe to place a queen there considering the current state of the board. Parameters: board (2D matrix): The chessboard row, column: Coordinates of the cell on the board Returns: Boolean Value >>> is_safe([[0, 0, 0], [0, 0, 0], [0, 0, 0]], 1, 1) True >>> is_safe([[0, 1, 0], [0, 0, 0], [0, 0, 0]], 1, 1) False >>> is_safe([[1, 0, 0], [0, 0, 0], [0, 0, 0]], 1, 1) False >>> is_safe([[0, 0, 1], [0, 0, 0], [0, 0, 0]], 1, 1) False """ n = len(board) # Size of the board # Check if there is any queen in the same upper column, # left upper diagonal and right upper diagonal return ( all(board[i][j] != 1 for i, j in zip(range(row), [column] * row)) and all( board[i][j] != 1 for i, j in zip(range(row - 1, -1, -1), range(column - 1, -1, -1)) ) and all( board[i][j] != 1 for i, j in zip(range(row - 1, -1, -1), range(column + 1, n)) ) ) def solve(board: list[list[int]], row: int) -> bool: """ This function creates a state space tree and calls the safe function until it receives a False Boolean and terminates that branch and backtracks to the next possible solution branch. """ if row >= len(board): """ If the row number exceeds N, we have a board with a successful combination and that combination is appended to the solution list and the board is printed. """ solution.append(board) printboard(board) print() return True for i in range(len(board)): """ For every row, it iterates through each column to check if it is feasible to place a queen there. If all the combinations for that particular branch are successful, the board is reinitialized for the next possible combination. """ if is_safe(board, row, i): board[row][i] = 1 solve(board, row + 1) board[row][i] = 0 return False def printboard(board: list[list[int]]) -> None: """ Prints the boards that have a successful combination. """ for i in range(len(board)): for j in range(len(board)): if board[i][j] == 1: print("Q", end=" ") # Queen is present else: print(".", end=" ") # Empty cell print() # Number of queens (e.g., n=8 for an 8x8 board) n = 8 board = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print("The total number of solutions are:", len(solution))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/all_permutations.py
backtracking/all_permutations.py
""" In this problem, we want to determine all possible permutations of the given sequence. We use backtracking to solve this problem. Time complexity: O(n! * n), where n denotes the length of the given sequence. """ from __future__ import annotations def generate_all_permutations(sequence: list[int | str]) -> None: create_state_space_tree(sequence, [], 0, [0 for i in range(len(sequence))]) def create_state_space_tree( sequence: list[int | str], current_sequence: list[int | str], index: int, index_used: list[int], ) -> None: """ Creates a state space tree to iterate through each branch using DFS. We know that each state has exactly len(sequence) - index children. It terminates when it reaches the end of the given sequence. :param sequence: The input sequence for which permutations are generated. :param current_sequence: The current permutation being built. :param index: The current index in the sequence. :param index_used: list to track which elements are used in permutation. Example 1: >>> sequence = [1, 2, 3] >>> current_sequence = [] >>> index_used = [False, False, False] >>> create_state_space_tree(sequence, current_sequence, 0, index_used) [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1] Example 2: >>> sequence = ["A", "B", "C"] >>> current_sequence = [] >>> index_used = [False, False, False] >>> create_state_space_tree(sequence, current_sequence, 0, index_used) ['A', 'B', 'C'] ['A', 'C', 'B'] ['B', 'A', 'C'] ['B', 'C', 'A'] ['C', 'A', 'B'] ['C', 'B', 'A'] Example 3: >>> sequence = [1] >>> current_sequence = [] >>> index_used = [False] >>> create_state_space_tree(sequence, current_sequence, 0, index_used) [1] """ if index == len(sequence): print(current_sequence) return for i in range(len(sequence)): if not index_used[i]: current_sequence.append(sequence[i]) index_used[i] = True create_state_space_tree(sequence, current_sequence, index + 1, index_used) current_sequence.pop() index_used[i] = False """ remove the comment to take an input from the user print("Enter the elements") sequence = list(map(int, input().split())) """ sequence: list[int | str] = [3, 1, 2, 4] generate_all_permutations(sequence) sequence_2: list[int | str] = ["A", "B", "C"] generate_all_permutations(sequence_2)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/generate_parentheses_iterative.py
backtracking/generate_parentheses_iterative.py
def generate_parentheses_iterative(length: int) -> list: """ Generate all valid combinations of parentheses (Iterative Approach). The algorithm works as follows: 1. Initialize an empty list to store the combinations. 2. Initialize a stack to keep track of partial combinations. 3. Start with empty string and push it onstack along with the counts of '(' and ')'. 4. While the stack is not empty: a. Pop a partial combination and its open and close counts from the stack. b. If the combination length is equal to 2*length, add it to the result. c. If open count < length, push new combination with added '(' on stack. d. If close count < open count, push new combination with added ')' on stack. 5. Return the result containing all valid combinations. Args: length: The desired length of the parentheses combinations Returns: A list of strings representing valid combinations of parentheses Time Complexity: O(2^(2*length)) Space Complexity: O(2^(2*length)) >>> generate_parentheses_iterative(3) ['()()()', '()(())', '(())()', '(()())', '((()))'] >>> generate_parentheses_iterative(2) ['()()', '(())'] >>> generate_parentheses_iterative(1) ['()'] >>> generate_parentheses_iterative(0) [''] """ result = [] stack = [] # Each element in stack is a tuple (current_combination, open_count, close_count) stack.append(("", 0, 0)) while stack: current_combination, open_count, close_count = stack.pop() if len(current_combination) == 2 * length: result.append(current_combination) if open_count < length: stack.append((current_combination + "(", open_count + 1, close_count)) if close_count < open_count: stack.append((current_combination + ")", open_count, close_count + 1)) return result if __name__ == "__main__": import doctest doctest.testmod() print(generate_parentheses_iterative(3))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/rat_in_maze.py
backtracking/rat_in_maze.py
from __future__ import annotations def solve_maze( maze: list[list[int]], source_row: int, source_column: int, destination_row: int, destination_column: int, ) -> list[list[int]]: """ This method solves the "rat in maze" problem. Parameters : - maze: A two dimensional matrix of zeros and ones. - source_row: The row index of the starting point. - source_column: The column index of the starting point. - destination_row: The row index of the destination point. - destination_column: The column index of the destination point. Returns: - solution: A 2D matrix representing the solution path if it exists. Raises: - ValueError: If no solution exists or if the source or destination coordinates are invalid. Description: This method navigates through a maze represented as an n by n matrix, starting from a specified source cell and aiming to reach a destination cell. The maze consists of walls (1s) and open paths (0s). By providing custom row and column values, the source and destination cells can be adjusted. >>> maze = [[0, 1, 0, 1, 1], ... [0, 0, 0, 0, 0], ... [1, 0, 1, 0, 1], ... [0, 0, 1, 0, 0], ... [1, 0, 0, 1, 0]] >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE [[0, 1, 1, 1, 1], [0, 0, 0, 0, 1], [1, 1, 1, 0, 1], [1, 1, 1, 0, 0], [1, 1, 1, 1, 0]] Note: In the output maze, the zeros (0s) represent one of the possible paths from the source to the destination. >>> maze = [[0, 1, 0, 1, 1], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 1], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0]] >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE [[0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 0, 0, 0, 0]] >>> maze = [[0, 0, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE [[0, 0, 0], [1, 1, 0], [1, 1, 0]] >>> maze = [[1, 0, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze,0,1,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE [[1, 0, 0], [1, 1, 0], [1, 1, 0]] >>> maze = [[1, 1, 0, 0, 1, 0, 0, 1], ... [1, 0, 1, 0, 0, 1, 1, 1], ... [0, 1, 0, 1, 0, 0, 1, 0], ... [1, 1, 1, 0, 0, 1, 0, 1], ... [0, 1, 0, 0, 1, 0, 1, 1], ... [0, 0, 0, 1, 1, 1, 0, 1], ... [0, 1, 0, 1, 0, 1, 1, 1], ... [1, 1, 0, 0, 0, 0, 0, 1]] >>> solve_maze(maze,0,2,len(maze)-1,2) # doctest: +NORMALIZE_WHITESPACE [[1, 1, 0, 0, 1, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 1], [1, 1, 1, 1, 0, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 1], [1, 1, 0, 0, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 1, 1]] >>> maze = [[1, 0, 0], ... [0, 1, 1], ... [1, 0, 1]] >>> solve_maze(maze,0,1,len(maze)-1,len(maze)-1) Traceback (most recent call last): ... ValueError: No solution exists! >>> maze = [[0, 0], ... [1, 1]] >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) Traceback (most recent call last): ... ValueError: No solution exists! >>> maze = [[0, 1], ... [1, 0]] >>> solve_maze(maze,2,0,len(maze)-1,len(maze)-1) Traceback (most recent call last): ... ValueError: Invalid source or destination coordinates >>> maze = [[1, 0, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze,0,1,len(maze),len(maze)-1) Traceback (most recent call last): ... ValueError: Invalid source or destination coordinates """ size = len(maze) # Check if source and destination coordinates are Invalid. if not (0 <= source_row <= size - 1 and 0 <= source_column <= size - 1) or ( not (0 <= destination_row <= size - 1 and 0 <= destination_column <= size - 1) ): raise ValueError("Invalid source or destination coordinates") # We need to create solution object to save path. solutions = [[1 for _ in range(size)] for _ in range(size)] solved = run_maze( maze, source_row, source_column, destination_row, destination_column, solutions ) if solved: return solutions else: raise ValueError("No solution exists!") def run_maze( maze: list[list[int]], i: int, j: int, destination_row: int, destination_column: int, solutions: list[list[int]], ) -> bool: """ This method is recursive starting from (i, j) and going in one of four directions: up, down, left, right. If a path is found to destination it returns True otherwise it returns False. Parameters maze: A two dimensional matrix of zeros and ones. i, j : coordinates of matrix solutions: A two dimensional matrix of solutions. Returns: Boolean if path is found True, Otherwise False. """ size = len(maze) # Final check point. if i == destination_row and j == destination_column and maze[i][j] == 0: solutions[i][j] = 0 return True lower_flag = (not i < 0) and (not j < 0) # Check lower bounds upper_flag = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. block_flag = (solutions[i][j]) and (not maze[i][j]) if block_flag: # check visited solutions[i][j] = 0 # check for directions if ( run_maze(maze, i + 1, j, destination_row, destination_column, solutions) or run_maze( maze, i, j + 1, destination_row, destination_column, solutions ) or run_maze( maze, i - 1, j, destination_row, destination_column, solutions ) or run_maze( maze, i, j - 1, destination_row, destination_column, solutions ) ): return True solutions[i][j] = 1 return False return False if __name__ == "__main__": import doctest doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/n_queens_math.py
backtracking/n_queens_math.py
r""" Problem: The n queens problem is: placing N queens on a N * N chess board such that no queen can attack any other queens placed on that chess board. This means that one queen cannot have any other queen on its horizontal, vertical and diagonal lines. Solution: To solve this problem we will use simple math. First we know the queen can move in all the possible ways, we can simplify it in this: vertical, horizontal, diagonal left and diagonal right. We can visualize it like this: left diagonal = \ right diagonal = / On a chessboard vertical movement could be the rows and horizontal movement could be the columns. In programming we can use an array, and in this array each index could be the rows and each value in the array could be the column. For example: . Q . . We have this chessboard with one queen in each column and each queen . . . Q can't attack to each other. Q . . . The array for this example would look like this: [1, 3, 0, 2] . . Q . So if we use an array and we verify that each value in the array is different to each other we know that at least the queens can't attack each other in horizontal and vertical. At this point we have it halfway completed and we will treat the chessboard as a Cartesian plane. Hereinafter we are going to remember basic math, so in the school we learned this formula: Slope of a line: y2 - y1 m = ---------- x2 - x1 This formula allow us to get the slope. For the angles 45º (right diagonal) and 135º (left diagonal) this formula gives us m = 1, and m = -1 respectively. See:: https://www.enotes.com/homework-help/write-equation-line-that-hits-origin-45-degree-1474860 Then we have this other formula: Slope intercept: y = mx + b b is where the line crosses the Y axis (to get more information see: https://www.mathsisfun.com/y_intercept.html), if we change the formula to solve for b we would have: y - mx = b And since we already have the m values for the angles 45º and 135º, this formula would look like this: 45º: y - (1)x = b 45º: y - x = b 135º: y - (-1)x = b 135º: y + x = b y = row x = column Applying these two formulas we can check if a queen in some position is being attacked for another one or vice versa. """ from __future__ import annotations def depth_first_search( possible_board: list[int], diagonal_right_collisions: list[int], diagonal_left_collisions: list[int], boards: list[list[str]], n: int, ) -> None: """ >>> boards = [] >>> depth_first_search([], [], [], boards, 4) >>> for board in boards: ... print(board) ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] ['. . Q . ', 'Q . . . ', '. . . Q ', '. Q . . '] """ # Get next row in the current board (possible_board) to fill it with a queen row = len(possible_board) # If row is equal to the size of the board it means there are a queen in each row in # the current board (possible_board) if row == n: # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] boards.append([". " * i + "Q " + ". " * (n - 1 - i) for i in possible_board]) return # We iterate each column in the row to find all possible results in each row for col in range(n): # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we # learned before: # # 45º: y - x = b or 45: row - col = b # 135º: y + x = b or row + col = b. # # And we verify if the results of this two formulas not exist in their variables # respectively. (diagonal_right_collisions, diagonal_left_collisions) # # If any or these are True it means there is a collision so we continue to the # next value in the for loop. if ( col in possible_board or row - col in diagonal_right_collisions or row + col in diagonal_left_collisions ): continue # If it is False we call dfs function again and we update the inputs depth_first_search( [*possible_board, col], [*diagonal_right_collisions, row - col], [*diagonal_left_collisions, row + col], boards, n, ) def n_queens_solution(n: int) -> None: boards: list[list[str]] = [] depth_first_search([], [], [], boards, n) # Print all the boards for board in boards: for column in board: print(column) print("") print(len(boards), "solutions were found.") if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/sum_of_subsets.py
backtracking/sum_of_subsets.py
""" The sum-of-subsets problem states that a set of non-negative integers, and a value M, determine all possible subsets of the given set whose summation sum equal to given M. Summation of the chosen numbers must be equal to given number M and one number can be used only once. """ def generate_sum_of_subsets_solutions(nums: list[int], max_sum: int) -> list[list[int]]: """ The main function. For list of numbers 'nums' find the subsets with sum equal to 'max_sum' >>> generate_sum_of_subsets_solutions(nums=[3, 34, 4, 12, 5, 2], max_sum=9) [[3, 4, 2], [4, 5]] >>> generate_sum_of_subsets_solutions(nums=[3, 34, 4, 12, 5, 2], max_sum=3) [[3]] >>> generate_sum_of_subsets_solutions(nums=[3, 34, 4, 12, 5, 2], max_sum=1) [] """ result: list[list[int]] = [] path: list[int] = [] num_index = 0 remaining_nums_sum = sum(nums) create_state_space_tree(nums, max_sum, num_index, path, result, remaining_nums_sum) return result def create_state_space_tree( nums: list[int], max_sum: int, num_index: int, path: list[int], result: list[list[int]], remaining_nums_sum: int, ) -> None: """ Creates a state space tree to iterate through each branch using DFS. It terminates the branching of a node when any of the two conditions given below satisfy. This algorithm follows depth-fist-search and backtracks when the node is not branchable. >>> path = [] >>> result = [] >>> create_state_space_tree( ... nums=[1], ... max_sum=1, ... num_index=0, ... path=path, ... result=result, ... remaining_nums_sum=1) >>> path [] >>> result [[1]] """ if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum: return if sum(path) == max_sum: result.append(path) return for index in range(num_index, len(nums)): create_state_space_tree( nums, max_sum, index + 1, [*path, nums[index]], result, remaining_nums_sum - nums[index], ) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/word_search.py
backtracking/word_search.py
""" Author : Alexander Pantyukhin Date : November 24, 2022 Task: Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once. Example: Matrix: --------- |A|B|C|E| |S|F|C|S| |A|D|E|E| --------- Word: "ABCCED" Result: True Implementation notes: Use backtracking approach. At each point, check all neighbors to try to find the next letter of the word. leetcode: https://leetcode.com/problems/word-search/ """ def get_point_key(len_board: int, len_board_column: int, row: int, column: int) -> int: """ Returns the hash key of matrix indexes. >>> get_point_key(10, 20, 1, 0) 200 """ return len_board * len_board_column * row + column def exits_word( board: list[list[str]], word: str, row: int, column: int, word_index: int, visited_points_set: set[int], ) -> bool: """ Return True if it's possible to search the word suffix starting from the word_index. >>> exits_word([["A"]], "B", 0, 0, 0, set()) False """ if board[row][column] != word[word_index]: return False if word_index == len(word) - 1: return True traverts_directions = [(0, 1), (0, -1), (-1, 0), (1, 0)] len_board = len(board) len_board_column = len(board[0]) for direction in traverts_directions: next_i = row + direction[0] next_j = column + direction[1] if not (0 <= next_i < len_board and 0 <= next_j < len_board_column): continue key = get_point_key(len_board, len_board_column, next_i, next_j) if key in visited_points_set: continue visited_points_set.add(key) if exits_word(board, word, next_i, next_j, word_index + 1, visited_points_set): return True visited_points_set.remove(key) return False def word_exists(board: list[list[str]], word: str) -> bool: """ >>> word_exists([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCCED") True >>> word_exists([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "SEE") True >>> word_exists([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCB") False >>> word_exists([["A"]], "A") True >>> word_exists([["B", "A", "A"], ["A", "A", "A"], ["A", "B", "A"]], "ABB") False >>> word_exists([["A"]], 123) Traceback (most recent call last): ... ValueError: The word parameter should be a string of length greater than 0. >>> word_exists([["A"]], "") Traceback (most recent call last): ... ValueError: The word parameter should be a string of length greater than 0. >>> word_exists([[]], "AB") Traceback (most recent call last): ... ValueError: The board should be a non empty matrix of single chars strings. >>> word_exists([], "AB") Traceback (most recent call last): ... ValueError: The board should be a non empty matrix of single chars strings. >>> word_exists([["A"], [21]], "AB") Traceback (most recent call last): ... ValueError: The board should be a non empty matrix of single chars strings. """ # Validate board board_error_message = ( "The board should be a non empty matrix of single chars strings." ) len_board = len(board) if not isinstance(board, list) or len(board) == 0: raise ValueError(board_error_message) for row in board: if not isinstance(row, list) or len(row) == 0: raise ValueError(board_error_message) for item in row: if not isinstance(item, str) or len(item) != 1: raise ValueError(board_error_message) # Validate word if not isinstance(word, str) or len(word) == 0: raise ValueError( "The word parameter should be a string of length greater than 0." ) len_board_column = len(board[0]) for i in range(len_board): for j in range(len_board_column): if exits_word( board, word, i, j, 0, {get_point_key(len_board, len_board_column, i, j)} ): return True return False if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/match_word_pattern.py
backtracking/match_word_pattern.py
def match_word_pattern(pattern: str, input_string: str) -> bool: """ Determine if a given pattern matches a string using backtracking. pattern: The pattern to match. input_string: The string to match against the pattern. return: True if the pattern matches the string, False otherwise. >>> match_word_pattern("aba", "GraphTreesGraph") True >>> match_word_pattern("xyx", "PythonRubyPython") True >>> match_word_pattern("GG", "PythonJavaPython") False """ def backtrack(pattern_index: int, str_index: int) -> bool: """ >>> backtrack(0, 0) True >>> backtrack(0, 1) True >>> backtrack(0, 4) False """ if pattern_index == len(pattern) and str_index == len(input_string): return True if pattern_index == len(pattern) or str_index == len(input_string): return False char = pattern[pattern_index] if char in pattern_map: mapped_str = pattern_map[char] if input_string.startswith(mapped_str, str_index): return backtrack(pattern_index + 1, str_index + len(mapped_str)) else: return False for end in range(str_index + 1, len(input_string) + 1): substr = input_string[str_index:end] if substr in str_map: continue pattern_map[char] = substr str_map[substr] = char if backtrack(pattern_index + 1, end): return True del pattern_map[char] del str_map[substr] return False pattern_map: dict[str, str] = {} str_map: dict[str, str] = {} return backtrack(0, 0) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/all_subsequences.py
backtracking/all_subsequences.py
""" In this problem, we want to determine all possible subsequences of the given sequence. We use backtracking to solve this problem. Time complexity: O(2^n), where n denotes the length of the given sequence. """ from __future__ import annotations from typing import Any def generate_all_subsequences(sequence: list[Any]) -> None: create_state_space_tree(sequence, [], 0) def create_state_space_tree( sequence: list[Any], current_subsequence: list[Any], index: int ) -> None: """ Creates a state space tree to iterate through each branch using DFS. We know that each state has exactly two children. It terminates when it reaches the end of the given sequence. :param sequence: The input sequence for which subsequences are generated. :param current_subsequence: The current subsequence being built. :param index: The current index in the sequence. Example: >>> sequence = [3, 2, 1] >>> current_subsequence = [] >>> create_state_space_tree(sequence, current_subsequence, 0) [] [1] [2] [2, 1] [3] [3, 1] [3, 2] [3, 2, 1] >>> sequence = ["A", "B"] >>> current_subsequence = [] >>> create_state_space_tree(sequence, current_subsequence, 0) [] ['B'] ['A'] ['A', 'B'] >>> sequence = [] >>> current_subsequence = [] >>> create_state_space_tree(sequence, current_subsequence, 0) [] >>> sequence = [1, 2, 3, 4] >>> current_subsequence = [] >>> create_state_space_tree(sequence, current_subsequence, 0) [] [4] [3] [3, 4] [2] [2, 4] [2, 3] [2, 3, 4] [1] [1, 4] [1, 3] [1, 3, 4] [1, 2] [1, 2, 4] [1, 2, 3] [1, 2, 3, 4] """ if index == len(sequence): print(current_subsequence) return create_state_space_tree(sequence, current_subsequence, index + 1) current_subsequence.append(sequence[index]) create_state_space_tree(sequence, current_subsequence, index + 1) current_subsequence.pop() if __name__ == "__main__": seq: list[Any] = [1, 2, 3] generate_all_subsequences(seq) seq.clear() seq.extend(["A", "B", "C"]) generate_all_subsequences(seq)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/minimax.py
backtracking/minimax.py
""" Minimax helps to achieve maximum score in a game by checking all possible moves depth is current depth in game tree. nodeIndex is index of current node in scores[]. if move is of maximizer return true else false leaves of game tree is stored in scores[] height is maximum height of Game tree """ from __future__ import annotations import math def minimax( depth: int, node_index: int, is_max: bool, scores: list[int], height: float ) -> int: """ This function implements the minimax algorithm, which helps achieve the optimal score for a player in a two-player game by checking all possible moves. If the player is the maximizer, then the score is maximized. If the player is the minimizer, then the score is minimized. Parameters: - depth: Current depth in the game tree. - node_index: Index of the current node in the scores list. - is_max: A boolean indicating whether the current move is for the maximizer (True) or minimizer (False). - scores: A list containing the scores of the leaves of the game tree. - height: The maximum height of the game tree. Returns: - An integer representing the optimal score for the current player. >>> import math >>> scores = [90, 23, 6, 33, 21, 65, 123, 34423] >>> height = math.log(len(scores), 2) >>> minimax(0, 0, True, scores, height) 65 >>> minimax(-1, 0, True, scores, height) Traceback (most recent call last): ... ValueError: Depth cannot be less than 0 >>> minimax(0, 0, True, [], 2) Traceback (most recent call last): ... ValueError: Scores cannot be empty >>> scores = [3, 5, 2, 9, 12, 5, 23, 23] >>> height = math.log(len(scores), 2) >>> minimax(0, 0, True, scores, height) 12 """ if depth < 0: raise ValueError("Depth cannot be less than 0") if len(scores) == 0: raise ValueError("Scores cannot be empty") # Base case: If the current depth equals the height of the tree, # return the score of the current node. if depth == height: return scores[node_index] # If it's the maximizer's turn, choose the maximum score # between the two possible moves. if is_max: return max( minimax(depth + 1, node_index * 2, False, scores, height), minimax(depth + 1, node_index * 2 + 1, False, scores, height), ) # If it's the minimizer's turn, choose the minimum score # between the two possible moves. return min( minimax(depth + 1, node_index * 2, True, scores, height), minimax(depth + 1, node_index * 2 + 1, True, scores, height), ) def main() -> None: # Sample scores and height calculation scores = [90, 23, 6, 33, 21, 65, 123, 34423] height = math.log(len(scores), 2) # Calculate and print the optimal value using the minimax algorithm print("Optimal value : ", end="") print(minimax(0, 0, True, scores, height)) if __name__ == "__main__": import doctest doctest.testmod() main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/all_combinations.py
backtracking/all_combinations.py
""" In this problem, we want to determine all possible combinations of k numbers out of 1 ... n. We use backtracking to solve this problem. Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!))), """ from __future__ import annotations from itertools import combinations def combination_lists(n: int, k: int) -> list[list[int]]: """ Generates all possible combinations of k numbers out of 1 ... n using itertools. >>> combination_lists(n=4, k=2) [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] """ return [list(x) for x in combinations(range(1, n + 1), k)] def generate_all_combinations(n: int, k: int) -> list[list[int]]: """ Generates all possible combinations of k numbers out of 1 ... n using backtracking. >>> generate_all_combinations(n=4, k=2) [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] >>> generate_all_combinations(n=0, k=0) [[]] >>> generate_all_combinations(n=10, k=-1) Traceback (most recent call last): ... ValueError: k must not be negative >>> generate_all_combinations(n=-1, k=10) Traceback (most recent call last): ... ValueError: n must not be negative >>> generate_all_combinations(n=5, k=4) [[1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]] >>> generate_all_combinations(n=3, k=3) [[1, 2, 3]] >>> generate_all_combinations(n=3, k=1) [[1], [2], [3]] >>> generate_all_combinations(n=1, k=0) [[]] >>> generate_all_combinations(n=1, k=1) [[1]] >>> from itertools import combinations >>> all(generate_all_combinations(n, k) == combination_lists(n, k) ... for n in range(1, 6) for k in range(1, 6)) True """ if k < 0: raise ValueError("k must not be negative") if n < 0: raise ValueError("n must not be negative") result: list[list[int]] = [] create_all_state(1, n, k, [], result) return result def create_all_state( increment: int, total_number: int, level: int, current_list: list[int], total_list: list[list[int]], ) -> None: """ Helper function to recursively build all combinations. >>> create_all_state(1, 4, 2, [], result := []) >>> result [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] >>> create_all_state(1, 3, 3, [], result := []) >>> result [[1, 2, 3]] >>> create_all_state(2, 2, 1, [1], result := []) >>> result [[1, 2]] >>> create_all_state(1, 0, 0, [], result := []) >>> result [[]] >>> create_all_state(1, 4, 0, [1, 2], result := []) >>> result [[1, 2]] >>> create_all_state(5, 4, 2, [1, 2], result := []) >>> result [] """ if level == 0: total_list.append(current_list[:]) return for i in range(increment, total_number - level + 2): current_list.append(i) create_all_state(i + 1, total_number, level - 1, current_list, total_list) current_list.pop() if __name__ == "__main__": from doctest import testmod testmod() print(generate_all_combinations(n=4, k=2)) tests = ((n, k) for n in range(1, 5) for k in range(1, 5)) for n, k in tests: print(n, k, generate_all_combinations(n, k) == combination_lists(n, k)) print("Benchmark:") from timeit import timeit for func in ("combination_lists", "generate_all_combinations"): print(f"{func:>25}(): {timeit(f'{func}(n=4, k = 2)', globals=globals())}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/coloring.py
backtracking/coloring.py
""" Graph Coloring also called "m coloring problem" consists of coloring a given graph with at most m colors such that no adjacent vertices are assigned the same color Wikipedia: https://en.wikipedia.org/wiki/Graph_coloring """ def valid_coloring( neighbours: list[int], colored_vertices: list[int], color: int ) -> bool: """ For each neighbour check if the coloring constraint is satisfied If any of the neighbours fail the constraint return False If all neighbours validate the constraint return True >>> neighbours = [0,1,0,1,0] >>> colored_vertices = [0, 2, 1, 2, 0] >>> color = 1 >>> valid_coloring(neighbours, colored_vertices, color) True >>> color = 2 >>> valid_coloring(neighbours, colored_vertices, color) False """ # Does any neighbour not satisfy the constraints return not any( neighbour == 1 and colored_vertices[i] == color for i, neighbour in enumerate(neighbours) ) def util_color( graph: list[list[int]], max_colors: int, colored_vertices: list[int], index: int ) -> bool: """ Pseudo-Code Base Case: 1. Check if coloring is complete 1.1 If complete return True (meaning that we successfully colored the graph) Recursive Step: 2. Iterates over each color: Check if the current coloring is valid: 2.1. Color given vertex 2.2. Do recursive call, check if this coloring leads to a solution 2.4. if current coloring leads to a solution return 2.5. Uncolor given vertex >>> graph = [[0, 1, 0, 0, 0], ... [1, 0, 1, 0, 1], ... [0, 1, 0, 1, 0], ... [0, 1, 1, 0, 0], ... [0, 1, 0, 0, 0]] >>> max_colors = 3 >>> colored_vertices = [0, 1, 0, 0, 0] >>> index = 3 >>> util_color(graph, max_colors, colored_vertices, index) True >>> max_colors = 2 >>> util_color(graph, max_colors, colored_vertices, index) False """ # Base Case if index == len(graph): return True # Recursive Step for i in range(max_colors): if valid_coloring(graph[index], colored_vertices, i): # Color current vertex colored_vertices[index] = i # Validate coloring if util_color(graph, max_colors, colored_vertices, index + 1): return True # Backtrack colored_vertices[index] = -1 return False def color(graph: list[list[int]], max_colors: int) -> list[int]: """ Wrapper function to call subroutine called util_color which will either return True or False. If True is returned colored_vertices list is filled with correct colorings >>> graph = [[0, 1, 0, 0, 0], ... [1, 0, 1, 0, 1], ... [0, 1, 0, 1, 0], ... [0, 1, 1, 0, 0], ... [0, 1, 0, 0, 0]] >>> max_colors = 3 >>> color(graph, max_colors) [0, 1, 0, 2, 0] >>> max_colors = 2 >>> color(graph, max_colors) [] """ colored_vertices = [-1] * len(graph) if util_color(graph, max_colors, colored_vertices, 0): return colored_vertices return []
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/word_ladder.py
backtracking/word_ladder.py
""" Word Ladder is a classic problem in computer science. The problem is to transform a start word into an end word by changing one letter at a time. Each intermediate word must be a valid word from a given list of words. The goal is to find a transformation sequence from the start word to the end word. Wikipedia: https://en.wikipedia.org/wiki/Word_ladder """ import string def backtrack( current_word: str, path: list[str], end_word: str, word_set: set[str] ) -> list[str]: """ Helper function to perform backtracking to find the transformation from the current_word to the end_word. Parameters: current_word (str): The current word in the transformation sequence. path (list[str]): The list of transformations from begin_word to current_word. end_word (str): The target word for transformation. word_set (set[str]): The set of valid words for transformation. Returns: list[str]: The list of transformations from begin_word to end_word. Returns an empty list if there is no valid transformation from current_word to end_word. Example: >>> backtrack("hit", ["hit"], "cog", {"hot", "dot", "dog", "lot", "log", "cog"}) ['hit', 'hot', 'dot', 'lot', 'log', 'cog'] >>> backtrack("hit", ["hit"], "cog", {"hot", "dot", "dog", "lot", "log"}) [] >>> backtrack("lead", ["lead"], "gold", {"load", "goad", "gold", "lead", "lord"}) ['lead', 'lead', 'load', 'goad', 'gold'] >>> backtrack("game", ["game"], "code", {"came", "cage", "code", "cade", "gave"}) ['game', 'came', 'cade', 'code'] """ # Base case: If the current word is the end word, return the path if current_word == end_word: return path # Try all possible single-letter transformations for i in range(len(current_word)): for c in string.ascii_lowercase: # Try changing each letter transformed_word = current_word[:i] + c + current_word[i + 1 :] if transformed_word in word_set: word_set.remove(transformed_word) # Recur with the new word added to the path result = backtrack( transformed_word, [*path, transformed_word], end_word, word_set ) if result: # valid transformation found return result word_set.add(transformed_word) # backtrack return [] # No valid transformation found def word_ladder(begin_word: str, end_word: str, word_set: set[str]) -> list[str]: """ Solve the Word Ladder problem using Backtracking and return the list of transformations from begin_word to end_word. Parameters: begin_word (str): The word from which the transformation starts. end_word (str): The target word for transformation. word_list (list[str]): The list of valid words for transformation. Returns: list[str]: The list of transformations from begin_word to end_word. Returns an empty list if there is no valid transformation. Example: >>> word_ladder("hit", "cog", ["hot", "dot", "dog", "lot", "log", "cog"]) ['hit', 'hot', 'dot', 'lot', 'log', 'cog'] >>> word_ladder("hit", "cog", ["hot", "dot", "dog", "lot", "log"]) [] >>> word_ladder("lead", "gold", ["load", "goad", "gold", "lead", "lord"]) ['lead', 'lead', 'load', 'goad', 'gold'] >>> word_ladder("game", "code", ["came", "cage", "code", "cade", "gave"]) ['game', 'came', 'cade', 'code'] """ if end_word not in word_set: # no valid transformation possible return [] # Perform backtracking starting from the begin_word return backtrack(begin_word, [begin_word], end_word, word_set)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/__init__.py
backtracking/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/power_sum.py
backtracking/power_sum.py
""" Problem source: https://www.hackerrank.com/challenges/the-power-sum/problem Find the number of ways that a given integer X, can be expressed as the sum of the Nth powers of unique, natural numbers. For example, if X=13 and N=2. We have to find all combinations of unique squares adding up to 13. The only solution is 2^2+3^2. Constraints: 1<=X<=1000, 2<=N<=10. """ def backtrack( needed_sum: int, power: int, current_number: int, current_sum: int, solutions_count: int, ) -> tuple[int, int]: """ >>> backtrack(13, 2, 1, 0, 0) (0, 1) >>> backtrack(10, 2, 1, 0, 0) (0, 1) >>> backtrack(10, 3, 1, 0, 0) (0, 0) >>> backtrack(20, 2, 1, 0, 0) (0, 1) >>> backtrack(15, 10, 1, 0, 0) (0, 0) >>> backtrack(16, 2, 1, 0, 0) (0, 1) >>> backtrack(20, 1, 1, 0, 0) (0, 64) """ if current_sum == needed_sum: # If the sum of the powers is equal to needed_sum, then we have a solution. solutions_count += 1 return current_sum, solutions_count i_to_n = current_number**power if current_sum + i_to_n <= needed_sum: # If the sum of the powers is less than needed_sum, then continue adding powers. current_sum += i_to_n current_sum, solutions_count = backtrack( needed_sum, power, current_number + 1, current_sum, solutions_count ) current_sum -= i_to_n if i_to_n < needed_sum: # If the power of i is less than needed_sum, then try with the next power. current_sum, solutions_count = backtrack( needed_sum, power, current_number + 1, current_sum, solutions_count ) return current_sum, solutions_count def solve(needed_sum: int, power: int) -> int: """ >>> solve(13, 2) 1 >>> solve(10, 2) 1 >>> solve(10, 3) 0 >>> solve(20, 2) 1 >>> solve(15, 10) 0 >>> solve(16, 2) 1 >>> solve(20, 1) Traceback (most recent call last): ... ValueError: Invalid input needed_sum must be between 1 and 1000, power between 2 and 10. >>> solve(-10, 5) Traceback (most recent call last): ... ValueError: Invalid input needed_sum must be between 1 and 1000, power between 2 and 10. """ if not (1 <= needed_sum <= 1000 and 2 <= power <= 10): raise ValueError( "Invalid input\n" "needed_sum must be between 1 and 1000, power between 2 and 10." ) return backtrack(needed_sum, power, 1, 0, 0)[1] # Return the solutions_count if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/combination_sum.py
backtracking/combination_sum.py
""" In the Combination Sum problem, we are given a list consisting of distinct integers. We need to find all the combinations whose sum equals to target given. We can use an element more than one. Time complexity(Average Case): O(n!) Constraints: 1 <= candidates.length <= 30 2 <= candidates[i] <= 40 All elements of candidates are distinct. 1 <= target <= 40 """ def backtrack( candidates: list, path: list, answer: list, target: int, previous_index: int ) -> None: """ A recursive function that searches for possible combinations. Backtracks in case of a bigger current combination value than the target value. Parameters ---------- previous_index: Last index from the previous search target: The value we need to obtain by summing our integers in the path list. answer: A list of possible combinations path: Current combination candidates: A list of integers we can use. """ if target == 0: answer.append(path.copy()) else: for index in range(previous_index, len(candidates)): if target >= candidates[index]: path.append(candidates[index]) backtrack(candidates, path, answer, target - candidates[index], index) path.pop(len(path) - 1) def combination_sum(candidates: list, target: int) -> list: """ >>> combination_sum([2, 3, 5], 8) [[2, 2, 2, 2], [2, 3, 3], [3, 5]] >>> combination_sum([2, 3, 6, 7], 7) [[2, 2, 3], [7]] >>> combination_sum([-8, 2.3, 0], 1) Traceback (most recent call last): ... ValueError: All elements in candidates must be non-negative >>> combination_sum([], 1) Traceback (most recent call last): ... ValueError: Candidates list should not be empty """ if not candidates: raise ValueError("Candidates list should not be empty") if any(x < 0 for x in candidates): raise ValueError("All elements in candidates must be non-negative") path = [] # type: list[int] answer = [] # type: list[int] backtrack(candidates, path, answer, target, 0) return answer def main() -> None: print(combination_sum([-8, 2.3, 0], 1)) if __name__ == "__main__": import doctest doctest.testmod() main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/generate_parentheses.py
backtracking/generate_parentheses.py
""" author: Aayush Soni Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Input: n = 2 Output: ["(())","()()"] Leetcode link: https://leetcode.com/problems/generate-parentheses/description/ """ def backtrack( partial: str, open_count: int, close_count: int, n: int, result: list[str] ) -> None: """ Generate valid combinations of balanced parentheses using recursion. :param partial: A string representing the current combination. :param open_count: An integer representing the count of open parentheses. :param close_count: An integer representing the count of close parentheses. :param n: An integer representing the total number of pairs. :param result: A list to store valid combinations. :return: None This function uses recursion to explore all possible combinations, ensuring that at each step, the parentheses remain balanced. Example: >>> result = [] >>> backtrack("", 0, 0, 2, result) >>> result ['(())', '()()'] """ if len(partial) == 2 * n: # When the combination is complete, add it to the result. result.append(partial) return if open_count < n: # If we can add an open parenthesis, do so, and recurse. backtrack(partial + "(", open_count + 1, close_count, n, result) if close_count < open_count: # If we can add a close parenthesis (it won't make the combination invalid), # do so, and recurse. backtrack(partial + ")", open_count, close_count + 1, n, result) def generate_parenthesis(n: int) -> list[str]: """ Generate valid combinations of balanced parentheses for a given n. :param n: An integer representing the number of pairs of parentheses. :return: A list of strings with valid combinations. This function uses a recursive approach to generate the combinations. Time Complexity: O(2^(2n)) - In the worst case, we have 2^(2n) combinations. Space Complexity: O(n) - where 'n' is the number of pairs. Example 1: >>> generate_parenthesis(3) ['((()))', '(()())', '(())()', '()(())', '()()()'] Example 2: >>> generate_parenthesis(1) ['()'] """ result: list[str] = [] backtrack("", 0, 0, n, result) return result if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/backtracking/sudoku.py
backtracking/sudoku.py
""" Given a partially filled 9x9 2D array, the objective is to fill a 9x9 square grid with digits numbered 1 to 9, so that every row, column, and and each of the nine 3x3 sub-grids contains all of the digits. This can be solved using Backtracking and is similar to n-queens. We check to see if a cell is safe or not and recursively call the function on the next column to see if it returns True. if yes, we have solved the puzzle. else, we backtrack and place another number in that cell and repeat this process. """ from __future__ import annotations Matrix = list[list[int]] # assigning initial values to the grid initial_grid: Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution no_solution: Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def is_safe(grid: Matrix, row: int, column: int, n: int) -> bool: """ This function checks the grid to see if each row, column, and the 3x3 subgrids contain the digit 'n'. It returns False if it is not 'safe' (a duplicate digit is found) else returns True if it is 'safe' """ for i in range(9): if n in {grid[row][i], grid[i][column]}: return False for i in range(3): for j in range(3): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def find_empty_location(grid: Matrix) -> tuple[int, int] | None: """ This function finds an empty location so that we can assign a number for that particular row and column. """ for i in range(9): for j in range(9): if grid[i][j] == 0: return i, j return None def sudoku(grid: Matrix) -> Matrix | None: """ Takes a partially filled-in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution (non-duplication across rows, columns, and boxes) >>> sudoku(initial_grid) # doctest: +NORMALIZE_WHITESPACE [[3, 1, 6, 5, 7, 8, 4, 9, 2], [5, 2, 9, 1, 3, 4, 7, 6, 8], [4, 8, 7, 6, 2, 9, 5, 3, 1], [2, 6, 3, 4, 1, 5, 9, 8, 7], [9, 7, 4, 8, 6, 3, 1, 2, 5], [8, 5, 1, 7, 9, 2, 6, 4, 3], [1, 3, 8, 9, 4, 7, 2, 5, 6], [6, 9, 2, 3, 5, 1, 8, 7, 4], [7, 4, 5, 2, 8, 6, 3, 1, 9]] >>> sudoku(no_solution) is None True """ if location := find_empty_location(grid): row, column = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1, 10): if is_safe(grid, row, column, digit): grid[row][column] = digit if sudoku(grid) is not None: return grid grid[row][column] = 0 return None def print_solution(grid: Matrix) -> None: """ A function to print the solution in the form of a 9x9 grid """ for row in grid: for cell in row: print(cell, end=" ") print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print("\nExample grid:\n" + "=" * 20) print_solution(example_grid) print("\nExample grid solution:") solution = sudoku(example_grid) if solution is not None: print_solution(solution) else: print("Cannot find a solution.")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/scripts/build_directory_md.py
scripts/build_directory_md.py
#!/usr/bin/env python3 import os from collections.abc import Iterator def good_file_paths(top_dir: str = ".") -> Iterator[str]: for dir_path, dir_names, filenames in os.walk(top_dir): dir_names[:] = [ d for d in dir_names if d != "scripts" and d[0] not in "._" and "venv" not in d ] for filename in filenames: if filename == "__init__.py": continue if os.path.splitext(filename)[1] in (".py", ".ipynb"): yield os.path.join(dir_path, filename).lstrip("./") def md_prefix(indent: int) -> str: """ Markdown prefix based on indent for bullet points >>> md_prefix(0) '\\n##' >>> md_prefix(1) ' *' >>> md_prefix(2) ' *' >>> md_prefix(3) ' *' """ return f"{indent * ' '}*" if indent else "\n##" def print_path(old_path: str, new_path: str) -> str: old_parts = old_path.split(os.sep) for i, new_part in enumerate(new_path.split(os.sep)): if (i + 1 > len(old_parts) or old_parts[i] != new_part) and new_part: print(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}") return new_path def print_directory_md(top_dir: str = ".") -> None: old_path = "" for filepath in sorted(good_file_paths(top_dir)): filepath, filename = os.path.split(filepath) if filepath != old_path: old_path = print_path(old_path, filepath) indent = (filepath.count(os.sep) + 1) if filepath else 0 url = f"{filepath}/{filename}".replace(" ", "%20") filename = os.path.splitext(filename.replace("_", " ").title())[0] print(f"{md_prefix(indent)} [{filename}]({url})") if __name__ == "__main__": print_directory_md(".")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/scripts/validate_filenames.py
scripts/validate_filenames.py
#!/usr/bin/env python3 import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore[no-redef] filepaths = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" if upper_files := [file for file in filepaths if file != file.lower()]: print(f"{len(upper_files)} files contain uppercase characters:") print("\n".join(upper_files) + "\n") if space_files := [file for file in filepaths if " " in file]: print(f"{len(space_files)} files contain space characters:") print("\n".join(space_files) + "\n") if hyphen_files := [ file for file in filepaths if "-" in file and "/site-packages/" not in file ]: print(f"{len(hyphen_files)} files contain hyphen characters:") print("\n".join(hyphen_files) + "\n") if nodir_files := [file for file in filepaths if os.sep not in file]: print(f"{len(nodir_files)} files are not in a directory:") print("\n".join(nodir_files) + "\n") if bad_files := len(upper_files + space_files + hyphen_files + nodir_files): import sys sys.exit(bad_files)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/scripts/validate_solutions.py
scripts/validate_solutions.py
#!/usr/bin/env python3 # /// script # requires-python = ">=3.13" # dependencies = [ # "httpx", # "pytest", # ] # /// import hashlib import importlib.util import json import os import pathlib from types import ModuleType import httpx import pytest PROJECT_EULER_DIR_PATH = pathlib.Path.cwd().joinpath("project_euler") PROJECT_EULER_ANSWERS_PATH = pathlib.Path.cwd().joinpath( "scripts", "project_euler_answers.json" ) with open(PROJECT_EULER_ANSWERS_PATH) as file_handle: PROBLEM_ANSWERS: dict[str, str] = json.load(file_handle) def convert_path_to_module(file_path: pathlib.Path) -> ModuleType: """Converts a file path to a Python module""" spec = importlib.util.spec_from_file_location(file_path.name, str(file_path)) module = importlib.util.module_from_spec(spec) # type: ignore[arg-type] spec.loader.exec_module(module) # type: ignore[union-attr] return module def all_solution_file_paths() -> list[pathlib.Path]: """Collects all the solution file path in the Project Euler directory""" solution_file_paths = [] for problem_dir_path in PROJECT_EULER_DIR_PATH.iterdir(): if problem_dir_path.is_file() or problem_dir_path.name.startswith("_"): continue for file_path in problem_dir_path.iterdir(): if file_path.suffix != ".py" or file_path.name.startswith(("_", "test")): continue solution_file_paths.append(file_path) return solution_file_paths def get_files_url() -> str: """Return the pull request number which triggered this action.""" with open(os.environ["GITHUB_EVENT_PATH"]) as file: event = json.load(file) return event["pull_request"]["url"] + "/files" def added_solution_file_path() -> list[pathlib.Path]: """Collects only the solution file path which got added in the current pull request. This will only be triggered if the script is ran from GitHub Actions. """ solution_file_paths = [] headers = { "Accept": "application/vnd.github.v3+json", "Authorization": "token " + os.environ["GITHUB_TOKEN"], } files = httpx.get(get_files_url(), headers=headers, timeout=10).json() for file in files: filepath = pathlib.Path.cwd().joinpath(file["filename"]) if ( filepath.suffix != ".py" or filepath.name.startswith(("_", "test")) or not filepath.name.startswith("sol") ): continue solution_file_paths.append(filepath) return solution_file_paths def collect_solution_file_paths() -> list[pathlib.Path]: # Return only if there are any, otherwise default to all solutions if ( os.environ.get("CI") and os.environ.get("GITHUB_EVENT_NAME") == "pull_request" and (filepaths := added_solution_file_path()) ): return filepaths return all_solution_file_paths() @pytest.mark.parametrize( "solution_path", collect_solution_file_paths(), ids=lambda path: f"{path.parent.name}/{path.name}", ) def test_project_euler(solution_path: pathlib.Path) -> None: """Testing for all Project Euler solutions""" # problem_[extract this part] and pad it with zeroes for width 3 problem_number: str = solution_path.parent.name[8:].zfill(3) expected: str = PROBLEM_ANSWERS[problem_number] solution_module = convert_path_to_module(solution_path) answer = str(solution_module.solution()) answer = hashlib.sha256(answer.encode()).hexdigest() assert answer == expected, ( f"Expected solution to {problem_number} to have hash {expected}, got {answer}" )
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/scripts/__init__.py
scripts/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/center_of_mass.py
physics/center_of_mass.py
""" Calculating the center of mass for a discrete system of particles, given their positions and masses. Description: In physics, the center of mass of a distribution of mass in space (sometimes referred to as the barycenter or balance point) is the unique point at any given time where the weighted relative position of the distributed mass sums to zero. This is the point to which a force may be applied to cause a linear acceleration without an angular acceleration. Calculations in mechanics are often simplified when formulated with respect to the center of mass. It is a hypothetical point where the entire mass of an object may be assumed to be concentrated to visualize its motion. In other words, the center of mass is the particle equivalent of a given object for the application of Newton's laws of motion. In the case of a system of particles P_i, i = 1, ..., n , each with mass m_i that are located in space with coordinates r_i, i = 1, ..., n , the coordinates R of the center of mass corresponds to: R = (Σ(mi * ri) / Σ(mi)) Reference: https://en.wikipedia.org/wiki/Center_of_mass """ from collections import namedtuple Particle = namedtuple("Particle", "x y z mass") # noqa: PYI024 Coord3D = namedtuple("Coord3D", "x y z") # noqa: PYI024 def center_of_mass(particles: list[Particle]) -> Coord3D: """ Input Parameters ---------------- particles: list(Particle): A list of particles where each particle is a tuple with it's (x, y, z) position and it's mass. Returns ------- Coord3D: A tuple with the coordinates of the center of mass (Xcm, Ycm, Zcm) rounded to two decimal places. Examples -------- >>> center_of_mass([ ... Particle(1.5, 4, 3.4, 4), ... Particle(5, 6.8, 7, 8.1), ... Particle(9.4, 10.1, 11.6, 12) ... ]) Coord3D(x=6.61, y=7.98, z=8.69) >>> center_of_mass([ ... Particle(1, 2, 3, 4), ... Particle(5, 6, 7, 8), ... Particle(9, 10, 11, 12) ... ]) Coord3D(x=6.33, y=7.33, z=8.33) >>> center_of_mass([ ... Particle(1, 2, 3, -4), ... Particle(5, 6, 7, 8), ... Particle(9, 10, 11, 12) ... ]) Traceback (most recent call last): ... ValueError: Mass of all particles must be greater than 0 >>> center_of_mass([ ... Particle(1, 2, 3, 0), ... Particle(5, 6, 7, 8), ... Particle(9, 10, 11, 12) ... ]) Traceback (most recent call last): ... ValueError: Mass of all particles must be greater than 0 >>> center_of_mass([]) Traceback (most recent call last): ... ValueError: No particles provided """ if not particles: raise ValueError("No particles provided") if any(particle.mass <= 0 for particle in particles): raise ValueError("Mass of all particles must be greater than 0") total_mass = sum(particle.mass for particle in particles) center_of_mass_x = round( sum(particle.x * particle.mass for particle in particles) / total_mass, 2 ) center_of_mass_y = round( sum(particle.y * particle.mass for particle in particles) / total_mass, 2 ) center_of_mass_z = round( sum(particle.z * particle.mass for particle in particles) / total_mass, 2 ) return Coord3D(center_of_mass_x, center_of_mass_y, center_of_mass_z) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/speed_of_sound.py
physics/speed_of_sound.py
""" Title : Calculating the speed of sound Description : The speed of sound (c) is the speed that a sound wave travels per unit time (m/s). During propagation, the sound wave propagates through an elastic medium. Sound propagates as longitudinal waves in liquids and gases and as transverse waves in solids. This file calculates the speed of sound in a fluid based on its bulk module and density. Equation for the speed of sound in a fluid: c_fluid = sqrt(K_s / p) c_fluid: speed of sound in fluid K_s: isentropic bulk modulus p: density of fluid Source : https://en.wikipedia.org/wiki/Speed_of_sound """ def speed_of_sound_in_a_fluid(density: float, bulk_modulus: float) -> float: """ Calculates the speed of sound in a fluid from its density and bulk modulus Examples: Example 1 --> Water 20°C: bulk_modulus= 2.15MPa, density=998kg/m³ Example 2 --> Mercury 20°C: bulk_modulus= 28.5MPa, density=13600kg/m³ >>> speed_of_sound_in_a_fluid(bulk_modulus=2.15e9, density=998) 1467.7563207952705 >>> speed_of_sound_in_a_fluid(bulk_modulus=28.5e9, density=13600) 1447.614670861731 """ if density <= 0: raise ValueError("Impossible fluid density") if bulk_modulus <= 0: raise ValueError("Impossible bulk modulus") return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/doppler_frequency.py
physics/doppler_frequency.py
""" Doppler's effect The Doppler effect (also Doppler shift) is the change in the frequency of a wave in relation to an observer who is moving relative to the source of the wave. The Doppler effect is named after the physicist Christian Doppler. A common example of Doppler shift is the change of pitch heard when a vehicle sounding a horn approaches and recedes from an observer. The reason for the Doppler effect is that when the source of the waves is moving towards the observer, each successive wave crest is emitted from a position closer to the observer than the crest of the previous wave. Therefore, each wave takes slightly less time to reach the observer than the previous wave. Hence, the time between the arrivals of successive wave crests at the observer is reduced, causing an increase in the frequency. Similarly, if the source of waves is moving away from the observer, each wave is emitted from a position farther from the observer than the previous wave, so the arrival time between successive waves is increased, reducing the frequency. If the source of waves is stationary but the observer is moving with respect to the source, the transmission velocity of the waves changes (ie the rate at which the observer receives waves) even if the wavelength and frequency emitted from the source remain constant. These results are all summarized by the Doppler formula: f = (f0 * (v + v0)) / (v - vs) where: f: frequency of the wave f0: frequency of the wave when the source is stationary v: velocity of the wave in the medium v0: velocity of the observer, positive if the observer is moving towards the source vs: velocity of the source, positive if the source is moving towards the observer Doppler's effect has many applications in physics and engineering, such as radar, astronomy, medical imaging, and seismology. References: https://en.wikipedia.org/wiki/Doppler_effect Now, we will implement a function that calculates the frequency of a wave as a function of the frequency of the wave when the source is stationary, the velocity of the wave in the medium, the velocity of the observer and the velocity of the source. """ def doppler_effect( org_freq: float, wave_vel: float, obs_vel: float, src_vel: float ) -> float: """ Input Parameters: ----------------- org_freq: frequency of the wave when the source is stationary wave_vel: velocity of the wave in the medium obs_vel: velocity of the observer, +ve if the observer is moving towards the source src_vel: velocity of the source, +ve if the source is moving towards the observer Returns: -------- f: frequency of the wave as perceived by the observer Docstring Tests: >>> doppler_effect(100, 330, 10, 0) # observer moving towards the source 103.03030303030303 >>> doppler_effect(100, 330, -10, 0) # observer moving away from the source 96.96969696969697 >>> doppler_effect(100, 330, 0, 10) # source moving towards the observer 103.125 >>> doppler_effect(100, 330, 0, -10) # source moving away from the observer 97.05882352941177 >>> doppler_effect(100, 330, 10, 10) # source & observer moving towards each other 106.25 >>> doppler_effect(100, 330, -10, -10) # source and observer moving away 94.11764705882354 >>> doppler_effect(100, 330, 10, 330) # source moving at same speed as the wave Traceback (most recent call last): ... ZeroDivisionError: Division by zero implies vs=v and observer in front of the source >>> doppler_effect(100, 330, 10, 340) # source moving faster than the wave Traceback (most recent call last): ... ValueError: Non-positive frequency implies vs>v or v0>v (in the opposite direction) >>> doppler_effect(100, 330, -340, 10) # observer moving faster than the wave Traceback (most recent call last): ... ValueError: Non-positive frequency implies vs>v or v0>v (in the opposite direction) """ if wave_vel == src_vel: raise ZeroDivisionError( "Division by zero implies vs=v and observer in front of the source" ) doppler_freq = (org_freq * (wave_vel + obs_vel)) / (wave_vel - src_vel) if doppler_freq <= 0: raise ValueError( "Non-positive frequency implies vs>v or v0>v (in the opposite direction)" ) return doppler_freq if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/orbital_transfer_work.py
physics/orbital_transfer_work.py
def orbital_transfer_work( mass_central: float, mass_object: float, r_initial: float, r_final: float ) -> str: """ Calculates the work required to move an object from one orbit to another in a gravitational field based on the change in total mechanical energy. The formula used is: W = (G * M * m / 2) * (1/r_initial - 1/r_final) where: W = work done (Joules) G = gravitational constant (6.67430 * 10^-11 m^3 kg^-1 s^-2) M = mass of the central body (kg) m = mass of the orbiting object (kg) r_initial = initial orbit radius (m) r_final = final orbit radius (m) Args: mass_central (float): Mass of the central body (kg) mass_object (float): Mass of the object being moved (kg) r_initial (float): Initial orbital radius (m) r_final (float): Final orbital radius (m) Returns: str: Work done in Joules as a string in scientific notation (3 decimals) Examples: >>> orbital_transfer_work(5.972e24, 1000, 6.371e6, 7e6) '2.811e+09' >>> orbital_transfer_work(5.972e24, 500, 7e6, 6.371e6) '-1.405e+09' >>> orbital_transfer_work(1.989e30, 1000, 1.5e11, 2.28e11) '1.514e+11' """ gravitational_constant = 6.67430e-11 if r_initial <= 0 or r_final <= 0: raise ValueError("Orbital radii must be greater than zero.") work = (gravitational_constant * mass_central * mass_object / 2) * ( 1 / r_initial - 1 / r_final ) return f"{work:.3e}" if __name__ == "__main__": import doctest doctest.testmod() print("Orbital transfer work calculator\n") try: M = float(input("Enter mass of central body (kg): ").strip()) if M <= 0: r1 = float(input("Enter initial orbit radius (m): ").strip()) if r1 <= 0: raise ValueError("Initial orbit radius must be greater than zero.") r2 = float(input("Enter final orbit radius (m): ").strip()) if r2 <= 0: raise ValueError("Final orbit radius must be greater than zero.") m = float(input("Enter mass of orbiting object (kg): ").strip()) if m <= 0: raise ValueError("Mass of the orbiting object must be greater than zero.") r1 = float(input("Enter initial orbit radius (m): ").strip()) r2 = float(input("Enter final orbit radius (m): ").strip()) result = orbital_transfer_work(M, m, r1, r2) print(f"Work done in orbital transfer: {result} Joules") except ValueError as e: print(f"Input error: {e}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/rms_speed_of_molecule.py
physics/rms_speed_of_molecule.py
""" The root-mean-square speed is essential in measuring the average speed of particles contained in a gas, defined as, ----------------- | Vrms = √3RT/M | ----------------- In Kinetic Molecular Theory, gasified particles are in a condition of constant random motion; each particle moves at a completely different pace, perpetually clashing and changing directions consistently velocity is used to describe the movement of gas particles, thereby taking into account both speed and direction. Although the velocity of gaseous particles is constantly changing, the distribution of velocities does not change. We cannot gauge the velocity of every individual particle, thus we frequently reason in terms of the particles average behavior. Particles moving in opposite directions have velocities of opposite signs. Since gas particles are in random motion, it's plausible that there'll be about as several moving in one direction as within the other way, which means that the average velocity for a collection of gas particles equals zero; as this value is unhelpful, the average of velocities can be determined using an alternative method. """ UNIVERSAL_GAS_CONSTANT = 8.3144598 def rms_speed_of_molecule(temperature: float, molar_mass: float) -> float: """ >>> rms_speed_of_molecule(100, 2) 35.315279554323226 >>> rms_speed_of_molecule(273, 12) 23.821458421977443 """ 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 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # example temperature = 300 molar_mass = 28 vrms = rms_speed_of_molecule(temperature, molar_mass) print(f"Vrms of Nitrogen gas at 300 K is {vrms} m/s")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/period_of_pendulum.py
physics/period_of_pendulum.py
""" Title : Computing the time period of a simple pendulum The simple pendulum is a mechanical system that sways or moves in an oscillatory motion. The simple pendulum comprises of a small bob of mass m suspended by a thin string of length L and secured to a platform at its upper end. Its motion occurs in a vertical plane and is mainly driven by gravitational force. The period of the pendulum depends on the length of the string and the amplitude (the maximum angle) of oscillation. However, the effect of the amplitude can be ignored if the amplitude is small. It should be noted that the period does not depend on the mass of the bob. For small amplitudes, the period of a simple pendulum is given by the following approximation: T ≈ 2π * √(L / g) where: L = length of string from which the bob is hanging (in m) g = acceleration due to gravity (approx 9.8 m/s²) Reference : https://byjus.com/jee/simple-pendulum/ """ from math import pi from scipy.constants import g def period_of_pendulum(length: float) -> float: """ >>> period_of_pendulum(1.23) 2.2252155506257845 >>> period_of_pendulum(2.37) 3.0888278441908574 >>> period_of_pendulum(5.63) 4.76073193364765 >>> period_of_pendulum(-12) Traceback (most recent call last): ... ValueError: The length should be non-negative >>> period_of_pendulum(0) 0.0 """ if length < 0: raise ValueError("The length should be non-negative") return 2 * pi * (length / g) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/rainfall_intensity.py
physics/rainfall_intensity.py
""" Rainfall Intensity ================== This module contains functions to calculate the intensity of a rainfall event for a given duration and return period. This function uses the Sherman intensity-duration-frequency curve. References ---------- - Aparicio, F. (1997): Fundamentos de Hidrología de Superficie. Balderas, México, Limusa. 303 p. - https://en.wikipedia.org/wiki/Intensity-duration-frequency_curve """ def rainfall_intensity( coefficient_k: float, coefficient_a: float, coefficient_b: float, coefficient_c: float, return_period: float, duration: float, ) -> float: """ Calculate the intensity of a rainfall event for a given duration and return period. It's based on the Sherman intensity-duration-frequency curve: I = k * T^a / (D + b)^c where: I = Intensity of the rainfall event [mm/h] k, a, b, c = Coefficients obtained through statistical distribution adjust T = Return period in years D = Rainfall event duration in minutes Parameters ---------- coefficient_k : float Coefficient obtained through statistical distribution adjust. coefficient_a : float Coefficient obtained through statistical distribution adjust. coefficient_b : float Coefficient obtained through statistical distribution adjust. coefficient_c : float Coefficient obtained through statistical distribution adjust. return_period : float Return period in years. duration : float Rainfall event duration in minutes. Returns ------- intensity : float Intensity of the rainfall event in mm/h. Raises ------ ValueError If any of the parameters are not positive. Examples -------- >>> rainfall_intensity(1000, 0.2, 11.6, 0.81, 10, 60) 49.83339231138578 >>> rainfall_intensity(1000, 0.2, 11.6, 0.81, 10, 30) 77.36319588106228 >>> rainfall_intensity(1000, 0.2, 11.6, 0.81, 5, 60) 43.382487747633625 >>> rainfall_intensity(0, 0.2, 11.6, 0.81, 10, 60) Traceback (most recent call last): ... ValueError: All parameters must be positive. >>> rainfall_intensity(1000, -0.2, 11.6, 0.81, 10, 60) Traceback (most recent call last): ... ValueError: All parameters must be positive. >>> rainfall_intensity(1000, 0.2, -11.6, 0.81, 10, 60) Traceback (most recent call last): ... ValueError: All parameters must be positive. >>> rainfall_intensity(1000, 0.2, 11.6, -0.81, 10, 60) Traceback (most recent call last): ... ValueError: All parameters must be positive. >>> rainfall_intensity(1000, 0, 11.6, 0.81, 10, 60) Traceback (most recent call last): ... ValueError: All parameters must be positive. >>> rainfall_intensity(1000, 0.2, 0, 0.81, 10, 60) Traceback (most recent call last): ... ValueError: All parameters must be positive. >>> rainfall_intensity(1000, 0.2, 11.6, 0, 10, 60) Traceback (most recent call last): ... ValueError: All parameters must be positive. >>> rainfall_intensity(0, 0.2, 11.6, 0.81, 10, 60) Traceback (most recent call last): ... ValueError: All parameters must be positive. >>> rainfall_intensity(1000, 0.2, 11.6, 0.81, 0, 60) Traceback (most recent call last): ... ValueError: All parameters must be positive. >>> rainfall_intensity(1000, 0.2, 11.6, 0.81, 10, 0) Traceback (most recent call last): ... ValueError: All parameters must be positive. """ if ( coefficient_k <= 0 or coefficient_a <= 0 or coefficient_b <= 0 or coefficient_c <= 0 or return_period <= 0 or duration <= 0 ): raise ValueError("All parameters must be positive.") intensity = (coefficient_k * (return_period**coefficient_a)) / ( (duration + coefficient_b) ** coefficient_c ) return intensity if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/ideal_gas_law.py
physics/ideal_gas_law.py
""" The ideal gas law, also called the general gas equation, is the equation of state of a hypothetical ideal gas. It is a good approximation of the behavior of many gases under many conditions, although it has several limitations. It was first stated by Benoît Paul Émile Clapeyron in 1834 as a combination of the empirical Boyle's law, Charles's law, Avogadro's law, and Gay-Lussac's law.[1] The ideal gas law is often written in an empirical form: ------------ | PV = nRT | ------------ P = Pressure (Pa) V = Volume (m^3) n = Amount of substance (mol) R = Universal gas constant T = Absolute temperature (Kelvin) (Description adapted from https://en.wikipedia.org/wiki/Ideal_gas_law ) """ UNIVERSAL_GAS_CONSTANT = 8.314462 # Unit - J mol-1 K-1 def pressure_of_gas_system(moles: float, kelvin: float, volume: float) -> float: """ >>> pressure_of_gas_system(2, 100, 5) 332.57848 >>> pressure_of_gas_system(0.5, 273, 0.004) 283731.01575 >>> pressure_of_gas_system(3, -0.46, 23.5) Traceback (most recent call last): ... ValueError: Invalid inputs. Enter positive value. """ if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("Invalid inputs. Enter positive value.") return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def volume_of_gas_system(moles: float, kelvin: float, pressure: float) -> float: """ >>> volume_of_gas_system(2, 100, 5) 332.57848 >>> volume_of_gas_system(0.5, 273, 0.004) 283731.01575 >>> volume_of_gas_system(3, -0.46, 23.5) Traceback (most recent call last): ... ValueError: Invalid inputs. Enter positive value. """ if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value.") return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure def temperature_of_gas_system(moles: float, volume: float, pressure: float) -> float: """ >>> temperature_of_gas_system(2, 100, 5) 30.068090996146232 >>> temperature_of_gas_system(11, 5009, 1000) 54767.66101807144 >>> temperature_of_gas_system(3, -0.46, 23.5) Traceback (most recent call last): ... ValueError: Invalid inputs. Enter positive value. """ if moles < 0 or volume < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value.") return pressure * volume / (moles * UNIVERSAL_GAS_CONSTANT) def moles_of_gas_system(kelvin: float, volume: float, pressure: float) -> float: """ >>> moles_of_gas_system(100, 5, 10) 0.06013618199229246 >>> moles_of_gas_system(110, 5009, 1000) 5476.766101807144 >>> moles_of_gas_system(3, -0.46, 23.5) Traceback (most recent call last): ... ValueError: Invalid inputs. Enter positive value. """ if kelvin < 0 or volume < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value.") return pressure * volume / (kelvin * UNIVERSAL_GAS_CONSTANT) if __name__ == "__main__": from doctest import testmod testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/shear_stress.py
physics/shear_stress.py
from __future__ import annotations """ Shear stress is a component of stress that is coplanar to the material cross-section. It arises due to a shear force, the component of the force vector parallel to the material cross-section. https://en.wikipedia.org/wiki/Shear_stress """ def shear_stress( stress: float, tangential_force: float, area: float, ) -> tuple[str, float]: """ This function can calculate any one of the three - 1. Shear Stress 2. Tangential Force 3. Cross-sectional Area This is calculated from the other two provided values Examples - >>> shear_stress(stress=25, tangential_force=100, area=0) ('area', 4.0) >>> shear_stress(stress=0, tangential_force=1600, area=200) ('stress', 8.0) >>> shear_stress(stress=1000, tangential_force=0, area=1200) ('tangential_force', 1200000) """ 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, ) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/archimedes_principle_of_buoyant_force.py
physics/archimedes_principle_of_buoyant_force.py
""" Calculate the buoyant force of any body completely or partially submerged in a static fluid. This principle was discovered by the Greek mathematician Archimedes. Equation for calculating buoyant force: Fb = p * V * g https://en.wikipedia.org/wiki/Archimedes%27_principle """ # Acceleration Constant on Earth (unit m/s^2) g = 9.80665 # Also available in scipy.constants.g def archimedes_principle( fluid_density: float, volume: float, gravity: float = g ) -> float: """ Args: fluid_density: density of fluid (kg/m^3) volume: volume of object/liquid being displaced by the object (m^3) gravity: Acceleration from gravity. Gravitational force on the system, The default is Earth Gravity returns: the buoyant force on an object in Newtons >>> archimedes_principle(fluid_density=500, volume=4, gravity=9.8) 19600.0 >>> archimedes_principle(fluid_density=997, volume=0.5, gravity=9.8) 4885.3 >>> archimedes_principle(fluid_density=997, volume=0.7) 6844.061035 >>> archimedes_principle(fluid_density=997, volume=-0.7) Traceback (most recent call last): ... ValueError: Impossible object volume >>> archimedes_principle(fluid_density=0, volume=0.7) Traceback (most recent call last): ... ValueError: Impossible fluid density >>> archimedes_principle(fluid_density=997, volume=0.7, gravity=0) 0.0 >>> archimedes_principle(fluid_density=997, volume=0.7, gravity=-9.8) Traceback (most recent call last): ... ValueError: Impossible gravity """ 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 if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/grahams_law.py
physics/grahams_law.py
""" Title: Graham's Law of Effusion Description: Graham's law of effusion states that the rate of effusion of a gas is inversely proportional to the square root of the molar mass of its particles: r1/r2 = sqrt(m2/m1) r1 = Rate of effusion for the first gas. r2 = Rate of effusion for the second gas. m1 = Molar mass of the first gas. m2 = Molar mass of the second gas. (Description adapted from https://en.wikipedia.org/wiki/Graham%27s_law) """ from math import pow, sqrt # noqa: A004 def validate(*values: float) -> bool: """ Input Parameters: ----------------- effusion_rate_1: Effustion rate of first gas (m^2/s, mm^2/s, etc.) effusion_rate_2: Effustion rate of second gas (m^2/s, mm^2/s, etc.) molar_mass_1: Molar mass of the first gas (g/mol, kg/kmol, etc.) molar_mass_2: Molar mass of the second gas (g/mol, kg/kmol, etc.) Returns: -------- >>> validate(2.016, 4.002) True >>> validate(-2.016, 4.002) False >>> validate() False """ result = len(values) > 0 and all(value > 0.0 for value in values) return result def effusion_ratio(molar_mass_1: float, molar_mass_2: float) -> float | ValueError: """ Input Parameters: ----------------- molar_mass_1: Molar mass of the first gas (g/mol, kg/kmol, etc.) molar_mass_2: Molar mass of the second gas (g/mol, kg/kmol, etc.) Returns: -------- >>> effusion_ratio(2.016, 4.002) 1.408943 >>> effusion_ratio(-2.016, 4.002) ValueError('Input Error: Molar mass values must greater than 0.') >>> effusion_ratio(2.016) Traceback (most recent call last): ... TypeError: effusion_ratio() missing 1 required positional argument: 'molar_mass_2' """ return ( round(sqrt(molar_mass_2 / molar_mass_1), 6) if validate(molar_mass_1, molar_mass_2) else ValueError("Input Error: Molar mass values must greater than 0.") ) def first_effusion_rate( effusion_rate: float, molar_mass_1: float, molar_mass_2: float ) -> float | ValueError: """ Input Parameters: ----------------- effusion_rate: Effustion rate of second gas (m^2/s, mm^2/s, etc.) molar_mass_1: Molar mass of the first gas (g/mol, kg/kmol, etc.) molar_mass_2: Molar mass of the second gas (g/mol, kg/kmol, etc.) Returns: -------- >>> first_effusion_rate(1, 2.016, 4.002) 1.408943 >>> first_effusion_rate(-1, 2.016, 4.002) ValueError('Input Error: Molar mass and effusion rate values must greater than 0.') >>> first_effusion_rate(1) Traceback (most recent call last): ... TypeError: first_effusion_rate() missing 2 required positional arguments: \ 'molar_mass_1' and 'molar_mass_2' >>> first_effusion_rate(1, 2.016) Traceback (most recent call last): ... TypeError: first_effusion_rate() missing 1 required positional argument: \ 'molar_mass_2' """ return ( round(effusion_rate * sqrt(molar_mass_2 / molar_mass_1), 6) if validate(effusion_rate, molar_mass_1, molar_mass_2) else ValueError( "Input Error: Molar mass and effusion rate values must greater than 0." ) ) def second_effusion_rate( effusion_rate: float, molar_mass_1: float, molar_mass_2: float ) -> float | ValueError: """ Input Parameters: ----------------- effusion_rate: Effustion rate of second gas (m^2/s, mm^2/s, etc.) molar_mass_1: Molar mass of the first gas (g/mol, kg/kmol, etc.) molar_mass_2: Molar mass of the second gas (g/mol, kg/kmol, etc.) Returns: -------- >>> second_effusion_rate(1, 2.016, 4.002) 0.709752 >>> second_effusion_rate(-1, 2.016, 4.002) ValueError('Input Error: Molar mass and effusion rate values must greater than 0.') >>> second_effusion_rate(1) Traceback (most recent call last): ... TypeError: second_effusion_rate() missing 2 required positional arguments: \ 'molar_mass_1' and 'molar_mass_2' >>> second_effusion_rate(1, 2.016) Traceback (most recent call last): ... TypeError: second_effusion_rate() missing 1 required positional argument: \ 'molar_mass_2' """ return ( round(effusion_rate / sqrt(molar_mass_2 / molar_mass_1), 6) if validate(effusion_rate, molar_mass_1, molar_mass_2) else ValueError( "Input Error: Molar mass and effusion rate values must greater than 0." ) ) def first_molar_mass( molar_mass: float, effusion_rate_1: float, effusion_rate_2: float ) -> float | ValueError: """ Input Parameters: ----------------- molar_mass: Molar mass of the first gas (g/mol, kg/kmol, etc.) effusion_rate_1: Effustion rate of first gas (m^2/s, mm^2/s, etc.) effusion_rate_2: Effustion rate of second gas (m^2/s, mm^2/s, etc.) Returns: -------- >>> first_molar_mass(2, 1.408943, 0.709752) 0.507524 >>> first_molar_mass(-1, 2.016, 4.002) ValueError('Input Error: Molar mass and effusion rate values must greater than 0.') >>> first_molar_mass(1) Traceback (most recent call last): ... TypeError: first_molar_mass() missing 2 required positional arguments: \ 'effusion_rate_1' and 'effusion_rate_2' >>> first_molar_mass(1, 2.016) Traceback (most recent call last): ... TypeError: first_molar_mass() missing 1 required positional argument: \ 'effusion_rate_2' """ return ( round(molar_mass / pow(effusion_rate_1 / effusion_rate_2, 2), 6) if validate(molar_mass, effusion_rate_1, effusion_rate_2) else ValueError( "Input Error: Molar mass and effusion rate values must greater than 0." ) ) def second_molar_mass( molar_mass: float, effusion_rate_1: float, effusion_rate_2: float ) -> float | ValueError: """ Input Parameters: ----------------- molar_mass: Molar mass of the first gas (g/mol, kg/kmol, etc.) effusion_rate_1: Effustion rate of first gas (m^2/s, mm^2/s, etc.) effusion_rate_2: Effustion rate of second gas (m^2/s, mm^2/s, etc.) Returns: -------- >>> second_molar_mass(2, 1.408943, 0.709752) 1.970351 >>> second_molar_mass(-2, 1.408943, 0.709752) ValueError('Input Error: Molar mass and effusion rate values must greater than 0.') >>> second_molar_mass(1) Traceback (most recent call last): ... TypeError: second_molar_mass() missing 2 required positional arguments: \ 'effusion_rate_1' and 'effusion_rate_2' >>> second_molar_mass(1, 2.016) Traceback (most recent call last): ... TypeError: second_molar_mass() missing 1 required positional argument: \ 'effusion_rate_2' """ return ( round(pow(effusion_rate_1 / effusion_rate_2, 2) / molar_mass, 6) if validate(molar_mass, effusion_rate_1, effusion_rate_2) else ValueError( "Input Error: Molar mass and effusion rate values must greater than 0." ) )
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/newtons_law_of_gravitation.py
physics/newtons_law_of_gravitation.py
""" Title : Finding the value of either Gravitational Force, one of the masses or distance provided that the other three parameters are given. Description : Newton's Law of Universal Gravitation explains the presence of force of attraction between bodies having a definite mass situated at a distance. It is usually stated as that, every particle attracts every other particle in the universe with a force that is directly proportional to the product of their masses and inversely proportional to the square of the distance between their centers. The publication of the theory has become known as the "first great unification", as it marked the unification of the previously described phenomena of gravity on Earth with known astronomical behaviors. The equation for the universal gravitation is as follows: F = (G * mass_1 * mass_2) / (distance)^2 Source : - https://en.wikipedia.org/wiki/Newton%27s_law_of_universal_gravitation - Newton (1687) "Philosophiæ Naturalis Principia Mathematica" """ from __future__ import annotations # Define the Gravitational Constant G and the function GRAVITATIONAL_CONSTANT = 6.6743e-11 # unit of G : m^3 * kg^-1 * s^-2 def gravitational_law( force: float, mass_1: float, mass_2: float, distance: float ) -> dict[str, float]: """ Input Parameters ---------------- force : magnitude in Newtons mass_1 : mass in Kilograms mass_2 : mass in Kilograms distance : distance in Meters Returns ------- result : dict name, value pair of the parameter having Zero as it's value Returns the value of one of the parameters specified as 0, provided the values of other parameters are given. >>> gravitational_law(force=0, mass_1=5, mass_2=10, distance=20) {'force': 8.342875e-12} >>> gravitational_law(force=7367.382, mass_1=0, mass_2=74, distance=3048) {'mass_1': 1.385816317292268e+19} >>> gravitational_law(force=36337.283, mass_1=0, mass_2=0, distance=35584) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 >>> gravitational_law(force=36337.283, mass_1=-674, mass_2=0, distance=35584) Traceback (most recent call last): ... ValueError: Mass can not be negative >>> gravitational_law(force=-847938e12, mass_1=674, mass_2=0, distance=9374) Traceback (most recent call last): ... ValueError: Gravitational force can not be negative """ 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") # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/lorentz_transformation_four_vector.py
physics/lorentz_transformation_four_vector.py
""" Lorentz transformations describe the transition between two inertial reference frames F and F', each of which is moving in some direction with respect to the other. This code only calculates Lorentz transformations for movement in the x direction with no spatial rotation (i.e., a Lorentz boost in the x direction). The Lorentz transformations are calculated here as linear transformations of four-vectors [ct, x, y, z] described by Minkowski space. Note that t (time) is multiplied by c (the speed of light) in the first entry of each four-vector. Thus, if X = [ct; x; y; z] and X' = [ct'; x'; y'; z'] are the four-vectors for two inertial reference frames and X' moves in the x direction with velocity v with respect to X, then the Lorentz transformation from X to X' is X' = BX, where | y -γβ 0 0| B = |-γβ y 0 0| | 0 0 1 0| | 0 0 0 1| is the matrix describing the Lorentz boost between X and X', y = 1 / √(1 - v²/c²) is the Lorentz factor, and β = v/c is the velocity as a fraction of c. Reference: https://en.wikipedia.org/wiki/Lorentz_transformation """ from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) c = 299792458 # Symbols ct, x, y, z = symbols("ct x y z") # Vehicle's speed divided by speed of light (no units) def beta(velocity: float) -> float: """ Calculates β = v/c, the given velocity as a fraction of c >>> beta(c) 1.0 >>> beta(199792458) 0.666435904801848 >>> beta(1e5) 0.00033356409519815205 >>> beta(0.2) Traceback (most recent call last): ... ValueError: Speed must be greater than or equal to 1! """ 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 def gamma(velocity: float) -> float: """ Calculate the Lorentz factor y = 1 / √(1 - v²/c²) for a given velocity >>> gamma(4) 1.0000000000000002 >>> gamma(1e5) 1.0000000556325075 >>> gamma(3e7) 1.005044845777813 >>> gamma(2.8e8) 2.7985595722318277 >>> gamma(299792451) 4627.49902669495 >>> gamma(0.3) Traceback (most recent call last): ... ValueError: Speed must be greater than or equal to 1! >>> gamma(2 * c) Traceback (most recent call last): ... ValueError: Speed must not exceed light speed 299,792,458 [m/s]! """ return 1 / sqrt(1 - beta(velocity) ** 2) def transformation_matrix(velocity: float) -> np.ndarray: """ Calculate the Lorentz transformation matrix for movement in the x direction: | y -γβ 0 0| |-γβ y 0 0| | 0 0 1 0| | 0 0 0 1| where y is the Lorentz factor and β is the velocity as a fraction of c >>> transformation_matrix(29979245) array([[ 1.00503781, -0.10050378, 0. , 0. ], [-0.10050378, 1.00503781, 0. , 0. ], [ 0. , 0. , 1. , 0. ], [ 0. , 0. , 0. , 1. ]]) >>> transformation_matrix(19979245.2) array([[ 1.00222811, -0.06679208, 0. , 0. ], [-0.06679208, 1.00222811, 0. , 0. ], [ 0. , 0. , 1. , 0. ], [ 0. , 0. , 0. , 1. ]]) >>> transformation_matrix(1) array([[ 1.00000000e+00, -3.33564095e-09, 0.00000000e+00, 0.00000000e+00], [-3.33564095e-09, 1.00000000e+00, 0.00000000e+00, 0.00000000e+00], [ 0.00000000e+00, 0.00000000e+00, 1.00000000e+00, 0.00000000e+00], [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00]]) >>> transformation_matrix(0) Traceback (most recent call last): ... ValueError: Speed must be greater than or equal to 1! >>> transformation_matrix(c * 1.5) Traceback (most recent call last): ... ValueError: Speed must not exceed light speed 299,792,458 [m/s]! """ 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], ] ) def transform(velocity: float, event: np.ndarray | None = None) -> np.ndarray: """ Calculate a Lorentz transformation for movement in the x direction given a velocity and a four-vector for an inertial reference frame If no four-vector is given, then calculate the transformation symbolically with variables >>> transform(29979245, np.array([1, 2, 3, 4])) array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00]) >>> transform(29979245) array([1.00503781498831*ct - 0.100503778816875*x, -0.100503778816875*ct + 1.00503781498831*x, 1.0*y, 1.0*z], dtype=object) >>> transform(19879210.2) array([1.0022057787097*ct - 0.066456172618675*x, -0.066456172618675*ct + 1.0022057787097*x, 1.0*y, 1.0*z], dtype=object) >>> transform(299792459, np.array([1, 1, 1, 1])) Traceback (most recent call last): ... ValueError: Speed must not exceed light speed 299,792,458 [m/s]! >>> transform(-1, np.array([1, 1, 1, 1])) Traceback (most recent call last): ... ValueError: Speed must be greater than or equal to 1! """ # 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 if __name__ == "__main__": import doctest doctest.testmod() # Example of symbolic vector: four_vector = transform(29979245) print("Example of four vector: ") print(f"ct' = {four_vector[0]}") print(f"x' = {four_vector[1]}") print(f"y' = {four_vector[2]}") print(f"z' = {four_vector[3]}") # Substitute symbols with numerical values sub_dict = {ct: c, x: 1, y: 1, z: 1} numerical_vector = [four_vector[i].subs(sub_dict) for i in range(4)] print(f"\n{numerical_vector}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/terminal_velocity.py
physics/terminal_velocity.py
""" Title : Computing the terminal velocity of an object falling through a fluid. Terminal velocity is defined as the highest velocity attained by an object falling through a fluid. It is observed when the sum of drag force and buoyancy is equal to the downward gravity force acting on the object. The acceleration of the object is zero as the net force acting on the object is zero. Vt = ((2 * m * g)/(p * A * Cd))^0.5 where : Vt = Terminal velocity (in m/s) m = Mass of the falling object (in Kg) g = Acceleration due to gravity (value taken : imported from scipy) p = Density of the fluid through which the object is falling (in Kg/m^3) A = Projected area of the object (in m^2) Cd = Drag coefficient (dimensionless) Reference : https://byjus.com/physics/derivation-of-terminal-velocity/ """ from scipy.constants import g def terminal_velocity( mass: float, density: float, area: float, drag_coefficient: float ) -> float: """ >>> terminal_velocity(1, 25, 0.6, 0.77) 1.3031197996044768 >>> terminal_velocity(2, 100, 0.45, 0.23) 1.9467947148674276 >>> terminal_velocity(5, 50, 0.2, 0.5) 4.428690551393267 >>> terminal_velocity(-5, 50, -0.2, -2) Traceback (most recent call last): ... ValueError: mass, density, area and the drag coefficient all need to be positive >>> terminal_velocity(3, -20, -1, 2) Traceback (most recent call last): ... ValueError: mass, density, area and the drag coefficient all need to be positive >>> terminal_velocity(-2, -1, -0.44, -1) Traceback (most recent call last): ... ValueError: mass, density, area and the drag coefficient all need to be positive """ if mass <= 0 or density <= 0 or area <= 0 or drag_coefficient <= 0: raise ValueError( "mass, density, area and the drag coefficient all need to be positive" ) return ((2 * mass * g) / (density * area * drag_coefficient)) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/newtons_second_law_of_motion.py
physics/newtons_second_law_of_motion.py
r""" Description: Newton's second law of motion pertains to the behavior of objects for which all existing forces are not balanced. The second law states that the acceleration of an object is dependent upon two variables - the net force acting upon the object and the mass of the object. The acceleration of an object depends directly upon the net force acting upon the object, and inversely upon the mass of the object. As the force acting upon an object is increased, the acceleration of the object is increased. As the mass of an object is increased, the acceleration of the object is decreased. Source: https://www.physicsclassroom.com/class/newtlaws/Lesson-3/Newton-s-Second-Law Formulation: F_net = m • a Diagrammatic Explanation:: Forces are unbalanced | | | V There is acceleration /\ / \ / \ / \ / \ / \ / \ __________________ ____________________ | The acceleration | | The acceleration | | depends directly | | depends inversely | | on the net force | | upon the object's | | | | mass | |__________________| |____________________| Units: 1 Newton = 1 kg • meters/seconds^2 How to use? Inputs:: ______________ _____________________ ___________ | Name | Units | Type | |--------------|---------------------|-----------| | mass | in kgs | float | |--------------|---------------------|-----------| | acceleration | in meters/seconds^2 | float | |______________|_____________________|___________| Output:: ______________ _______________________ ___________ | Name | Units | Type | |--------------|-----------------------|-----------| | force | in Newtons | float | |______________|_______________________|___________| """ def newtons_second_law_of_motion(mass: float, acceleration: float) -> float: """ Calculates force from `mass` and `acceleration` >>> newtons_second_law_of_motion(10, 10) 100 >>> newtons_second_law_of_motion(2.0, 1) 2.0 """ force = 0.0 try: force = mass * acceleration except Exception: return -0.0 return force if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo mass = 12.5 acceleration = 10 force = newtons_second_law_of_motion(mass, acceleration) print("The force is ", force, "N")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/n_body_simulation.py
physics/n_body_simulation.py
""" In physics and astronomy, a gravitational N-body simulation is a simulation of a dynamical system of particles under the influence of gravity. The system consists of a number of bodies, each of which exerts a gravitational force on all other bodies. These forces are calculated using Newton's law of universal gravitation. The Euler method is used at each time-step to calculate the change in velocity and position brought about by these forces. Softening is used to prevent numerical divergences when a particle comes too close to another (and the force goes to infinity). (Description adapted from https://en.wikipedia.org/wiki/N-body_simulation ) (See also http://www.shodor.org/refdesk/Resources/Algorithms/EulersMethod/ ) """ from __future__ import annotations import random from matplotlib import animation from matplotlib import pyplot as plt # Frame rate of the animation INTERVAL = 20 # Time between time steps in seconds DELTA_TIME = INTERVAL / 1000 class Body: 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: """ The parameters "size" & "color" are not relevant for the simulation itself, they are only used for plotting. """ 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 @property def position(self) -> tuple[float, float]: return self.position_x, self.position_y @property def velocity(self) -> tuple[float, float]: return self.velocity_x, self.velocity_y def update_velocity( self, force_x: float, force_y: float, delta_time: float ) -> None: """ Euler algorithm for velocity >>> body_1 = Body(0.,0.,0.,0.) >>> body_1.update_velocity(1.,0.,1.) >>> body_1.velocity (1.0, 0.0) >>> body_1.update_velocity(1.,0.,1.) >>> body_1.velocity (2.0, 0.0) >>> body_2 = Body(0.,0.,5.,0.) >>> body_2.update_velocity(0.,-10.,10.) >>> body_2.velocity (5.0, -100.0) >>> body_2.update_velocity(0.,-10.,10.) >>> body_2.velocity (5.0, -200.0) """ self.velocity_x += force_x * delta_time self.velocity_y += force_y * delta_time def update_position(self, delta_time: float) -> None: """ Euler algorithm for position >>> body_1 = Body(0.,0.,1.,0.) >>> body_1.update_position(1.) >>> body_1.position (1.0, 0.0) >>> body_1.update_position(1.) >>> body_1.position (2.0, 0.0) >>> body_2 = Body(10.,10.,0.,-2.) >>> body_2.update_position(1.) >>> body_2.position (10.0, 8.0) >>> body_2.update_position(1.) >>> body_2.position (10.0, 6.0) """ self.position_x += self.velocity_x * delta_time self.position_y += self.velocity_y * delta_time class BodySystem: """ This class is used to hold the bodies, the gravitation constant, the time factor and the softening factor. The time factor is used to control the speed of the simulation. The softening factor is used for softening, a numerical trick for N-body simulations to prevent numerical divergences when two bodies get too close to each other. """ 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 def __len__(self) -> int: return len(self.bodies) def update_system(self, delta_time: float) -> None: """ For each body, loop through all other bodies to calculate the total force they exert on it. Use that force to update the body's velocity. >>> body_system_1 = BodySystem([Body(0,0,0,0), Body(10,0,0,0)]) >>> len(body_system_1) 2 >>> body_system_1.update_system(1) >>> body_system_1.bodies[0].position (0.01, 0.0) >>> body_system_1.bodies[0].velocity (0.01, 0.0) >>> body_system_2 = BodySystem([Body(-10,0,0,0), Body(10,0,0,0, mass=4)], 1, 10) >>> body_system_2.update_system(1) >>> body_system_2.bodies[0].position (-9.0, 0.0) >>> body_system_2.bodies[0].velocity (0.1, 0.0) """ 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) def update_step( body_system: BodySystem, delta_time: float, patches: list[plt.Circle] ) -> None: """ Updates the body-system and applies the change to the patch-list used for plotting >>> body_system_1 = BodySystem([Body(0,0,0,0), Body(10,0,0,0)]) >>> patches_1 = [plt.Circle((body.position_x, body.position_y), body.size, ... fc=body.color)for body in body_system_1.bodies] #doctest: +ELLIPSIS >>> update_step(body_system_1, 1, patches_1) >>> patches_1[0].center (0.01, 0.0) >>> body_system_2 = BodySystem([Body(-10,0,0,0), Body(10,0,0,0, mass=4)], 1, 10) >>> patches_2 = [plt.Circle((body.position_x, body.position_y), body.size, ... fc=body.color)for body in body_system_2.bodies] #doctest: +ELLIPSIS >>> update_step(body_system_2, 1, patches_2) >>> patches_2[0].center (-9.0, 0.0) """ # 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) def plot( title: str, body_system: BodySystem, x_start: float = -1, x_end: float = 1, y_start: float = -1, y_end: float = 1, ) -> None: """ Utility function to plot how the given body-system evolves over time. No doctest provided since this function does not have a return value. """ fig = plt.figure() fig.canvas.manager.set_window_title(title) ax = plt.axes( xlim=(x_start, x_end), ylim=(y_start, y_end) ) # Set section to be plotted plt.gca().set_aspect("equal") # Fix aspect ratio # Each body is drawn as a patch by the plt-function patches = [ plt.Circle((body.position_x, body.position_y), body.size, fc=body.color) for body in body_system.bodies ] for patch in patches: ax.add_patch(patch) # Function called at each step of the animation def update(frame: int) -> list[plt.Circle]: # noqa: ARG001 update_step(body_system, DELTA_TIME, patches) return patches anim = animation.FuncAnimation( # noqa: F841 fig, update, interval=INTERVAL, blit=True ) plt.show() def example_1() -> BodySystem: """ Example 1: figure-8 solution to the 3-body-problem This example can be seen as a test of the implementation: given the right initial conditions, the bodies should move in a figure-8. (initial conditions taken from http://www.artcompsci.org/vol_1/v1_web/node56.html) >>> body_system = example_1() >>> len(body_system) 3 """ 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) def example_2() -> BodySystem: """ Example 2: Moon's orbit around the earth This example can be seen as a test of the implementation: given the right initial conditions, the moon should orbit around the earth as it actually does. (mass, velocity and distance taken from https://en.wikipedia.org/wiki/Earth and https://en.wikipedia.org/wiki/Moon) No doctest provided since this function does not have a return value. """ 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) def example_3() -> BodySystem: """ Example 3: Random system with many bodies. No doctest provided since this function does not have a return value. """ 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) if __name__ == "__main__": plot("Figure-8 solution to the 3-body-problem", example_1(), -2, 2, -2, 2) plot( "Moon's orbit around the earth", example_2(), -430000000, 430000000, -430000000, 430000000, ) plot("Random system with many bodies", example_3(), -1.5, 1.5, -1.5, 1.5)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/mirror_formulae.py
physics/mirror_formulae.py
""" This module contains the functions to calculate the focal length, object distance and image distance of a mirror. The mirror formula is an equation that relates the object distance (u), image distance (v), and focal length (f) of a spherical mirror. It is commonly used in optics to determine the position and characteristics of an image formed by a mirror. It is expressed using the formulae : ------------------- | 1/f = 1/v + 1/u | ------------------- Where, f = Focal length of the spherical mirror (metre) v = Image distance from the mirror (metre) u = Object distance from the mirror (metre) The signs of the distances are taken with respect to the sign convention. The sign convention is as follows: 1) Object is always placed to the left of mirror 2) Distances measured in the direction of the incident ray are positive and the distances measured in the direction opposite to that of the incident rays are negative. 3) All distances are measured from the pole of the mirror. There are a few assumptions that are made while using the mirror formulae. They are as follows: 1) Thin Mirror: The mirror is assumed to be thin, meaning its thickness is negligible compared to its radius of curvature. This assumption allows us to treat the mirror as a two-dimensional surface. 2) Spherical Mirror: The mirror is assumed to have a spherical shape. While this assumption may not hold exactly for all mirrors, it is a reasonable approximation for most practical purposes. 3) Small Angles: The angles involved in the derivation are assumed to be small. This assumption allows us to use the small-angle approximation, where the tangent of a small angle is approximately equal to the angle itself. It simplifies the calculations and makes the derivation more manageable. 4) Paraxial Rays: The mirror formula is derived using paraxial rays, which are rays that are close to the principal axis and make small angles with it. This assumption ensures that the rays are close enough to the principal axis, making the calculations more accurate. 5) Reflection and Refraction Laws: The derivation assumes that the laws of reflection and refraction hold. These laws state that the angle of incidence is equal to the angle of reflection for reflection, and the incident and refracted rays lie in the same plane and obey Snell's law for refraction. (Description and Assumptions adapted from https://www.collegesearch.in/articles/mirror-formula-derivation) (Sign Convention adapted from https://www.toppr.com/ask/content/concept/sign-convention-for-mirrors-210189/) """ def focal_length(distance_of_object: float, distance_of_image: float) -> float: """ >>> from math import isclose >>> isclose(focal_length(10, 20), 6.66666666666666) True >>> from math import isclose >>> isclose(focal_length(9.5, 6.7), 3.929012346) True >>> focal_length(0, 20) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: Invalid inputs. Enter non zero values with respect to the sign convention. """ if distance_of_object == 0 or distance_of_image == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) focal_length = 1 / ((1 / distance_of_object) + (1 / distance_of_image)) return focal_length def object_distance(focal_length: float, distance_of_image: float) -> float: """ >>> from math import isclose >>> isclose(object_distance(30, 20), -60.0) True >>> from math import isclose >>> isclose(object_distance(10.5, 11.7), 102.375) True >>> object_distance(90, 0) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: Invalid inputs. Enter non zero values with respect to the sign convention. """ if distance_of_image == 0 or focal_length == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) object_distance = 1 / ((1 / focal_length) - (1 / distance_of_image)) return object_distance def image_distance(focal_length: float, distance_of_object: float) -> float: """ >>> from math import isclose >>> isclose(image_distance(10, 40), 13.33333333) True >>> from math import isclose >>> isclose(image_distance(1.5, 6.7), 1.932692308) True >>> image_distance(0, 0) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: Invalid inputs. Enter non zero values with respect to the sign convention. """ if distance_of_object == 0 or focal_length == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) image_distance = 1 / ((1 / focal_length) - (1 / distance_of_object)) return image_distance
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/casimir_effect.py
physics/casimir_effect.py
""" Title : Finding the value of magnitude of either the Casimir force, the surface area of one of the plates or distance between the plates provided that the other two parameters are given. Description : In quantum field theory, the Casimir effect is a physical force acting on the macroscopic boundaries of a confined space which arises from the quantum fluctuations of the field. It is a physical force exerted between separate objects, which is due to neither charge, gravity, nor the exchange of particles, but instead is due to resonance of all-pervasive energy fields in the intervening space between the objects. Since the strength of the force falls off rapidly with distance it is only measurable when the distance between the objects is extremely small. On a submicron scale, this force becomes so strong that it becomes the dominant force between uncharged conductors. Dutch physicist Hendrik B. G. Casimir first proposed the existence of the force, and he formulated an experiment to detect it in 1948 while participating in research at Philips Research Labs. The classic form of his experiment used a pair of uncharged parallel metal plates in a vacuum, and successfully demonstrated the force to within 15% of the value he had predicted according to his theory. The Casimir force F for idealized, perfectly conducting plates of surface area A square meter and placed at a distance of a meter apart with vacuum between them is expressed as - F = - ((Reduced Planck Constant ℏ) * c * Pi^2 * A) / (240 * a^4) Here, the negative sign indicates the force is attractive in nature. For the ease of calculation, only the magnitude of the force is considered. Source : - https://en.wikipedia.org/wiki/Casimir_effect - https://www.cs.mcgill.ca/~rwest/wikispeedia/wpcd/wp/c/Casimir_effect.htm - Casimir, H. B. ; Polder, D. (1948) "The Influence of Retardation on the London-van der Waals Forces", Physical Review, vol. 73, Issue 4, pp. 360-372 """ from __future__ import annotations from math import pi # Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of # Pi and the function REDUCED_PLANCK_CONSTANT = 1.054571817e-34 # unit of ℏ : J * s SPEED_OF_LIGHT = 3e8 # unit of c : m * s^-1 def casimir_force(force: float, area: float, distance: float) -> dict[str, float]: """ Input Parameters ---------------- force -> Casimir Force : magnitude in Newtons area -> Surface area of each plate : magnitude in square meters distance -> Distance between two plates : distance in Meters Returns ------- result : dict name, value pair of the parameter having Zero as it's value Returns the value of one of the parameters specified as 0, provided the values of other parameters are given. >>> casimir_force(force = 0, area = 4, distance = 0.03) {'force': 6.4248189174864216e-21} >>> casimir_force(force = 2635e-13, area = 0.0023, distance = 0) {'distance': 1.0323056015031114e-05} >>> casimir_force(force = 2737e-21, area = 0, distance = 0.0023746) {'area': 0.06688838837354052} >>> casimir_force(force = 3457e-12, area = 0, distance = 0) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 >>> casimir_force(force = 3457e-12, area = 0, distance = -0.00344) Traceback (most recent call last): ... ValueError: Distance can not be negative >>> casimir_force(force = -912e-12, area = 0, distance = 0.09374) Traceback (most recent call last): ... ValueError: Magnitude of force can not be negative """ 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") # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/altitude_pressure.py
physics/altitude_pressure.py
""" Title : Calculate altitude using Pressure Description : The below algorithm approximates the altitude using Barometric formula """ def get_altitude_at_pressure(pressure: float) -> float: """ This method calculates the altitude from Pressure wrt to Sea level pressure as reference .Pressure is in Pascals https://en.wikipedia.org/wiki/Pressure_altitude https://community.bosch-sensortec.com/t5/Question-and-answers/How-to-calculate-the-altitude-from-the-pressure-sensor-data/qaq-p/5702 H = 44330 * [1 - (P/p0)^(1/5.255) ] Where : H = altitude (m) P = measured pressure p0 = reference pressure at sea level 101325 Pa Examples: >>> get_altitude_at_pressure(pressure=100_000) 105.47836610778828 >>> get_altitude_at_pressure(pressure=101_325) 0.0 >>> get_altitude_at_pressure(pressure=80_000) 1855.873388064995 >>> get_altitude_at_pressure(pressure=201_325) Traceback (most recent call last): ... ValueError: Value Higher than Pressure at Sea Level ! >>> get_altitude_at_pressure(pressure=-80_000) Traceback (most recent call last): ... ValueError: Atmospheric Pressure can not be negative ! """ if pressure > 101325: raise ValueError("Value Higher than Pressure at Sea Level !") if pressure < 0: raise ValueError("Atmospheric Pressure can not be negative !") return 44_330 * (1 - (pressure / 101_325) ** (1 / 5.5255)) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/reynolds_number.py
physics/reynolds_number.py
""" Title : computing the Reynolds number to find out the type of flow (laminar or turbulent) Reynolds number is a dimensionless quantity that is used to determine the type of flow pattern as laminar or turbulent while flowing through a pipe. Reynolds number is defined by the ratio of inertial forces to that of viscous forces. R = Inertial Forces / Viscous Forces R = (p * V * D)/μ where : p = Density of fluid (in Kg/m^3) D = Diameter of pipe through which fluid flows (in m) V = Velocity of flow of the fluid (in m/s) μ = Viscosity of the fluid (in Ns/m^2) If the Reynolds number calculated is high (greater than 2000), then the flow through the pipe is said to be turbulent. If Reynolds number is low (less than 2000), the flow is said to be laminar. Numerically, these are acceptable values, although in general the laminar and turbulent flows are classified according to a range. Laminar flow falls below Reynolds number of 1100 and turbulent falls in a range greater than 2200. Laminar flow is the type of flow in which the fluid travels smoothly in regular paths. Conversely, turbulent flow isn't smooth and follows an irregular path with lots of mixing. Reference : https://byjus.com/physics/reynolds-number/ """ def reynolds_number( density: float, velocity: float, diameter: float, viscosity: float ) -> float: """ >>> reynolds_number(900, 2.5, 0.05, 0.4) 281.25 >>> reynolds_number(450, 3.86, 0.078, 0.23) 589.0695652173912 >>> reynolds_number(234, -4.5, 0.3, 0.44) 717.9545454545454 >>> reynolds_number(-90, 2, 0.045, 1) Traceback (most recent call last): ... ValueError: please ensure that density, diameter and viscosity are positive >>> reynolds_number(0, 2, -0.4, -2) Traceback (most recent call last): ... ValueError: please ensure that density, diameter and viscosity are positive """ if density <= 0 or diameter <= 0 or viscosity <= 0: raise ValueError( "please ensure that density, diameter and viscosity are positive" ) return (density * abs(velocity) * diameter) / viscosity if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/kinetic_energy.py
physics/kinetic_energy.py
""" Find the kinetic energy of an object, given its mass and velocity. Description : In physics, the kinetic energy of an object is the energy that it possesses due to its motion.It is defined as the work needed to accelerate a body of a given mass from rest to its stated velocity.Having gained this energy during its acceleration, the body maintains this kinetic energy unless its speed changes.The same amount of work is done by the body when decelerating from its current speed to a state of rest.Formally, a kinetic energy is any term in a system's Lagrangian which includes a derivative with respect to time. In classical mechanics, the kinetic energy of a non-rotating object of mass m traveling at a speed v is ½mv².In relativistic mechanics, this is a good approximation only when v is much less than the speed of light.The standard unit of kinetic energy is the joule, while the English unit of kinetic energy is the foot-pound. Reference : https://en.m.wikipedia.org/wiki/Kinetic_energy """ def kinetic_energy(mass: float, velocity: float) -> float: """ Calculate kinetic energy. The kinetic energy of a non-rotating object of mass m traveling at a speed v is ½mv² >>> kinetic_energy(10,10) 500.0 >>> kinetic_energy(0,10) 0.0 >>> kinetic_energy(10,0) 0.0 >>> kinetic_energy(20,-20) 4000.0 >>> kinetic_energy(0,0) 0.0 >>> kinetic_energy(2,2) 4.0 >>> kinetic_energy(100,100) 500000.0 """ if mass < 0: raise ValueError("The mass of a body cannot be negative") return 0.5 * mass * abs(velocity) * abs(velocity) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/potential_energy.py
physics/potential_energy.py
from scipy.constants import g """ Finding the gravitational potential energy of an object with reference to the earth,by taking its mass and height above the ground as input Description : Gravitational energy or gravitational potential energy is the potential energy a massive object has in relation to another massive object due to gravity. It is the potential energy associated with the gravitational field, which is released (converted into kinetic energy) when the objects fall towards each other. Gravitational potential energy increases when two objects are brought further apart. For two pairwise interacting point particles, the gravitational potential energy U is given by U=-GMm/R where M and m are the masses of the two particles, R is the distance between them, and G is the gravitational constant. Close to the Earth's surface, the gravitational field is approximately constant, and the gravitational potential energy of an object reduces to U=mgh where m is the object's mass, g=GM/R² is the gravity of Earth, and h is the height of the object's center of mass above a chosen reference level. Reference : "https://en.m.wikipedia.org/wiki/Gravitational_energy" """ def potential_energy(mass: float, height: float) -> float: # function will accept mass and height as parameters and return potential energy """ >>> potential_energy(10,10) 980.665 >>> potential_energy(0,5) 0.0 >>> potential_energy(8,0) 0.0 >>> potential_energy(10,5) 490.3325 >>> potential_energy(0,0) 0.0 >>> potential_energy(2,8) 156.9064 >>> potential_energy(20,100) 19613.3 """ 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 if __name__ == "__main__": from doctest import testmod testmod(name="potential_energy")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/malus_law.py
physics/malus_law.py
import math """ Finding the intensity of light transmitted through a polariser using Malus Law and by taking initial intensity and angle between polariser and axis as input Description : Malus's law, which is named after Étienne-Louis Malus, says that when a perfect polarizer is placed in a polarized beam of light, the irradiance, I, of the light that passes through is given by I=I'cos²θ where I' is the initial intensity and θ is the angle between the light's initial polarization direction and the axis of the polarizer. A beam of unpolarized light can be thought of as containing a uniform mixture of linear polarizations at all possible angles. Since the average value of cos²θ is 1/2, the transmission coefficient becomes I/I' = 1/2 In practice, some light is lost in the polarizer and the actual transmission will be somewhat lower than this, around 38% for Polaroid-type polarizers but considerably higher (>49.9%) for some birefringent prism types. If two polarizers are placed one after another (the second polarizer is generally called an analyzer), the mutual angle between their polarizing axes gives the value of θ in Malus's law. If the two axes are orthogonal, the polarizers are crossed and in theory no light is transmitted, though again practically speaking no polarizer is perfect and the transmission is not exactly zero (for example, crossed Polaroid sheets appear slightly blue in colour because their extinction ratio is better in the red). If a transparent object is placed between the crossed polarizers, any polarization effects present in the sample (such as birefringence) will be shown as an increase in transmission. This effect is used in polarimetry to measure the optical activity of a sample. Real polarizers are also not perfect blockers of the polarization orthogonal to their polarization axis; the ratio of the transmission of the unwanted component to the wanted component is called the extinction ratio, and varies from around 1:500 for Polaroid to about 1:106 for Glan-Taylor prism polarizers. Reference : "https://en.wikipedia.org/wiki/Polarizer#Malus's_law_and_other_properties" """ def malus_law(initial_intensity: float, angle: float) -> float: """ >>> round(malus_law(10,45),2) 5.0 >>> round(malus_law(100,60),2) 25.0 >>> round(malus_law(50,150),2) 37.5 >>> round(malus_law(75,270),2) 0.0 >>> round(malus_law(10,-900),2) Traceback (most recent call last): ... ValueError: In Malus Law, the angle is in the range 0-360 degrees >>> round(malus_law(10,900),2) Traceback (most recent call last): ... ValueError: In Malus Law, the angle is in the range 0-360 degrees >>> round(malus_law(-100,900),2) Traceback (most recent call last): ... ValueError: The value of intensity cannot be negative >>> round(malus_law(100,180),2) 100.0 >>> round(malus_law(100,360),2) 100.0 """ 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) if __name__ == "__main__": import doctest doctest.testmod(name="malus_law")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/__init__.py
physics/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/photoelectric_effect.py
physics/photoelectric_effect.py
""" The photoelectric effect is the emission of electrons when electromagnetic radiation , such as light, hits a material. Electrons emitted in this manner are called photoelectrons. In 1905, Einstein proposed a theory of the photoelectric effect using a concept that light consists of tiny packets of energy known as photons or light quanta. Each packet carries energy hv that is proportional to the frequency v of the corresponding electromagnetic wave. The proportionality constant h has become known as the Planck constant. In the range of kinetic energies of the electrons that are removed from their varying atomic bindings by the absorption of a photon of energy hv, the highest kinetic energy K_max is : K_max = hv-W Here, W is the minimum energy required to remove an electron from the surface of the material. It is called the work function of the surface Reference: https://en.wikipedia.org/wiki/Photoelectric_effect """ PLANCK_CONSTANT_JS = 6.6261 * pow(10, -34) # in SI (Js) PLANCK_CONSTANT_EVS = 4.1357 * pow(10, -15) # in eVs def maximum_kinetic_energy( frequency: float, work_function: float, in_ev: bool = False ) -> float: """ Calculates the maximum kinetic energy of emitted electron from the surface. if the maximum kinetic energy is zero then no electron will be emitted or given electromagnetic wave frequency is small. frequency (float): Frequency of electromagnetic wave. work_function (float): Work function of the surface. in_ev (optional)(bool): Pass True if values are in eV. Usage example: >>> maximum_kinetic_energy(1000000,2) 0 >>> maximum_kinetic_energy(1000000,2,True) 0 >>> maximum_kinetic_energy(10000000000000000,2,True) 39.357000000000006 >>> maximum_kinetic_energy(-9,20) Traceback (most recent call last): ... ValueError: Frequency can't be negative. >>> maximum_kinetic_energy(1000,"a") Traceback (most recent call last): ... TypeError: unsupported operand type(s) for -: 'float' and 'str' """ if frequency < 0: raise ValueError("Frequency can't be negative.") if in_ev: return max(PLANCK_CONSTANT_EVS * frequency - work_function, 0) return max(PLANCK_CONSTANT_JS * frequency - work_function, 0) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/horizontal_projectile_motion.py
physics/horizontal_projectile_motion.py
""" Horizontal Projectile Motion problem in physics. This algorithm solves a specific problem in which the motion starts from the ground as can be seen below:: (v = 0) * * * * * * * * * * * * GROUND GROUND For more info: https://en.wikipedia.org/wiki/Projectile_motion """ # Importing packages from math import radians as deg_to_rad from math import sin # Acceleration Constant on Earth (unit m/s^2) g = 9.80665 def check_args(init_velocity: float, angle: float) -> None: """ Check that the arguments are valid """ # Ensure valid instance if not isinstance(init_velocity, (int, float)): raise TypeError("Invalid velocity. Should be an integer or float.") if not isinstance(angle, (int, float)): raise TypeError("Invalid angle. Should be an integer or float.") # 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.") def horizontal_distance(init_velocity: float, angle: float) -> float: r""" Returns the horizontal distance that the object cover Formula: .. math:: \frac{v_0^2 \cdot \sin(2 \alpha)}{g} v_0 - \text{initial velocity} \alpha - \text{angle} >>> horizontal_distance(30, 45) 91.77 >>> horizontal_distance(100, 78) 414.76 >>> horizontal_distance(-1, 20) Traceback (most recent call last): ... ValueError: Invalid velocity. Should be a positive number. >>> horizontal_distance(30, -20) Traceback (most recent call last): ... ValueError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = deg_to_rad(2 * angle) return round(init_velocity**2 * sin(radians) / g, 2) def max_height(init_velocity: float, angle: float) -> float: r""" Returns the maximum height that the object reach Formula: .. math:: \frac{v_0^2 \cdot \sin^2 (\alpha)}{2 g} v_0 - \text{initial velocity} \alpha - \text{angle} >>> max_height(30, 45) 22.94 >>> max_height(100, 78) 487.82 >>> max_height("a", 20) Traceback (most recent call last): ... TypeError: Invalid velocity. Should be an integer or float. >>> horizontal_distance(30, "b") Traceback (most recent call last): ... TypeError: Invalid angle. Should be an integer or float. """ check_args(init_velocity, angle) radians = deg_to_rad(angle) return round(init_velocity**2 * sin(radians) ** 2 / (2 * g), 2) def total_time(init_velocity: float, angle: float) -> float: r""" Returns total time of the motion Formula: .. math:: \frac{2 v_0 \cdot \sin (\alpha)}{g} v_0 - \text{initial velocity} \alpha - \text{angle} >>> total_time(30, 45) 4.33 >>> total_time(100, 78) 19.95 >>> total_time(-10, 40) Traceback (most recent call last): ... ValueError: Invalid velocity. Should be a positive number. >>> total_time(30, "b") Traceback (most recent call last): ... TypeError: Invalid angle. Should be an integer or float. """ check_args(init_velocity, angle) radians = deg_to_rad(angle) return round(2 * init_velocity * sin(radians) / g, 2) def test_motion() -> None: """ Test motion >>> test_motion() """ 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 if __name__ == "__main__": from doctest import testmod testmod() # Get input from user init_vel = float(input("Initial Velocity: ").strip()) # Get input from user angle = float(input("angle: ").strip()) # Print results print() print("Results: ") print(f"Horizontal Distance: {horizontal_distance(init_vel, angle)!s} [m]") print(f"Maximum Height: {max_height(init_vel, angle)!s} [m]") print(f"Total Time: {total_time(init_vel, angle)!s} [s]")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/in_static_equilibrium.py
physics/in_static_equilibrium.py
""" Checks if a system of forces is in static equilibrium. """ from __future__ import annotations from numpy import array, cos, cross, float64, radians, sin from numpy.typing import NDArray def polar_force( magnitude: float, angle: float, radian_mode: bool = False ) -> list[float]: """ Resolves force along rectangular components. (force, angle) => (force_x, force_y) >>> import math >>> force = polar_force(10, 45) >>> math.isclose(force[0], 7.071067811865477) True >>> math.isclose(force[1], 7.0710678118654755) True >>> force = polar_force(10, 3.14, radian_mode=True) >>> math.isclose(force[0], -9.999987317275396) True >>> math.isclose(force[1], 0.01592652916486828) True """ if radian_mode: return [magnitude * cos(angle), magnitude * sin(angle)] return [magnitude * cos(radians(angle)), magnitude * sin(radians(angle))] def in_static_equilibrium( forces: NDArray[float64], location: NDArray[float64], eps: float = 10**-1 ) -> bool: """ Check if a system is in equilibrium. It takes two numpy.array objects. forces ==> [ [force1_x, force1_y], [force2_x, force2_y], ....] location ==> [ [x1, y1], [x2, y2], ....] >>> force = array([[1, 1], [-1, 2]]) >>> location = array([[1, 0], [10, 0]]) >>> in_static_equilibrium(force, location) False """ # summation of moments is zero moments: NDArray[float64] = cross(location, forces) sum_moments: float = sum(moments) return bool(abs(sum_moments) < eps) if __name__ == "__main__": # Test to check if it works forces = array( [ polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90), ] ) location: NDArray[float64] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg forces = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) location = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg forces = array([[0, -2000], [0, -1200], [0, 15600], [0, -12400]]) location = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/basic_orbital_capture.py
physics/basic_orbital_capture.py
""" These two functions will return the radii of impact for a target object of mass M and radius R as well as it's effective cross sectional area sigma. That is to say any projectile with velocity v passing within sigma, will impact the target object with mass M. The derivation of which is given at the bottom of this file. The derivation shows that a projectile does not need to aim directly at the target body in order to hit it, as R_capture>R_target. Astronomers refer to the effective cross section for capture as sigma=π*R_capture**2. This algorithm does not account for an N-body problem. """ from math import pow, sqrt # noqa: A004 from scipy.constants import G, c, pi def capture_radii( target_body_radius: float, target_body_mass: float, projectile_velocity: float ) -> float: """ Input Params: ------------- target_body_radius: Radius of the central body SI units: meters | m target_body_mass: Mass of the central body SI units: kilograms | kg projectile_velocity: Velocity of object moving toward central body SI units: meters/second | m/s Returns: -------- >>> capture_radii(6.957e8, 1.99e30, 25000.0) 17209590691.0 >>> capture_radii(-6.957e8, 1.99e30, 25000.0) Traceback (most recent call last): ... ValueError: Radius cannot be less than 0 >>> capture_radii(6.957e8, -1.99e30, 25000.0) Traceback (most recent call last): ... ValueError: Mass cannot be less than 0 >>> capture_radii(6.957e8, 1.99e30, c+1) Traceback (most recent call last): ... ValueError: Cannot go beyond speed of light Returned SI units: ------------------ meters | m """ if target_body_mass < 0: raise ValueError("Mass cannot be less than 0") if target_body_radius < 0: raise ValueError("Radius cannot be less than 0") if projectile_velocity > c: raise ValueError("Cannot go beyond speed of light") escape_velocity_squared = (2 * G * target_body_mass) / target_body_radius capture_radius = target_body_radius * sqrt( 1 + escape_velocity_squared / pow(projectile_velocity, 2) ) return round(capture_radius, 0) def capture_area(capture_radius: float) -> float: """ Input Param: ------------ capture_radius: The radius of orbital capture and impact for a central body of mass M and a projectile moving towards it with velocity v SI units: meters | m Returns: -------- >>> capture_area(17209590691) 9.304455331329126e+20 >>> capture_area(-1) Traceback (most recent call last): ... ValueError: Cannot have a capture radius less than 0 Returned SI units: ------------------ meters*meters | m**2 """ if capture_radius < 0: raise ValueError("Cannot have a capture radius less than 0") sigma = pi * pow(capture_radius, 2) return round(sigma, 0) if __name__ == "__main__": from doctest import testmod testmod() """ Derivation: Let: Mt=target mass, Rt=target radius, v=projectile_velocity, r_0=radius of projectile at instant 0 to CM of target v_p=v at closest approach, r_p=radius from projectile to target CM at closest approach, R_capture= radius of impact for projectile with velocity v (1)At time=0 the projectile's energy falling from infinity| E=K+U=0.5*m*(v**2)+0 E_initial=0.5*m*(v**2) (2)at time=0 the angular momentum of the projectile relative to CM target| L_initial=m*r_0*v*sin(Θ)->m*r_0*v*(R_capture/r_0)->m*v*R_capture L_i=m*v*R_capture (3)The energy of the projectile at closest approach will be its kinetic energy at closest approach plus gravitational potential energy(-(GMm)/R)| E_p=K_p+U_p->E_p=0.5*m*(v_p**2)-(G*Mt*m)/r_p E_p=0.0.5*m*(v_p**2)-(G*Mt*m)/r_p (4)The angular momentum of the projectile relative to the target at closest approach will be L_p=m*r_p*v_p*sin(Θ), however relative to the target Θ=90° sin(90°)=1| L_p=m*r_p*v_p (5)Using conservation of angular momentum and energy, we can write a quadratic equation that solves for r_p| (a) Ei=Ep-> 0.5*m*(v**2)=0.5*m*(v_p**2)-(G*Mt*m)/r_p-> v**2=v_p**2-(2*G*Mt)/r_p (b) Li=Lp-> m*v*R_capture=m*r_p*v_p-> v*R_capture=r_p*v_p-> v_p=(v*R_capture)/r_p (c) b plugs int a| v**2=((v*R_capture)/r_p)**2-(2*G*Mt)/r_p-> v**2-(v**2)*(R_c**2)/(r_p**2)+(2*G*Mt)/r_p=0-> (v**2)*(r_p**2)+2*G*Mt*r_p-(v**2)*(R_c**2)=0 (d) Using the quadratic formula, we'll solve for r_p then rearrange to solve to R_capture r_p=(-2*G*Mt ± sqrt(4*G^2*Mt^2+ 4(v^4*R_c^2)))/(2*v^2)-> r_p=(-G*Mt ± sqrt(G^2*Mt+v^4*R_c^2))/v^2-> r_p<0 is something we can ignore, as it has no physical meaning for our purposes.-> r_p=(-G*Mt)/v^2 + sqrt(G^2*Mt^2/v^4 + R_c^2) (e)We are trying to solve for R_c. We are looking for impact, so we want r_p=Rt Rt + G*Mt/v^2 = sqrt(G^2*Mt^2/v^4 + R_c^2)-> (Rt + G*Mt/v^2)^2 = G^2*Mt^2/v^4 + R_c^2-> Rt^2 + 2*G*Mt*Rt/v^2 + G^2*Mt^2/v^4 = G^2*Mt^2/v^4 + R_c^2-> Rt**2 + 2*G*Mt*Rt/v**2 = R_c**2-> Rt**2 * (1 + 2*G*Mt/Rt *1/v**2) = R_c**2-> escape velocity = sqrt(2GM/R)= v_escape**2=2GM/R-> Rt**2 * (1 + v_esc**2/v**2) = R_c**2-> (6) R_capture = Rt * sqrt(1 + v_esc**2/v**2) Source: Problem Set 3 #8 c.Fall_2017|Honors Astronomy|Professor Rachel Bezanson Source #2: http://www.nssc.ac.cn/wxzygx/weixin/201607/P020160718380095698873.pdf 8.8 Planetary Rendezvous: Pg.368 """
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/lens_formulae.py
physics/lens_formulae.py
""" This module has functions which calculate focal length of lens, distance of image from the lens and distance of object from the lens. The above is calculated using the lens formula. In optics, the relationship between the distance of the image (v), the distance of the object (u), and the focal length (f) of the lens is given by the formula known as the Lens formula. The Lens formula is applicable for convex as well as concave lenses. The formula is given as follows: ------------------- | 1/f = 1/v + 1/u | ------------------- Where f = focal length of the lens in meters. v = distance of the image from the lens in meters. u = distance of the object from the lens in meters. To make our calculations easy few assumptions are made while deriving the formula which are important to keep in mind before solving this equation. The assumptions are as follows: 1. The object O is a point object lying somewhere on the principle axis. 2. The lens is thin. 3. The aperture of the lens taken must be small. 4. The angles of incidence and angle of refraction should be small. Sign convention is a set of rules to set signs for image distance, object distance, focal length, etc for mathematical analysis of image formation. According to it: 1. Object is always placed to the left of lens. 2. All distances are measured from the optical centre of the mirror. 3. Distances measured in the direction of the incident ray are positive and the distances measured in the direction opposite to that of the incident rays are negative. 4. Distances measured along y-axis above the principal axis are positive and that measured along y-axis below the principal axis are negative. Note: Sign convention can be reversed and will still give the correct results. Reference for Sign convention: https://www.toppr.com/ask/content/concept/sign-convention-for-lenses-210246/ Reference for assumptions: https://testbook.com/physics/derivation-of-lens-maker-formula """ def focal_length_of_lens( object_distance_from_lens: float, image_distance_from_lens: float ) -> float: """ Doctests: >>> from math import isclose >>> isclose(focal_length_of_lens(10,4), 6.666666666666667) True >>> from math import isclose >>> isclose(focal_length_of_lens(2.7,5.8), -5.0516129032258075) True >>> focal_length_of_lens(0, 20) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: Invalid inputs. Enter non zero values with respect to the sign convention. """ if object_distance_from_lens == 0 or image_distance_from_lens == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) focal_length = 1 / ( (1 / image_distance_from_lens) - (1 / object_distance_from_lens) ) return focal_length def object_distance( focal_length_of_lens: float, image_distance_from_lens: float ) -> float: """ Doctests: >>> from math import isclose >>> isclose(object_distance(10,40), -13.333333333333332) True >>> from math import isclose >>> isclose(object_distance(6.2,1.5), 1.9787234042553192) True >>> object_distance(0, 20) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: Invalid inputs. Enter non zero values with respect to the sign convention. """ if image_distance_from_lens == 0 or focal_length_of_lens == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) object_distance = 1 / ((1 / image_distance_from_lens) - (1 / focal_length_of_lens)) return object_distance def image_distance( focal_length_of_lens: float, object_distance_from_lens: float ) -> float: """ Doctests: >>> from math import isclose >>> isclose(image_distance(50,40), 22.22222222222222) True >>> from math import isclose >>> isclose(image_distance(5.3,7.9), 3.1719696969696973) True >>> object_distance(0, 20) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: Invalid inputs. Enter non zero values with respect to the sign convention. """ if object_distance_from_lens == 0 or focal_length_of_lens == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) image_distance = 1 / ((1 / object_distance_from_lens) + (1 / focal_length_of_lens)) return image_distance
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/escape_velocity.py
physics/escape_velocity.py
import math def escape_velocity(mass: float, radius: float) -> float: """ Calculates the escape velocity needed to break free from a celestial body's gravitational field. The formula used is: v = sqrt(2 * G * M / R) where: v = escape velocity (m/s) G = gravitational constant (6.67430 * 10^-11 m^3 kg^-1 s^-2) M = mass of the celestial body (kg) R = radius from the center of mass (m) Source: https://en.wikipedia.org/wiki/Escape_velocity Args: mass (float): Mass of the celestial body in kilograms. radius (float): Radius from the center of mass in meters. Returns: float: Escape velocity in meters per second, rounded to 3 decimal places. Examples: >>> escape_velocity(mass=5.972e24, radius=6.371e6) # Earth 11185.978 >>> escape_velocity(mass=7.348e22, radius=1.737e6) # Moon 2376.307 >>> escape_velocity(mass=1.898e27, radius=6.9911e7) # Jupiter 60199.545 >>> escape_velocity(mass=0, radius=1.0) 0.0 >>> escape_velocity(mass=1.0, radius=0) Traceback (most recent call last): ... ZeroDivisionError: Radius cannot be zero. """ gravitational_constant = 6.67430e-11 # m^3 kg^-1 s^-2 if radius == 0: raise ZeroDivisionError("Radius cannot be zero.") velocity = math.sqrt(2 * gravitational_constant * mass / radius) return round(velocity, 3) if __name__ == "__main__": import doctest doctest.testmod() print("Calculate escape velocity of a celestial body...\n") try: mass = float(input("Enter mass of the celestial body (in kgs): ").strip()) radius = float(input("Enter radius from the center of mass (in ms): ").strip()) velocity = escape_velocity(mass=mass, radius=radius) print(f"Escape velocity is {velocity} m/s") except ValueError: print("Invalid input. Please enter valid numeric values.") except ZeroDivisionError as e: print(e)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/speeds_of_gas_molecules.py
physics/speeds_of_gas_molecules.py
""" The root-mean-square, average and most probable speeds of gas molecules are derived from the Maxwell-Boltzmann distribution. The Maxwell-Boltzmann distribution is a probability distribution that describes the distribution of speeds of particles in an ideal gas. The distribution is given by the following equation:: ------------------------------------------------- | f(v) = (M/2πRT)^(3/2) * 4πv^2 * e^(-Mv^2/2RT) | ------------------------------------------------- where: * ``f(v)`` is the fraction of molecules with a speed ``v`` * ``M`` is the molar mass of the gas in kg/mol * ``R`` is the gas constant * ``T`` is the absolute temperature More information about the Maxwell-Boltzmann distribution can be found here: https://en.wikipedia.org/wiki/Maxwell%E2%80%93Boltzmann_distribution The average speed can be calculated by integrating the Maxwell-Boltzmann distribution from 0 to infinity and dividing by the total number of molecules. The result is:: ---------------------- | v_avg = √(8RT/πM) | ---------------------- The most probable speed is the speed at which the Maxwell-Boltzmann distribution is at its maximum. This can be found by differentiating the Maxwell-Boltzmann distribution with respect to ``v`` and setting the result equal to zero. The result is:: ---------------------- | v_mp = √(2RT/M) | ---------------------- The root-mean-square speed is another measure of the average speed of the molecules in a gas. It is calculated by taking the square root of the average of the squares of the speeds of the molecules. The result is:: ---------------------- | v_rms = √(3RT/M) | ---------------------- Here we have defined functions to calculate the average and most probable speeds of molecules in a gas given the temperature and molar mass of the gas. """ # import the constants R and pi from the scipy.constants library from scipy.constants import R, pi def avg_speed_of_molecule(temperature: float, molar_mass: float) -> float: """ Takes the temperature (in K) and molar mass (in kg/mol) of a gas and returns the average speed of a molecule in the gas (in m/s). Examples: >>> avg_speed_of_molecule(273, 0.028) # nitrogen at 273 K 454.3488755062257 >>> avg_speed_of_molecule(300, 0.032) # oxygen at 300 K 445.5257273433045 >>> avg_speed_of_molecule(-273, 0.028) # invalid temperature Traceback (most recent call last): ... Exception: Absolute temperature cannot be less than 0 K >>> avg_speed_of_molecule(273, 0) # invalid molar mass Traceback (most recent call last): ... Exception: Molar mass should be greater than 0 kg/mol """ if temperature < 0: raise Exception("Absolute temperature cannot be less than 0 K") if molar_mass <= 0: raise Exception("Molar mass should be greater than 0 kg/mol") return (8 * R * temperature / (pi * molar_mass)) ** 0.5 def mps_speed_of_molecule(temperature: float, molar_mass: float) -> float: """ Takes the temperature (in K) and molar mass (in kg/mol) of a gas and returns the most probable speed of a molecule in the gas (in m/s). Examples: >>> mps_speed_of_molecule(273, 0.028) # nitrogen at 273 K 402.65620702280023 >>> mps_speed_of_molecule(300, 0.032) # oxygen at 300 K 394.8368955535605 >>> mps_speed_of_molecule(-273, 0.028) # invalid temperature Traceback (most recent call last): ... Exception: Absolute temperature cannot be less than 0 K >>> mps_speed_of_molecule(273, 0) # invalid molar mass Traceback (most recent call last): ... Exception: Molar mass should be greater than 0 kg/mol """ if temperature < 0: raise Exception("Absolute temperature cannot be less than 0 K") if molar_mass <= 0: raise Exception("Molar mass should be greater than 0 kg/mol") return (2 * R * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/coulombs_law.py
physics/coulombs_law.py
""" Coulomb's law states that the magnitude of the electrostatic force of attraction or repulsion between two point charges is directly proportional to the product of the magnitudes of charges and inversely proportional to the square of the distance between them. F = k * q1 * q2 / r^2 k is Coulomb's constant and equals 1/(4π*ε0) q1 is charge of first body (C) q2 is charge of second body (C) r is distance between two charged bodies (m) Reference: https://en.wikipedia.org/wiki/Coulomb%27s_law """ def coulombs_law(q1: float, q2: float, radius: float) -> float: """ Calculate the electrostatic force of attraction or repulsion between two point charges >>> coulombs_law(15.5, 20, 15) 12382849136.06 >>> coulombs_law(1, 15, 5) 5392531075.38 >>> coulombs_law(20, -50, 15) -39944674632.44 >>> coulombs_law(-5, -8, 10) 3595020716.92 >>> coulombs_law(50, 100, 50) 17975103584.6 """ if radius <= 0: raise ValueError("The radius is always a positive number") return round(((8.9875517923 * 10**9) * q1 * q2) / (radius**2), 2) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/hubble_parameter.py
physics/hubble_parameter.py
""" Title : Calculating the Hubble Parameter Description : The Hubble parameter H is the Universe expansion rate in any time. In cosmology is customary to use the redshift redshift in place of time, becausethe redshift is directily mensure in the light of galaxies moving away from us. So, the general relation that we obtain is H = hubble_constant*(radiation_density*(redshift+1)**4 + matter_density*(redshift+1)**3 + curvature*(redshift+1)**2 + dark_energy)**(1/2) where radiation_density, matter_density, dark_energy are the relativity (the percentage) energy densities that exist in the Universe today. Here, matter_density is the sum of the barion density and the dark matter. Curvature is the curvature parameter and can be written in term of the densities by the completeness curvature = 1 - (matter_density + radiation_density + dark_energy) Source : https://www.sciencedirect.com/topics/mathematics/hubble-parameter """ def hubble_parameter( hubble_constant: float, radiation_density: float, matter_density: float, dark_energy: float, redshift: float, ) -> float: """ Input Parameters ---------------- hubble_constant: Hubble constante is the expansion rate today usually given in km/(s*Mpc) radiation_density: relative radiation density today matter_density: relative mass density today dark_energy: relative dark energy density today redshift: the light redshift Returns ------- result : Hubble parameter in and the unit km/s/Mpc (the unit can be changed if you want, just need to change the unit of the Hubble constant) >>> hubble_parameter(hubble_constant=68.3, radiation_density=1e-4, ... matter_density=-0.3, dark_energy=0.7, redshift=1) Traceback (most recent call last): ... ValueError: All input parameters must be positive >>> hubble_parameter(hubble_constant=68.3, radiation_density=1e-4, ... matter_density= 1.2, dark_energy=0.7, redshift=1) Traceback (most recent call last): ... ValueError: Relative densities cannot be greater than one >>> hubble_parameter(hubble_constant=68.3, radiation_density=1e-4, ... matter_density= 0.3, dark_energy=0.7, redshift=0) 68.3 """ 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 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation matter_density = 0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1e-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/mass_energy_equivalence.py
physics/mass_energy_equivalence.py
""" Title: Finding the energy equivalence of mass and mass equivalence of energy by Einstein's equation. Description: Einstein's mass-energy equivalence is a pivotal concept in theoretical physics. It asserts that energy (E) and mass (m) are directly related by the speed of light in vacuum (c) squared, as described in the equation E = mc². This means that mass and energy are interchangeable; a mass increase corresponds to an energy increase, and vice versa. This principle has profound implications in nuclear reactions, explaining the release of immense energy from minuscule changes in atomic nuclei. Equations: E = mc² and m = E/c², where m is mass, E is Energy, c is speed of light in vacuum. Reference: https://en.wikipedia.org/wiki/Mass%E2%80%93energy_equivalence """ from scipy.constants import c # speed of light in vacuum (299792458 m/s) def energy_from_mass(mass: float) -> float: """ Calculates the Energy equivalence of the Mass using E = mc² in SI units J from Mass in kg. mass (float): Mass of body. Usage example: >>> energy_from_mass(124.56) 1.11948945063458e+19 >>> energy_from_mass(320) 2.8760165719578165e+19 >>> energy_from_mass(0) 0.0 >>> energy_from_mass(-967.9) Traceback (most recent call last): ... ValueError: Mass can't be negative. """ if mass < 0: raise ValueError("Mass can't be negative.") return mass * c**2 def mass_from_energy(energy: float) -> float: """ Calculates the Mass equivalence of the Energy using m = E/c² in SI units kg from Energy in J. energy (float): Mass of body. Usage example: >>> mass_from_energy(124.56) 1.3859169098203872e-15 >>> mass_from_energy(320) 3.560480179371579e-15 >>> mass_from_energy(0) 0.0 >>> mass_from_energy(-967.9) Traceback (most recent call last): ... ValueError: Energy can't be negative. """ if energy < 0: raise ValueError("Energy can't be negative.") return energy / c**2 if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/centripetal_force.py
physics/centripetal_force.py
""" Description : Centripetal force is the force acting on an object in curvilinear motion directed towards the axis of rotation or centre of curvature. The unit of centripetal force is newton. The centripetal force is always directed perpendicular to the direction of the object's displacement. Using Newton's second law of motion, it is found that the centripetal force of an object moving in a circular path always acts towards the centre of the circle. The Centripetal Force Formula is given as the product of mass (in kg) and tangential velocity (in meters per second) squared, divided by the radius (in meters) that implies that on doubling the tangential velocity, the centripetal force will be quadrupled. Mathematically it is written as: F = mv²/r Where, F is the Centripetal force, m is the mass of the object, v is the speed or velocity of the object and r is the radius. Reference: https://byjus.com/physics/centripetal-and-centrifugal-force/ """ def centripetal(mass: float, velocity: float, radius: float) -> float: """ The Centripetal Force formula is given as: (m*v*v)/r >>> round(centripetal(15.5,-30,10),2) 1395.0 >>> round(centripetal(10,15,5),2) 450.0 >>> round(centripetal(20,-50,15),2) 3333.33 >>> round(centripetal(12.25,40,25),2) 784.0 >>> round(centripetal(50,100,50),2) 10000.0 """ 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 if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/physics/image_data/__init__.py
physics/image_data/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/blockchain/diophantine_equation.py
blockchain/diophantine_equation.py
from __future__ import annotations from maths.greatest_common_divisor import greatest_common_divisor def diophantine(a: int, b: int, c: int) -> tuple[float, float]: """ Diophantine Equation : Given integers a,b,c ( at least one of a and b != 0), the diophantine equation a*x + b*y = c has a solution (where x and y are integers) iff greatest_common_divisor(a,b) divides c. GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) >>> diophantine(10,6,14) (-7.0, 14.0) >>> diophantine(391,299,-69) (9.0, -12.0) But above equation has one more solution i.e., x = -4, y = 5. That's why we need diophantine all solution function. """ assert ( c % greatest_common_divisor(a, b) == 0 ) # greatest_common_divisor(a,b) is in maths directory (d, x, y) = extended_gcd(a, b) # extended_gcd(a,b) function implemented below r = c / d return (r * x, r * y) def diophantine_all_soln(a: int, b: int, c: int, n: int = 2) -> None: """ Lemma : if n|ab and gcd(a,n) = 1, then n|b. Finding All solutions of Diophantine Equations: Theorem : Let gcd(a,b) = d, a = d*p, b = d*q. If (x0,y0) is a solution of Diophantine Equation a*x + b*y = c. a*x0 + b*y0 = c, then all the solutions have the form a(x0 + t*q) + b(y0 - t*p) = c, where t is an arbitrary integer. n is the number of solution you want, n = 2 by default >>> diophantine_all_soln(10, 6, 14) -7.0 14.0 -4.0 9.0 >>> diophantine_all_soln(10, 6, 14, 4) -7.0 14.0 -4.0 9.0 -1.0 4.0 2.0 -1.0 >>> diophantine_all_soln(391, 299, -69, n = 4) 9.0 -12.0 22.0 -29.0 35.0 -46.0 48.0 -63.0 """ (x0, y0) = diophantine(a, b, c) # Initial value d = greatest_common_divisor(a, b) p = a // d q = b // d for i in range(n): x = x0 + i * q y = y0 - i * p print(x, y) def extended_gcd(a: int, b: int) -> tuple[int, int, int]: """ Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x and y, then d = gcd(a,b) >>> extended_gcd(10, 6) (2, -1, 2) >>> extended_gcd(7, 5) (1, -2, 3) """ assert a >= 0 assert b >= 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) assert a % d == 0 assert b % d == 0 assert d == a * x + b * y return (d, x, y) if __name__ == "__main__": from doctest import testmod testmod(name="diophantine", verbose=True) testmod(name="diophantine_all_soln", verbose=True) testmod(name="extended_gcd", verbose=True) testmod(name="greatest_common_divisor", verbose=True)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/blockchain/__init__.py
blockchain/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/__init__.py
project_euler/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_191/sol1.py
project_euler/problem_191/sol1.py
""" Prize Strings Problem 191 A particular school offers cash rewards to children with good attendance and punctuality. If they are absent for three consecutive days or late on more than one occasion then they forfeit their prize. During an n-day period a trinary string is formed for each child consisting of L's (late), O's (on time), and A's (absent). Although there are eighty-one trinary strings for a 4-day period that can be formed, exactly forty-three strings would lead to a prize: OOOO OOOA OOOL OOAO OOAA OOAL OOLO OOLA OAOO OAOA OAOL OAAO OAAL OALO OALA OLOO OLOA OLAO OLAA AOOO AOOA AOOL AOAO AOAA AOAL AOLO AOLA AAOO AAOA AAOL AALO AALA ALOO ALOA ALAO ALAA LOOO LOOA LOAO LOAA LAOO LAOA LAAO How many "prize" strings exist over a 30-day period? References: - The original Project Euler project page: https://projecteuler.net/problem=191 """ cache: dict[tuple[int, int, int], int] = {} def _calculate(days: int, absent: int, late: int) -> int: """ A small helper function for the recursion, mainly to have a clean interface for the solution() function below. It should get called with the number of days (corresponding to the desired length of the 'prize strings'), and the initial values for the number of consecutive absent days and number of total late days. >>> _calculate(days=4, absent=0, late=0) 43 >>> _calculate(days=30, absent=2, late=0) 0 >>> _calculate(days=30, absent=1, late=0) 98950096 """ # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on key = (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one state_late = _calculate(days - 1, absent, late + 1) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 state_absent = _calculate(days - 1, absent + 1, 0) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter state_ontime = _calculate(days - 1, absent, 0) prizestrings = state_late + state_absent + state_ontime cache[key] = prizestrings return prizestrings def solution(days: int = 30) -> int: """ Returns the number of possible prize strings for a particular number of days, using a simple recursive function with caching to speed it up. >>> solution() 1918080160 >>> solution(4) 43 """ return _calculate(days, absent=0, late=0) if __name__ == "__main__": print(solution())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_191/__init__.py
project_euler/problem_191/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_686/sol1.py
project_euler/problem_686/sol1.py
""" Project Euler Problem 686: https://projecteuler.net/problem=686 2^7 = 128 is the first power of two whose leading digits are "12". The next power of two whose leading digits are "12" is 2^80. Define p(L,n) to be the nth-smallest value of j such that the base 10 representation of 2^j begins with the digits of L. So p(12, 1) = 7 and p(12, 2) = 80. You are given that p(123, 45) = 12710. Find p(123, 678910). """ import math def log_difference(number: int) -> float: """ This function returns the decimal value of a number multiplied with log(2) Since the problem is on powers of two, finding the powers of two with large exponents is time consuming. Hence we use log to reduce compute time. We can find out that the first power of 2 with starting digits 123 is 90. Computing 2^90 is time consuming. Hence we find log(2^90) = 90*log(2) = 27.092699609758302 But we require only the decimal part to determine whether the power starts with 123. So we just return the decimal part of the log product. Therefore we return 0.092699609758302 >>> log_difference(90) 0.092699609758302 >>> log_difference(379) 0.090368356648852 """ log_number = math.log(2, 10) * number difference = round((log_number - int(log_number)), 15) return difference def solution(number: int = 678910) -> int: """ This function calculates the power of two which is nth (n = number) smallest value of power of 2 such that the starting digits of the 2^power is 123. For example the powers of 2 for which starting digits is 123 are: 90, 379, 575, 864, 1060, 1545, 1741, 2030, 2226, 2515 and so on. 90 is the first power of 2 whose starting digits are 123, 379 is second power of 2 whose starting digits are 123, and so on. So if number = 10, then solution returns 2515 as we observe from above series. We will define a lowerbound and upperbound. lowerbound = log(1.23), upperbound = log(1.24) because we need to find the powers that yield 123 as starting digits. log(1.23) = 0.08990511143939792, log(1,24) = 0.09342168516223506. We use 1.23 and not 12.3 or 123, because log(1.23) yields only decimal value which is less than 1. log(12.3) will be same decimal value but 1 added to it which is log(12.3) = 1.093421685162235. We observe that decimal value remains same no matter 1.23 or 12.3 Since we use the function log_difference(), which returns the value that is only decimal part, using 1.23 is logical. If we see, 90*log(2) = 27.092699609758302, decimal part = 0.092699609758302, which is inside the range of lowerbound and upperbound. If we compute the difference between all the powers which lead to 123 starting digits is as follows: 379 - 90 = 289 575 - 379 = 196 864 - 575 = 289 1060 - 864 = 196 We see a pattern here. The difference is either 196 or 289 = 196 + 93. Hence to optimize the algorithm we will increment by 196 or 93 depending upon the log_difference() value. Let's take for example 90. Since 90 is the first power leading to staring digits as 123, we will increment iterator by 196. Because the difference between any two powers leading to 123 as staring digits is greater than or equal to 196. After incrementing by 196 we get 286. log_difference(286) = 0.09457875989861 which is greater than upperbound. The next power is 379, and we need to add 93 to get there. The iterator will now become 379, which is the next power leading to 123 as starting digits. Let's take 1060. We increment by 196, we get 1256. log_difference(1256) = 0.09367455396034, Which is greater than upperbound hence we increment by 93. Now iterator is 1349. log_difference(1349) = 0.08946415071057 which is less than lowerbound. The next power is 1545 and we need to add 196 to get 1545. Conditions are as follows: 1) If we find a power whose log_difference() is in the range of lower and upperbound, we will increment by 196. which implies that the power is a number which will lead to 123 as starting digits. 2) If we find a power, whose log_difference() is greater than or equal upperbound, we will increment by 93. 3) if log_difference() < lowerbound, we increment by 196. Reference to the above logic: https://math.stackexchange.com/questions/4093970/powers-of-2-starting-with-123-does-a-pattern-exist >>> solution(1000) 284168 >>> solution(56000) 15924915 >>> solution(678910) 193060223 """ power_iterator = 90 position = 0 lower_limit = math.log(1.23, 10) upper_limit = math.log(1.24, 10) previous_power = 0 while position < number: difference = log_difference(power_iterator) if difference >= upper_limit: power_iterator += 93 elif difference < lower_limit: power_iterator += 196 else: previous_power = power_iterator power_iterator += 196 position += 1 return previous_power if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_686/__init__.py
project_euler/problem_686/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_002/sol2.py
project_euler/problem_002/sol2.py
""" Project Euler Problem 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 """ even_fibs = [] a, b = 0, 1 while b <= n: if b % 2 == 0: even_fibs.append(b) a, b = b, a + b return sum(even_fibs) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_002/sol4.py
project_euler/problem_002/sol4.py
""" Project Euler Problem 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ import math from decimal import Decimal, getcontext def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 >>> solution(3.4) 2 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") getcontext().prec = 100 phi = (Decimal(5) ** Decimal("0.5") + 1) / Decimal(2) index = (math.floor(math.log(n * (phi + 2), phi) - 1) // 3) * 3 + 2 num = Decimal(round(phi ** Decimal(index + 1))) / (phi + 2) total = num // 2 return int(total) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_002/sol3.py
project_euler/problem_002/sol3.py
""" Project Euler Problem 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 """ if n <= 1: return 0 a = 0 b = 2 count = 0 while 4 * b + a <= n: a, b = b, 4 * b + a count += a return count + b if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_002/sol5.py
project_euler/problem_002/sol5.py
""" Project Euler Problem 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 """ fib = [0, 1] i = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1]) if fib[i + 2] > n: break i += 1 total = 0 for j in range(len(fib) - 1): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_002/sol1.py
project_euler/problem_002/sol1.py
""" Project Euler Problem 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 """ i = 1 j = 2 total = 0 while j <= n: if j % 2 == 0: total += j i, j = j, i + j return total if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_002/__init__.py
project_euler/problem_002/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_116/sol1.py
project_euler/problem_116/sol1.py
""" Project Euler Problem 116: https://projecteuler.net/problem=116 A row of five grey square tiles is to have a number of its tiles replaced with coloured oblong tiles chosen from red (length two), green (length three), or blue (length four). If red tiles are chosen there are exactly seven ways this can be done. |red,red|grey|grey|grey| |grey|red,red|grey|grey| |grey|grey|red,red|grey| |grey|grey|grey|red,red| |red,red|red,red|grey| |red,red|grey|red,red| |grey|red,red|red,red| If green tiles are chosen there are three ways. |green,green,green|grey|grey| |grey|green,green,green|grey| |grey|grey|green,green,green| And if blue tiles are chosen there are two ways. |blue,blue,blue,blue|grey| |grey|blue,blue,blue,blue| Assuming that colours cannot be mixed there are 7 + 3 + 2 = 12 ways of replacing the grey tiles in a row measuring five units in length. How many different ways can the grey tiles in a row measuring fifty units in length be replaced if colours cannot be mixed and at least one coloured tile must be used? NOTE: This is related to Problem 117 (https://projecteuler.net/problem=117). """ def solution(length: int = 50) -> int: """ Returns the number of different ways can the grey tiles in a row of the given length be replaced if colours cannot be mixed and at least one coloured tile must be used >>> solution(5) 12 """ different_colour_ways_number = [[0] * 3 for _ in range(length + 1)] for row_length in range(length + 1): for tile_length in range(2, 5): for tile_start in range(row_length - tile_length + 1): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length]) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_116/__init__.py
project_euler/problem_116/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_493/sol1.py
project_euler/problem_493/sol1.py
""" Project Euler Problem 493: https://projecteuler.net/problem=493 70 coloured balls are placed in an urn, 10 for each of the seven rainbow colours. What is the expected number of distinct colours in 20 randomly picked balls? Give your answer with nine digits after the decimal point (a.bcdefghij). ----- This combinatorial problem can be solved by decomposing the problem into the following steps: 1. Calculate the total number of possible picking combinations [combinations := binom_coeff(70, 20)] 2. Calculate the number of combinations with one colour missing [missing := binom_coeff(60, 20)] 3. Calculate the probability of one colour missing [missing_prob := missing / combinations] 4. Calculate the probability of no colour missing [no_missing_prob := 1 - missing_prob] 5. Calculate the expected number of distinct colours [expected = 7 * no_missing_prob] References: - https://en.wikipedia.org/wiki/Binomial_coefficient """ import math BALLS_PER_COLOUR = 10 NUM_COLOURS = 7 NUM_BALLS = BALLS_PER_COLOUR * NUM_COLOURS def solution(num_picks: int = 20) -> str: """ Calculates the expected number of distinct colours >>> solution(10) '5.669644129' >>> solution(30) '6.985042712' """ total = math.comb(NUM_BALLS, num_picks) missing_colour = math.comb(NUM_BALLS - BALLS_PER_COLOUR, num_picks) result = NUM_COLOURS * (1 - missing_colour / total) return f"{result:.9f}" if __name__ == "__main__": print(solution(20))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_493/__init__.py
project_euler/problem_493/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_025/sol2.py
project_euler/problem_025/sol2.py
""" The Fibonacci sequence is defined by the recurrence relation: Fn = Fn-1 + Fn-2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? """ from collections.abc import Generator def fibonacci_generator() -> Generator[int]: """ A generator that produces numbers in the Fibonacci sequence >>> generator = fibonacci_generator() >>> next(generator) 1 >>> next(generator) 2 >>> next(generator) 3 >>> next(generator) 5 >>> next(generator) 8 """ a, b = 0, 1 while True: a, b = b, a + b yield b def solution(n: int = 1000) -> int: """Returns the index of the first term in the Fibonacci sequence to contain n digits. >>> solution(1000) 4782 >>> solution(100) 476 >>> solution(50) 237 >>> solution(3) 12 """ answer = 1 gen = fibonacci_generator() while len(str(next(gen))) < n: answer += 1 return answer + 1 if __name__ == "__main__": print(solution(int(str(input()).strip())))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_025/sol3.py
project_euler/problem_025/sol3.py
""" The Fibonacci sequence is defined by the recurrence relation: Fn = Fn-1 + Fn-2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? """ def solution(n: int = 1000) -> int: """Returns the index of the first term in the Fibonacci sequence to contain n digits. >>> solution(1000) 4782 >>> solution(100) 476 >>> solution(50) 237 >>> solution(3) 12 """ f1, f2 = 1, 1 index = 2 while True: i = 0 f = f1 + f2 f1, f2 = f2, f index += 1 for _ in str(f): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_025/sol1.py
project_euler/problem_025/sol1.py
""" The Fibonacci sequence is defined by the recurrence relation: Fn = Fn-1 + Fn-2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? """ def fibonacci(n: int) -> int: """ Computes the Fibonacci number for input n by iterating through n numbers and creating an array of ints using the Fibonacci formula. Returns the nth element of the array. >>> fibonacci(2) 1 >>> fibonacci(3) 2 >>> fibonacci(5) 5 >>> fibonacci(10) 55 >>> fibonacci(12) 144 """ if n == 1 or not isinstance(n, int): return 0 elif n == 2: return 1 else: sequence = [0, 1] for i in range(2, n + 1): sequence.append(sequence[i - 1] + sequence[i - 2]) return sequence[n] def fibonacci_digits_index(n: int) -> int: """ Computes incrementing Fibonacci numbers starting from 3 until the length of the resulting Fibonacci result is the input value n. Returns the term of the Fibonacci sequence where this occurs. >>> fibonacci_digits_index(1000) 4782 >>> fibonacci_digits_index(100) 476 >>> fibonacci_digits_index(50) 237 >>> fibonacci_digits_index(3) 12 """ digits = 0 index = 2 while digits < n: index += 1 digits = len(str(fibonacci(index))) return index def solution(n: int = 1000) -> int: """ Returns the index of the first term in the Fibonacci sequence to contain n digits. >>> solution(1000) 4782 >>> solution(100) 476 >>> solution(50) 237 >>> solution(3) 12 """ return fibonacci_digits_index(n) if __name__ == "__main__": print(solution(int(str(input()).strip())))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_025/__init__.py
project_euler/problem_025/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_017/sol1.py
project_euler/problem_017/sol1.py
""" Number letter counts Problem 17: https://projecteuler.net/problem=17 If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance withBritish usage. """ def solution(n: int = 1000) -> int: """Returns the number of letters used to write all numbers from 1 to n. where n is lower or equals to 1000. >>> solution(1000) 21124 >>> solution(5) 19 """ # number of letters in zero, one, two, ..., nineteen (0 for zero since it's # never said aloud) ones_counts = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8] # number of letters in twenty, thirty, ..., ninety (0 for numbers less than # 20 due to inconsistency in teens) tens_counts = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6] count = 0 for i in range(1, n + 1): if i < 1000: if i >= 100: # add number of letters for "n hundred" count += ones_counts[i // 100] + 7 if i % 100 != 0: # add number of letters for "and" if number is not multiple # of 100 count += 3 if 0 < i % 100 < 20: # add number of letters for one, two, three, ..., nineteen # (could be combined with below if not for inconsistency in # teens) count += ones_counts[i % 100] else: # add number of letters for twenty, twenty one, ..., ninety # nine count += ones_counts[i % 10] count += tens_counts[(i % 100 - i % 10) // 10] else: count += ones_counts[i // 1000] + 8 return count if __name__ == "__main__": print(solution(int(input().strip())))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_017/__init__.py
project_euler/problem_017/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_044/sol1.py
project_euler/problem_044/sol1.py
""" Problem 44: https://projecteuler.net/problem=44 Pentagonal numbers are generated by the formula, Pn=n(3n-1)/2. The first ten pentagonal numbers are: 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 - 22 = 48, is not pentagonal. Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk - Pj| is minimised; what is the value of D? """ def is_pentagonal(n: int) -> bool: """ Returns True if n is pentagonal, False otherwise. >>> is_pentagonal(330) True >>> is_pentagonal(7683) False >>> is_pentagonal(2380) True """ root = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def solution(limit: int = 5000) -> int: """ Returns the minimum difference of two pentagonal numbers P1 and P2 such that P1 + P2 is pentagonal and P2 - P1 is pentagonal. >>> solution(5000) 5482660 """ pentagonal_nums = [(i * (3 * i - 1)) // 2 for i in range(1, limit)] for i, pentagonal_i in enumerate(pentagonal_nums): for j in range(i, len(pentagonal_nums)): pentagonal_j = pentagonal_nums[j] a = pentagonal_i + pentagonal_j b = pentagonal_j - pentagonal_i if is_pentagonal(a) and is_pentagonal(b): return b return -1 if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_044/__init__.py
project_euler/problem_044/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_079/sol1.py
project_euler/problem_079/sol1.py
""" Project Euler Problem 79: https://projecteuler.net/problem=79 Passcode derivation A common security method used for online banking is to ask the user for three random characters from a passcode. For example, if the passcode was 531278, they may ask for the 2nd, 3rd, and 5th characters; the expected reply would be: 317. The text file, keylog.txt, contains fifty successful login attempts. Given that the three characters are always asked for in order, analyse the file so as to determine the shortest possible secret passcode of unknown length. """ import itertools from pathlib import Path def find_secret_passcode(logins: list[str]) -> int: """ Returns the shortest possible secret passcode of unknown length. >>> find_secret_passcode(["135", "259", "235", "189", "690", "168", "120", ... "136", "289", "589", "160", "165", "580", "369", "250", "280"]) 12365890 >>> find_secret_passcode(["426", "281", "061", "819" "268", "406", "420", ... "428", "209", "689", "019", "421", "469", "261", "681", "201"]) 4206819 """ # Split each login by character e.g. '319' -> ('3', '1', '9') split_logins = [tuple(login) for login in logins] unique_chars = {char for login in split_logins for char in login} for permutation in itertools.permutations(unique_chars): satisfied = True for login in logins: if not ( permutation.index(login[0]) < permutation.index(login[1]) < permutation.index(login[2]) ): satisfied = False break if satisfied: return int("".join(permutation)) raise Exception("Unable to find the secret passcode") def solution(input_file: str = "keylog.txt") -> int: """ Returns the shortest possible secret passcode of unknown length for successful login attempts given by `input_file` text file. >>> solution("keylog_test.txt") 6312980 """ logins = Path(__file__).parent.joinpath(input_file).read_text().splitlines() return find_secret_passcode(logins) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_079/__init__.py
project_euler/problem_079/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_085/sol1.py
project_euler/problem_085/sol1.py
""" Project Euler Problem 85: https://projecteuler.net/problem=85 By counting carefully it can be seen that a rectangular grid measuring 3 by 2 contains eighteen rectangles.  Although there exists no rectangular grid that contains exactly two million rectangles, find the area of the grid with the nearest solution. Solution: For a grid with side-lengths a and b, the number of rectangles contained in the grid is [a*(a+1)/2] * [b*(b+1)/2)], which happens to be the product of the a-th and b-th triangle numbers. So to find the solution grid (a,b), we need to find the two triangle numbers whose product is closest to two million. Denote these two triangle numbers Ta and Tb. We want their product Ta*Tb to be as close as possible to 2m. Assuming that the best solution is fairly close to 2m, We can assume that both Ta and Tb are roughly bounded by 2m. Since Ta = a(a+1)/2, we can assume that a (and similarly b) are roughly bounded by sqrt(2 * 2m) = 2000. Since this is a rough bound, to be on the safe side we add 10%. Therefore we start by generating all the triangle numbers Ta for 1 <= a <= 2200. This can be done iteratively since the ith triangle number is the sum of 1,2, ... ,i, and so T(i) = T(i-1) + i. We then search this list of triangle numbers for the two that give a product closest to our target of two million. Rather than testing every combination of 2 elements of the list, which would find the result in quadratic time, we can find the best pair in linear time. We iterate through the list of triangle numbers using enumerate() so we have a and Ta. Since we want Ta * Tb to be as close as possible to 2m, we know that Tb needs to be roughly 2m / Ta. Using the formula Tb = b*(b+1)/2 as well as the quadratic formula, we can solve for b: b is roughly (-1 + sqrt(1 + 8 * 2m / Ta)) / 2. Since the closest integers to this estimate will give product closest to 2m, we only need to consider the integers above and below. It's then a simple matter to get the triangle numbers corresponding to those integers, calculate the product Ta * Tb, compare that product to our target 2m, and keep track of the (a,b) pair that comes the closest. Reference: https://en.wikipedia.org/wiki/Triangular_number https://en.wikipedia.org/wiki/Quadratic_formula """ from __future__ import annotations from math import ceil, floor, sqrt def solution(target: int = 2000000) -> int: """ Find the area of the grid which contains as close to two million rectangles as possible. >>> solution(20) 6 >>> solution(2000) 72 >>> solution(2000000000) 86595 """ triangle_numbers: list[int] = [0] idx: int for idx in range(1, ceil(sqrt(target * 2) * 1.1)): triangle_numbers.append(triangle_numbers[-1] + idx) # we want this to be as close as possible to target best_product: int = 0 # the area corresponding to the grid that gives the product closest to target area: int = 0 # an estimate of b, using the quadratic formula b_estimate: float # the largest integer less than b_estimate b_floor: int # the largest integer less than b_estimate b_ceil: int # the triangle number corresponding to b_floor triangle_b_first_guess: int # the triangle number corresponding to b_ceil triangle_b_second_guess: int for idx_a, triangle_a in enumerate(triangle_numbers[1:], 1): b_estimate = (-1 + sqrt(1 + 8 * target / triangle_a)) / 2 b_floor = floor(b_estimate) b_ceil = ceil(b_estimate) triangle_b_first_guess = triangle_numbers[b_floor] triangle_b_second_guess = triangle_numbers[b_ceil] if abs(target - triangle_b_first_guess * triangle_a) < abs( target - best_product ): best_product = triangle_b_first_guess * triangle_a area = idx_a * b_floor if abs(target - triangle_b_second_guess * triangle_a) < abs( target - best_product ): best_product = triangle_b_second_guess * triangle_a area = idx_a * b_ceil return area if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_085/__init__.py
project_euler/problem_085/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_001/sol2.py
project_euler/problem_001/sol2.py
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ total = 0 terms = (n - 1) // 3 total += ((terms) * (6 + (terms - 1) * 3)) // 2 # total of an A.P. terms = (n - 1) // 5 total += ((terms) * (10 + (terms - 1) * 5)) // 2 terms = (n - 1) // 15 total -= ((terms) * (30 + (terms - 1) * 15)) // 2 return total if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_001/sol4.py
project_euler/problem_001/sol4.py
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ xmulti = [] zmulti = [] z = 3 x = 5 temp = 1 while True: result = z * temp if result < n: zmulti.append(result) temp += 1 else: temp = 1 break while True: result = x * temp if result < n: xmulti.append(result) temp += 1 else: break collection = list(set(xmulti + zmulti)) return sum(collection) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_001/sol3.py
project_euler/problem_001/sol3.py
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ This solution is based on the pattern that the successive numbers in the series follow: 0+3,+2,+1,+3,+1,+2,+3. Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ total = 0 num = 0 while 1: num += 3 if num >= n: break total += num num += 2 if num >= n: break total += num num += 1 if num >= n: break total += num num += 3 if num >= n: break total += num num += 1 if num >= n: break total += num num += 2 if num >= n: break total += num num += 3 if num >= n: break total += num return total if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_001/sol5.py
project_euler/problem_001/sol5.py
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. A straightforward pythonic solution using list comprehension. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ return sum(i for i in range(n) if i % 3 == 0 or i % 5 == 0) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_001/sol1.py
project_euler/problem_001/sol1.py
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 >>> solution(-7) 0 """ return sum(e for e in range(3, n) if e % 3 == 0 or e % 5 == 0) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_001/sol6.py
project_euler/problem_001/sol6.py
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ a = 3 result = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 return result if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_001/__init__.py
project_euler/problem_001/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_001/sol7.py
project_euler/problem_001/sol7.py
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ result = 0 for i in range(n): if i % 3 == 0 or i % 5 == 0: result += i return result if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_121/sol1.py
project_euler/problem_121/sol1.py
""" A bag contains one red disc and one blue disc. In a game of chance a player takes a disc at random and its colour is noted. After each turn the disc is returned to the bag, an extra red disc is added, and another disc is taken at random. The player pays £1 to play and wins if they have taken more blue discs than red discs at the end of the game. If the game is played for four turns, the probability of a player winning is exactly 11/120, and so the maximum prize fund the banker should allocate for winning in this game would be £10 before they would expect to incur a loss. Note that any payout will be a whole number of pounds and also includes the original £1 paid to play the game, so in the example given the player actually wins £9. Find the maximum prize fund that should be allocated to a single game in which fifteen turns are played. Solution: For each 15-disc sequence of red and blue for which there are more red than blue, we calculate the probability of that sequence and add it to the total probability of the player winning. The inverse of this probability gives an upper bound for the prize if the banker wants to avoid an expected loss. """ from itertools import product def solution(num_turns: int = 15) -> int: """ Find the maximum prize fund that should be allocated to a single game in which fifteen turns are played. >>> solution(4) 10 >>> solution(10) 225 """ total_prob: float = 0.0 prob: float num_blue: int num_red: int ind: int col: int series: tuple[int, ...] for series in product(range(2), repeat=num_turns): num_blue = series.count(1) num_red = num_turns - num_blue if num_red >= num_blue: continue prob = 1.0 for ind, col in enumerate(series, 2): if col == 0: prob *= (ind - 1) / ind else: prob *= 1 / ind total_prob += prob return int(1 / total_prob) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false