### Installing Qiskit Python Library (Shell) Source: https://github.com/thealgorithms/python/blob/master/quantum/README.md This command uses the pip package installer to install the IBM Qiskit library, which is essential for programming quantum computers using Python with IBM's platform. Running this command makes the qiskit package available for import in Python scripts. ```Shell pip install qiskit ``` -------------------------------- ### Installing Cirq Python Library (Shell) Source: https://github.com/thealgorithms/python/blob/master/quantum/README.md This command installs the Google Cirq library using pip, invoked via the `python -m` runner, ensuring the correct Python environment's pip is used. Cirq is a Python framework for writing, simulating, and running quantum circuits. It's a necessary dependency for developing quantum algorithms with Google's tools. ```Shell python -m pip install cirq ``` -------------------------------- ### Installing Pre-commit Hook (Bash) Source: https://github.com/thealgorithms/python/blob/master/CONTRIBUTING.md Commands to install the pre-commit tool using pip and set up the Git hook in the current repository to run checks automatically before each commit. ```Bash python3 -m pip install pre-commit # only required the first time pre-commit install ``` -------------------------------- ### Installing and Running Ruff Checks (Bash) Source: https://github.com/thealgorithms/python/blob/master/CONTRIBUTING.md Commands to install the Ruff linter/formatter using pip and then run its checks on the codebase to identify style issues and potential errors. ```Bash python3 -m pip install ruff # only required the first time ruff check ``` -------------------------------- ### Installing and Running Black Formatter (Bash) Source: https://github.com/thealgorithms/python/blob/master/CONTRIBUTING.md Commands to install the Black Python code formatter via pip and then apply it to format all Python files in the current directory and its subdirectories. ```Bash python3 -m pip install black # only required the first time black . ``` -------------------------------- ### Example Function with Python Doctests (Python) Source: https://github.com/thealgorithms/python/blob/master/CONTRIBUTING.md Demonstrates how to include doctests within a Python function's docstring to show usage examples and provide executable tests for verification. ```Python def sum_ab(a, b): """ Return the sum of two integers a and b >>> sum_ab(2, 2) 4 >>> sum_ab(-2, 3) 1 >>> sum_ab(4.9, 5.1) 10.0 """ return a + b ``` -------------------------------- ### Example Function with Python Type Hints (Python) Source: https://github.com/thealgorithms/python/blob/master/CONTRIBUTING.md Demonstrates how to add type hints to function parameters and return values in Python for improved code clarity and static analysis. ```Python def sum_ab(a: int, b: int) -> int: return a + b ``` -------------------------------- ### Example of Trivial Python Comment (Python) Source: https://github.com/thealgorithms/python/blob/master/CONTRIBUTING.md Illustrates an example of a comment that is considered too simple and uninformative, as comments should provide more explanatory context. ```Python x = x + 2 # increased by 2 ``` -------------------------------- ### Running Superdense Coding Example in Python Source: https://github.com/thealgorithms/python/blob/master/quantum/superdense_coding.py.DISABLED.txt This block demonstrates how to execute the `superdense_coding` function when the script is run directly. It calls the function with example input bits (1, 1) and prints the resulting measurement counts, showing the outcome of the simulated quantum communication protocol. ```python if __name__ == "__main__": print(f"Counts for classical state send: {superdense_coding(1,1)}") ``` -------------------------------- ### Example of Good Python Docstring (Python) Source: https://github.com/thealgorithms/python/blob/master/CONTRIBUTING.md Shows the recommended style and indentation for adding a basic docstring to a Python function to explain its purpose. ```Python def sum_ab(a, b): """ Return the sum of two integers a and b. """ return a + b ``` -------------------------------- ### Executing Quantum Full Adder Example - Python Source: https://github.com/thealgorithms/python/blob/master/quantum/q_full_adder.py.DISABLED.txt This standard Python block demonstrates how to call the `quantum_full_adder` function when the script is executed directly. It calls the function with inputs (1, 1, 1) and prints the resulting measurement counts to the console. ```Python if __name__ == "__main__": print(f"Total sum count for state is: {quantum_full_adder(1, 1, 1)}") ``` -------------------------------- ### Defining Script Entry Point - Python Source: https://github.com/thealgorithms/python/blob/master/machine_learning/random_forest_classifier.py.broken.txt Standard Python idiom to ensure the `main` function is executed only when the script is run directly, not when imported as a module. ```Python if __name__ == "__main__": main() ``` -------------------------------- ### Example of Discouraged Python Input (Python) Source: https://github.com/thealgorithms/python/blob/master/CONTRIBUTING.md Illustrates the use of the built-in `input()` function, which is generally discouraged for core algorithm implementations in this repository, especially when combined with `eval`. ```Python input('Enter your input:') # Or even worse... input = eval(input("Enter your input: ")) ``` -------------------------------- ### Running BB84 Simulation Example and Doctests - Python Source: https://github.com/thealgorithms/python/blob/master/quantum/bb84.py.DISABLED.txt This block executes when the script is run directly. It demonstrates calling the `bb84` function to generate a key with specific parameters and runs the embedded doctests within the `bb84` function's docstring to verify its behavior against expected outputs. ```python if __name__ == "__main__": print(f"The generated key is : {bb84(8, seed=0)}") from doctest import testmod testmod() ``` -------------------------------- ### Importing Libraries for ML Example - Python Source: https://github.com/thealgorithms/python/blob/master/machine_learning/random_forest_classifier.py.broken.txt Imports necessary modules from scikit-learn and matplotlib for data handling, model training, evaluation, and plotting. Essential components like dataset loading, classifier, evaluation metrics, and data splitting are included. ```Python from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import plot_confusion_matrix from sklearn.model_selection import train_test_split ``` -------------------------------- ### Running Doctests - Python Source: https://github.com/thealgorithms/python/blob/master/quantum/ripple_adder_classic.py.DISABLED.txt This block serves as the standard entry point for the script. It ensures that the `doctest.testmod()` function is called only when the script is executed directly. `doctest` finds and runs tests embedded within the docstrings of the functions in the script, verifying their behavior against the provided examples. ```python if __name__ == "__main__": import doctest doctest.testmod() ``` -------------------------------- ### Defining Main Function - Python Source: https://github.com/thealgorithms/python/blob/master/machine_learning/random_forest_classifier.py.broken.txt Defines the `main` function that encapsulates the primary logic of the script. It includes a docstring explaining the example's purpose and the dataset used. ```Python def main(): """ Random Forest Classifier Example using sklearn function. Iris type dataset is used to demonstrate algorithm. """ ``` -------------------------------- ### Executing Quantum Half Adder Example in Python Source: https://github.com/thealgorithms/python/blob/master/quantum/half_adder.py.DISABLED.txt This block demonstrates how to call the `half_adder` function with specific inputs (1, 1) when the script is run directly. It executes the quantum circuit simulation and prints the resulting measurement counts for the sum and carry qubits. ```python if __name__ == "__main__": counts = half_adder(1, 1) print(f"Half Adder Output Qubit Counts: {counts}") ``` -------------------------------- ### Running Deutsch-Jozsa Examples - Python Source: https://github.com/thealgorithms/python/blob/master/quantum/deutsch_jozsa.py.DISABLED.txt This block demonstrates how to use the `deutsch_jozsa` function. It calls the function twice, once with the 'constant' case and once with the 'balanced' case, both for a 3-qubit input. It then prints the returned result counts from the simulation for each case, showing the expected outcome of the algorithm. ```Python if __name__ == "__main__": print(f"Deutsch Jozsa - Constant Oracle: {deutsch_jozsa('constant', 3)}") print(f"Deutsch Jozsa - Balanced Oracle: {deutsch_jozsa('balanced', 3)}") ``` -------------------------------- ### Importing Required Libraries - Python Source: https://github.com/thealgorithms/python/blob/master/machine_learning/gaussian_naive_bayes.py.broken.txt Imports necessary modules for data handling, machine learning algorithms (Gaussian Naive Bayes), model selection (train_test_split), evaluation metrics (accuracy_score, plot_confusion_matrix), plotting (matplotlib), and timing. ```python import time from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import accuracy_score, plot_confusion_matrix from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB ``` -------------------------------- ### Training RandomForestClassifier - Python Source: https://github.com/thealgorithms/python/blob/master/machine_learning/random_forest_classifier.py.broken.txt Initializes a `RandomForestClassifier` with 100 trees (`n_estimators=100`) and a fixed `random_state` for consistent results. The model is then trained using the `fit` method on the prepared training data (`x_train`, `y_train`). ```Python # Random Forest Classifier rand_for = RandomForestClassifier(random_state=42, n_estimators=100) rand_for.fit(x_train, y_train) ``` -------------------------------- ### Initializing, Training, and Predicting with GaussianNB - Python Source: https://github.com/thealgorithms/python/blob/master/machine_learning/gaussian_naive_bayes.py.broken.txt Initializes a `GaussianNB` model from scikit-learn. The model is trained (fitted) on the training data (`x_train`, `y_train`) using the `fit` method. After training, it makes predictions (`y_pred`) on the unseen test features (`x_test`) using the `predict` method. ```python # Gaussian Naive Bayes nb_model = GaussianNB() time.sleep(2.9) model_fit = nb_model.fit(x_train, y_train) y_pred = model_fit.predict(x_test) # Predictions on the test set ``` -------------------------------- ### Running Main Function Guard - Python Source: https://github.com/thealgorithms/python/blob/master/machine_learning/gaussian_naive_bayes.py.broken.txt Standard Python idiom that ensures the `main()` function is called only when the script is executed directly (not imported as a module). This structure organizes the primary execution flow of the script. ```python if __name__ == "__main__": main() ``` -------------------------------- ### Loading and Splitting Iris Dataset - Python Source: https://github.com/thealgorithms/python/blob/master/machine_learning/random_forest_classifier.py.broken.txt Loads the built-in Iris dataset from scikit-learn and separates features (`x`) and target (`y`). It then splits the data into 70% for training and 30% for testing using `train_test_split`, ensuring reproducibility with `random_state=1`. ```Python # Load Iris dataset iris = load_iris() # Split dataset into train and test data x = iris["data"] # features y = iris["target"] x_train, x_test, y_train, y_test = train_test_split( x, y, test_size=0.3, random_state=1 ) ``` -------------------------------- ### Implementing Random Forest Regression using Scikit-learn in Python Source: https://github.com/thealgorithms/python/blob/master/machine_learning/random_forest_regressor.py.broken.txt This snippet demonstrates the end-to-end process of applying Random Forest Regression. It loads the Boston house price dataset, splits the data into training and testing sets, initializes and trains a RandomForestRegressor model, makes predictions on the test data, and calculates the Mean Absolute Error (MAE) and Mean Squared Error (MSE) to evaluate the model's performance. Required dependencies include `sklearn`. ```python from sklearn.datasets import load_boston from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split def main(): """ Random Forest Regressor Example using sklearn function. Boston house price dataset is used to demonstrate the algorithm. """ # Load Boston house price dataset boston = load_boston() print(boston.keys()) # Split dataset into train and test data x = boston["data"] # features y = boston["target"] x_train, x_test, y_train, y_test = train_test_split( x, y, test_size=0.3, random_state=1 ) # Random Forest Regressor rand_for = RandomForestRegressor(random_state=42, n_estimators=300) rand_for.fit(x_train, y_train) # Predict target for test data predictions = rand_for.predict(x_test) predictions = predictions.reshape(len(predictions), 1) # Error printing print(f"Mean Absolute Error:\t {mean_absolute_error(y_test, predictions)}") print(f"Mean Square Error :\t {mean_squared_error(y_test, predictions)}") ``` -------------------------------- ### Loading and Splitting Iris Dataset - Python Source: https://github.com/thealgorithms/python/blob/master/machine_learning/gaussian_naive_bayes.py.broken.txt Loads the standard Iris dataset using scikit-learn's `load_iris` function. It then separates the features (`x`) and target labels (`y`) and splits them into training (70%) and testing (30%) sets using `train_test_split`, ensuring a consistent split via `random_state`. ```python # Load Iris dataset iris = load_iris() # Split dataset into train and test data x = iris["data"] # features y = iris["target"] x_train, x_test, y_train, y_test = train_test_split( x, y, test_size=0.3, random_state=1 ) ``` -------------------------------- ### Displaying Normalized Confusion Matrix Plot - Python Source: https://github.com/thealgorithms/python/blob/master/machine_learning/gaussian_naive_bayes.py.broken.txt Generates and displays a normalized confusion matrix plot for the model's performance on the test set. It uses `plot_confusion_matrix`, requiring the trained model, test features, test labels, and target class names. The plot is titled and shown using matplotlib. ```python # Display Confusion Matrix plot_confusion_matrix( nb_model, x_test, y_test, display_labels=iris["target_names"], cmap="Blues", # although, Greys_r has a better contrast... normalize="true", ) plt.title("Normalized Confusion Matrix - IRIS Dataset") plt.show() ``` -------------------------------- ### Plotting Confusion Matrix - Matplotlib/Scikit-learn Source: https://github.com/thealgorithms/python/blob/master/machine_learning/random_forest_classifier.py.broken.txt Generates and displays a normalized confusion matrix using `plot_confusion_matrix` from scikit-learn, evaluating the trained `rand_for` model on the test data (`x_test`, `y_test`). The matrix is labeled with Iris target names, styled with a 'Blues' colormap, and shown using `matplotlib.pyplot.show()`. ```Python # Display Confusion Matrix of Classifier plot_confusion_matrix( rand_for, x_test, y_test, display_labels=iris["target_names"], cmap="Blues", normalize="true", ) plt.title("Normalized Confusion Matrix - IRIS Dataset") plt.show() ``` -------------------------------- ### Executing Deutsch-Jozsa Algorithm and Getting Results - Qiskit Python Source: https://github.com/thealgorithms/python/blob/master/quantum/deutsch_jozsa.py.DISABLED.txt This is the main function to run the Deutsch-Jozsa algorithm simulation. It calls the helper functions to create the oracle and the complete circuit. It uses Qiskit's Aer simulator to execute the circuit 1000 times (shots). The function returns the measurement counts from the simulation. According to the Deutsch-Jozsa algorithm, a 'constant' function will result in counts for '000...0', while a 'balanced' function will result in counts for '111...1' (for n qubits). ```Python def deutsch_jozsa(case: str, num_qubits: int) -> qiskit.result.counts.Counts: """ Main function that builds the circuit using other helper functions, runs the experiment 1000 times & returns the resultant qubit counts >>> deutsch_jozsa("constant", 3) {'000': 1000} >>> deutsch_jozsa("balanced", 3) {'111': 1000} """ # Use Aer's simulator simulator = qiskit.Aer.get_backend("aer_simulator") oracle_gate = dj_oracle(case, num_qubits) dj_circuit = dj_algorithm(oracle_gate, num_qubits) # Execute the circuit on the simulator job = qiskit.execute(dj_circuit, simulator, shots=1000) # Return the histogram data of the results of the experiment. return job.result().get_counts(dj_circuit) ``` -------------------------------- ### Project Euler Solution File Template Python Source: https://github.com/thealgorithms/python/blob/master/project_euler/README.md This snippet provides a complete template for a Project Euler solution file in Python. It includes placeholders for the module-level docstring (with problem link, description, and optional references), import statements, helper functions, the main `solution` function, and an `if __name__ == "__main__"` block for execution. ```python """ Project Euler Problem [problem number]: [link to the original problem] ... [Entire problem statement] ... ... [Solution explanation - Optional] ... References [Optional]: - [Wikipedia link to the topic] - [Stackoverflow link] ... """ import module1 import module2 ... def helper1(arg1: [type hint], arg2: [type hint], ...) -> [Return type hint]: """ A brief statement explaining what the function is about. ... A more elaborate description ... [Optional] ... [Doctest] ... """ ... # calculations ... return # You can have multiple helper functions but the solution function should be # after all the helper functions ... def solution(arg1: [type hint], arg2: [type hint], ...) -> [Return type hint]: """ A brief statement mentioning what the function is about. You can have a detailed explanation about the solution in the module-level docstring. ... [Doctest as mentioned above] ... """ ... # calculations ... return answer if __name__ == "__main__": print(f"{solution() = }") ``` -------------------------------- ### Running Quantum Teleportation Simulation in Python Source: https://github.com/thealgorithms/python/blob/master/quantum/quantum_teleportation.py.DISABLED.txt This standard Python entry point block executes the `quantum_teleportation` function when the script is run directly. It calls the function with default parameters and prints the resulting dictionary of measurement counts to the console, showing the simulated outcome of the teleportation process. ```Python if __name__ == "__main__": print( "Total count for teleported state is: " f"{quantum_teleportation(np.pi/2, np.pi/2, np.pi/2)}" ) ``` -------------------------------- ### Demonstrating ProjectQ Random Bit Generation Python Source: https://github.com/thealgorithms/python/blob/master/quantum/quantum_random.py.DISABLED.txt This block demonstrates the usage of the `get_random_number` function. It first runs the built-in doctests defined in the file. Then, it initializes a ProjectQ quantum engine, generates a list containing 10 random bits by repeatedly calling the `get_random_number` function, flushes the quantum engine to execute queued operations, and finally prints the resulting list of random numbers. ```python if __name__ == "__main__": doctest.testmod() # initialises a new quantum backend quantum_engine = projectq.MainEngine() # Generate a list of 10 random numbers random_numbers_list = [get_random_number(quantum_engine) for _ in range(10)] # Flushes the quantum engine from memory quantum_engine.flush() print("Random numbers", random_numbers_list) ``` -------------------------------- ### Running Pre-commit Manually (Bash) Source: https://github.com/thealgorithms/python/blob/master/CONTRIBUTING.md This command executes all configured pre-commit hooks on all files in the repository manually, showing diffs for any suggested changes. ```Bash pre-commit run --all-files --show-diff-on-failure ``` -------------------------------- ### Defining Project Euler Solution Function with Doctests Python Source: https://github.com/thealgorithms/python/blob/master/project_euler/README.md This snippet shows the required structure for the main `solution` function in a Project Euler solution file. It includes type hinting for parameters and return type, a brief docstring, and placeholders for doctests demonstrating how to test the function with various inputs. ```python def solution(limit: int = 1000): """ A brief statement mentioning what the function is about. You can have a detailed explanation about the solution method in the module-level docstring. >>> solution(1) ... >>> solution(16) ... >>> solution(100) ... """ ``` -------------------------------- ### Running Quantum Simulation Script with Qiskit Python Source: https://github.com/thealgorithms/python/blob/master/quantum/single_qubit_measure.py.DISABLED.txt This block serves as the entry point for the script when executed directly. It calls the `single_qubit_measure` function with one quantum bit and one classical bit, and then prints the returned dictionary of state counts, prefixed with an explanatory message. Requires the `single_qubit_measure` function and the `qiskit` library implicitly used by it. ```python if __name__ == "__main__": print(f"Total count for various states are: {single_qubit_measure(1, 1)}") ``` -------------------------------- ### Calculating and Printing Model Accuracy - Python Source: https://github.com/thealgorithms/python/blob/master/machine_learning/gaussian_naive_bayes.py.broken.txt Calculates the overall accuracy of the model's predictions by comparing the true test labels (`y_test`) against the predicted labels (`y_pred`) using `accuracy_score`. The accuracy is converted to a percentage, rounded to two decimal places, and printed to the console. ```python time.sleep(1.8) final_accuracy = 100 * accuracy_score(y_true=y_test, y_pred=y_pred) print(f"The overall accuracy of the model is: {round(final_accuracy, 2)}%") ``` -------------------------------- ### Simulating Quantum Circuit Measurement with Qiskit Python Source: https://github.com/thealgorithms/python/blob/master/quantum/single_qubit_measure.py.DISABLED.txt This function simulates a basic quantum circuit using Qiskit's Aer simulator. It initializes a circuit with specified quantum and classical bits, measures the first qubit onto the first classical bit, executes the circuit 1000 times on the simulator, and returns a dictionary containing the counts of observed states. Requires the `qiskit` library. Takes the number of quantum and classical bits as input and returns a dictionary of measurement counts. ```python def single_qubit_measure( qubits: int, classical_bits: int ) -> qiskit.result.counts.Counts: """ >>> single_qubit_measure(1, 1) {'0': 1000} """ # Use Aer's simulator simulator = qiskit.Aer.get_backend("aer_simulator") # Create a Quantum Circuit acting on the q register circuit = qiskit.QuantumCircuit(qubits, classical_bits) # Map the quantum measurement to the classical bits circuit.measure([0], [0]) # Execute the circuit on the simulator job = qiskit.execute(circuit, simulator, shots=1000) # Return the histogram data of the results of the experiment. return job.result().get_counts(circuit) ``` -------------------------------- ### Executing Qiskit Simulation and Printing Results Python Source: https://github.com/thealgorithms/python/blob/master/quantum/not_gate.py.DISABLED.txt This block serves as the main entry point of the script. It calls the `single_qubit_measure` function with 2 qubits and 2 classical bits to run the quantum simulation and then prints the dictionary containing the total counts of the observed states. ```python if __name__ == "__main__": counts = single_qubit_measure(2, 2) print(f"Total count for various states are: {counts}") ``` -------------------------------- ### Initializing Quantum State with Classical Integers - Python/Qiskit Source: https://github.com/thealgorithms/python/blob/master/quantum/ripple_adder_classic.py.DISABLED.txt This function prepares a quantum circuit to represent two classical integers. It converts integers to padded binary strings, allocates qubits (3x max bits + 1) and classical registers (max bits + 1), and applies X gates to flip qubits where the corresponding bit in the classical number is 1. It returns the initialized circuit and the padded binary strings. Requires the `qiskit` library. ```python import qiskit from qiskit.providers import Backend def store_two_classics(val1: int, val2: int) -> tuple[qiskit.QuantumCircuit, str, str]: """ Generates a Quantum Circuit which stores two classical integers Returns the circuit and binary representation of the integers """ x, y = bin(val1)[2:], bin(val2)[2:] # Remove leading '0b' # Ensure that both strings are of the same length if len(x) > len(y): y = y.zfill(len(x)) else: x = x.zfill(len(y)) # We need (3 * number of bits in the larger number)+1 qBits # The second parameter is the number of classical registers, to measure the result circuit = qiskit.QuantumCircuit((len(x) * 3) + 1, len(x) + 1) # We are essentially "not-ing" the bits that are 1 # Reversed because it's easier to perform ops on more significant bits for i in range(len(x)): if x[::-1][i] == "1": circuit.x(i) for j in range(len(y)): if y[::-1][j] == "1": circuit.x(len(x) + j) return circuit, x, y ``` -------------------------------- ### Handling Whitespace in Python Input (Python) Source: https://github.com/thealgorithms/python/blob/master/CONTRIBUTING.md Shows the recommended way to process input from the user using `input()` by calling `.strip()` to remove leading/trailing whitespace before parsing. ```Python starting_value = int(input("Please enter a starting value: ").strip()) ``` -------------------------------- ### Implementing a Quantum Half Adder using Qiskit Source: https://github.com/thealgorithms/python/blob/master/quantum/half_adder.py.DISABLED.txt This function constructs and simulates a quantum half-adder circuit for two classical bits. It initializes qubits, applies X gates based on input bits, uses CNOT for the sum (XOR) and Toffoli (CCX) for the carry (AND), measures the results, and runs the simulation 1000 times on Qiskit's Aer simulator. ```python def half_adder(bit0: int, bit1: int) -> qiskit.result.counts.Counts: """ >>> half_adder(0, 0) {'00': 1000} >>> half_adder(0, 1) {'01': 1000} >>> half_adder(1, 0) {'01': 1000} >>> half_adder(1, 1) {'10': 1000} """ # Use Aer's simulator simulator = qiskit.Aer.get_backend("aer_simulator") qc_ha = qiskit.QuantumCircuit(4, 2) # encode inputs in qubits 0 and 1 if bit0 == 1: qc_ha.x(0) if bit1 == 1: qc_ha.x(1) qc_ha.barrier() # use cnots to write XOR of the inputs on qubit2 qc_ha.cx(0, 2) qc_ha.cx(1, 2) # use ccx / toffoli gate to write AND of the inputs on qubit3 qc_ha.ccx(0, 1, 3) qc_ha.barrier() # extract outputs qc_ha.measure(2, 0) # extract XOR value qc_ha.measure(3, 1) # extract AND value # Execute the circuit on the qasm simulator job = qiskit.execute(qc_ha, simulator, shots=1000) # Return the histogram data of the results of the experiment return job.result().get_counts(qc_ha) ``` -------------------------------- ### Running Python Doctests Locally (Bash) Source: https://github.com/thealgorithms/python/blob/master/CONTRIBUTING.md Command to execute the doctests embedded in the docstrings of a specific Python file using the built-in `doctest` module with verbose output. ```Bash python3 -m doctest -v my_submission.py ``` -------------------------------- ### Initializing Gradient Boosting Regressor Python Source: https://github.com/thealgorithms/python/blob/master/machine_learning/gradient_boosting_regressor.py.broken.txt Initializes the GradientBoostingRegressor model with specific hyperparameters. Key parameters include the number of boosting stages (`n_estimators`), the maximum depth of individual trees (`max_depth`), the minimum number of samples required to split an internal node (`min_samples_split`), and the step size shrinkage used in updating the weights (`learning_rate`). ```python model = GradientBoostingRegressor( n_estimators=500, max_depth=5, min_samples_split=4, learning_rate=0.01 ) ``` -------------------------------- ### Building and Simulating Quantum Full Adder - Qiskit Python Source: https://github.com/thealgorithms/python/blob/master/quantum/q_full_adder.py.DISABLED.txt This function constructs and simulates a 4-qubit quantum full adder circuit using Qiskit. It initializes qubits based on integer inputs (0, 1, or 2 for superposition), applies necessary quantum gates (CCX, CX, X, H, I), measures the sum and carry qubits, and runs the circuit on an Aer simulator for 1000 shots. It returns the measurement counts. ```Python import math import qiskit def quantum_full_adder( input_1: int = 1, input_2: int = 1, carry_in: int = 1 ) -> qiskit.result.counts.Counts: """ # >>> q_full_adder(inp_1, inp_2, cin) # the inputs can be 0/1 for qubits in define # values, or can be in a superposition of both # states with hadamard gate using the input value 2. # result for default values: {11: 1000} qr_0: ──■────■──────────────■── │ ┌─┴─┐ ┌─┴─┐ qr_1: ──■──┤ X ├──■────■──┤ X ├ │ └───┘ │ ┌─┴─┐└───┘ qr_2: ──┼─────────■──┤ X ├───── ┌─┴─┐ ┌─┴─┐└───┘ qr_3: ┤ X ├─────┤ X ├────────── └───┘ └───┘ cr: 2/═════════════════════════ Args: input_1: input 1 for the circuit. input_2: input 2 for the circuit. carry_in: carry in for the circuit. Returns: qiskit.result.counts.Counts: sum result counts. >>> quantum_full_adder(1, 1, 1) {'11': 1000} >>> quantum_full_adder(0, 0, 1) {'01': 1000} >>> quantum_full_adder(1, 0, 1) {'10': 1000} >>> quantum_full_adder(1, -4, 1) Traceback (most recent call last): ... ValueError: inputs must be positive. >>> quantum_full_adder('q', 0, 1) Traceback (most recent call last): ... TypeError: inputs must be integers. >>> quantum_full_adder(0.5, 0, 1) Traceback (most recent call last): ... ValueError: inputs must be exact integers. >>> quantum_full_adder(0, 1, 3) Traceback (most recent call last): ... ValueError: inputs must be less or equal to 2. """ if ( isinstance(input_1, str) or isinstance(input_2, str) or isinstance(carry_in, str) ): raise TypeError("inputs must be integers.") if (input_1 < 0) or (input_2 < 0) or (carry_in < 0): raise ValueError("inputs must be positive.") if ( (math.floor(input_1) != input_1) or (math.floor(input_2) != input_2) or (math.floor(carry_in) != carry_in) ): raise ValueError("inputs must be exact integers.") if (input_1 > 2) or (input_2 > 2) or (carry_in > 2): raise ValueError("inputs must be less or equal to 2.") # build registers qr = qiskit.QuantumRegister(4, "qr") cr = qiskit.ClassicalRegister(2, "cr") # list the entries entry = [input_1, input_2, carry_in] quantum_circuit = qiskit.QuantumCircuit(qr, cr) for i in range(3): if entry[i] == 2: quantum_circuit.h(i) # for hadamard entries elif entry[i] == 1: quantum_circuit.x(i) # for 1 entries elif entry[i] == 0: quantum_circuit.i(i) # for 0 entries # build the circuit quantum_circuit.ccx(0, 1, 3) # ccx = toffoli gate quantum_circuit.cx(0, 1) quantum_circuit.ccx(1, 2, 3) quantum_circuit.cx(1, 2) quantum_circuit.cx(0, 1) quantum_circuit.measure([2, 3], cr) # measure the last two qbits backend = qiskit.Aer.get_backend("aer_simulator") job = qiskit.execute(quantum_circuit, backend, shots=1000) return job.result().get_counts(quantum_circuit) ``` -------------------------------- ### Defining Qiskit Simulation Function Python Source: https://github.com/thealgorithms/python/blob/master/quantum/not_gate.py.DISABLED.txt Defines a function to build and simulate a quantum circuit using Qiskit's Aer simulator. It initializes a circuit with specified qubits and classical bits, applies X gates to the first two qubits, measures them onto corresponding classical bits, executes the circuit for 1000 shots, and returns the resulting state counts. ```python import qiskit def single_qubit_measure( qubits: int, classical_bits: int ) -> qiskit.result.counts.Counts: """ >>> single_qubit_measure(2, 2) {'11': 1000} >>> single_qubit_measure(4, 4) {'0011': 1000} """ # Use Aer's simulator simulator = qiskit.Aer.get_backend("aer_simulator") # Create a Quantum Circuit acting on the q register circuit = qiskit.QuantumCircuit(qubits, classical_bits) # Apply X (NOT) Gate to Qubits 0 & 1 circuit.x(0) circuit.x(1) # Map the quantum measurement to the classical bits circuit.measure([0, 1], [0, 1]) # Execute the circuit on the qasm simulator job = qiskit.execute(circuit, simulator, shots=1000) # Return the histogram data of the results of the experiment. return job.result().get_counts(circuit) ``` -------------------------------- ### Importing Libraries and Loading Data (Python) Source: https://github.com/thealgorithms/python/blob/master/audio_filters/equal_loudness_filter.py.broken.txt This snippet imports necessary Python libraries and modules, including standard ones like `json` and `pathlib`, numerical processing with `numpy`, a custom `yulewalker` library, and local audio filter components. It then loads audio loudness curve data from a JSON file located relative to the script's path. ```Python from json import loads from pathlib import Path import numpy as np from yulewalker import yulewalk from audio_filters.butterworth_filter import make_highpass from audio_filters.iir_filter import IIRFilter data = loads((Path(__file__).resolve().parent / "loudness_curve.json").read_text()) ``` -------------------------------- ### Performing BB84 Protocol Simulation with Qiskit - Python Source: https://github.com/thealgorithms/python/blob/master/quantum/bb84.py.DISABLED.txt This function simulates the BB84 quantum key distribution protocol between Alice and Bob. It generates random bases and states, constructs a quantum circuit using Qiskit, simulates the circuit, and extracts the shared key by comparing Alice's preparation bases with Bob's measurement bases and keeping only the bits where they matched. ```python def bb84(key_len: int = 8, seed: int | None = None) -> str: """ Performs the BB84 protocol using a key made of `key_len` bits. The two parties in the key distribution are called Alice and Bob. Args: key_len: The length of the generated key in bits. The default is 8. seed: Seed for the random number generator. Mostly used for testing. Default is None. Returns: key: The key generated using BB84 protocol. >>> bb84(16, seed=0) '0111110111010010' >>> bb84(8, seed=0) '10110001' """ # Set up the random number generator. rng = np.random.default_rng(seed=seed) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. num_qubits = 6 * key_len # Measurement basis for Alice's qubits. alice_basis = rng.integers(2, size=num_qubits) # The set of states Alice will prepare. alice_state = rng.integers(2, size=num_qubits) # Measurement basis for Bob's qubits. bob_basis = rng.integers(2, size=num_qubits) # Quantum Circuit to simulate BB84 bb84_circ = qiskit.QuantumCircuit(num_qubits, name="BB84") # Alice prepares her qubits according to rules above. for index, _ in enumerate(alice_basis): if alice_state[index] == 1: bb84_circ.x(index) if alice_basis[index] == 1: bb84_circ.h(index) bb84_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(bob_basis): if bob_basis[index] == 1: bb84_circ.h(index) bb84_circ.barrier() bb84_circ.measure_all() # Simulate the quantum circuit. sim = qiskit.Aer.get_backend("aer_simulator") # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. job = qiskit.execute(bb84_circ, sim, shots=1, seed_simulator=seed) # Returns the result of measurement. result = job.result().get_counts(bb84_circ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. gen_key = "".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( alice_basis, bob_basis, result ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. key = gen_key[:key_len] if len(gen_key) >= key_len else gen_key.ljust(key_len, "0") return key ``` -------------------------------- ### Running Mypy on All Python Files (Bash) Source: https://github.com/thealgorithms/python/blob/master/CONTRIBUTING.md Command to run the Mypy static type checker on all Python files in the current directory and its subdirectories, configured to ignore missing import errors. ```Bash mypy --ignore-missing-imports . ``` -------------------------------- ### Generating Random Bit using ProjectQ Python Source: https://github.com/thealgorithms/python/blob/master/quantum/quantum_random.py.DISABLED.txt Generates a single random bit (0 or 1) using a quantum engine provided by ProjectQ. It allocates a qubit, applies a Hadamard gate to place it in a superposition state (equal probability of 0 or 1), measures the qubit collapsing its state, and returns the integer outcome (0 or 1). Requires an initialized ProjectQ MainEngine instance. ```python def get_random_number(quantum_engine: projectq.cengines._main.MainEngine) -> int: """ >>> isinstance(get_random_number(projectq.MainEngine()), int) True """ qubit = quantum_engine.allocate_qubit() H | qubit Measure | qubit return int(qubit) ``` -------------------------------- ### Executing Quantum Entanglement Simulation with Qiskit (Python) Source: https://github.com/thealgorithms/python/blob/master/quantum/quantum_entanglement.py.DISABLED.txt This block demonstrates how to execute the `quantum_entanglement` function when the script is run directly. It calls the function with 3 qubits and prints the resulting state counts obtained from the simulation. ```python if __name__ == "__main__": print(f"Total count for various states are: {quantum_entanglement(3)}") ``` -------------------------------- ### Building Complete Deutsch-Jozsa Quantum Circuit - Qiskit Python Source: https://github.com/thealgorithms/python/blob/master/quantum/deutsch_jozsa.py.DISABLED.txt This function constructs the full Deutsch-Jozsa quantum circuit. It takes the pre-built oracle gate and the number of qubits as input. It initializes the circuit with input and output registers, applies Hadamard gates to the input qubits and the output qubit (after an initial X-gate), appends the oracle gate, applies final Hadamard gates to the input qubits, and sets up measurements for the input register. It returns the complete Qiskit QuantumCircuit object. ```Python def dj_algorithm( oracle: qiskit.QuantumCircuit, num_qubits: int ) -> qiskit.QuantumCircuit: """ Returns the complete Deutsch-Jozsa Quantum Circuit, adding Input & Output registers and Hadamard & Measurement Gates, to the Oracle Circuit passed in arguments """ dj_circuit = qiskit.QuantumCircuit(num_qubits + 1, num_qubits) # Set up the output qubit: dj_circuit.x(num_qubits) dj_circuit.h(num_qubits) # And set up the input register: for qubit in range(num_qubits): dj_circuit.h(qubit) # Let's append the oracle gate to our circuit: dj_circuit.append(oracle, range(num_qubits + 1)) # Finally, perform the H-gates again and measure: for qubit in range(num_qubits): dj_circuit.h(qubit) for i in range(num_qubits): dj_circuit.measure(i, i) return dj_circuit ``` -------------------------------- ### Linking GitHub Issues via PR Description (Text) Source: https://github.com/thealgorithms/python/blob/master/CONTRIBUTING.md This snippet shows the syntax to include in a pull request description to automatically close a linked GitHub issue when the PR is merged. ```Text Fixes #10 ``` -------------------------------- ### Running Mypy on Specific Python File (Bash) Source: https://github.com/thealgorithms/python/blob/master/CONTRIBUTING.md Command to run the Mypy static type checker on a single specified Python file, configured to ignore missing import errors. ```Bash mypy --ignore-missing-imports path/to/file.py ``` -------------------------------- ### Setting Up and Plotting Prediction vs. Actual Python Source: https://github.com/thealgorithms/python/blob/master/machine_learning/gradient_boosting_regressor.py.broken.txt Creates a scatter plot to visualize the relationship between the actual target values (`y_test`) and the model's predicted values (`y_pred`). A diagonal line is plotted representing the ideal scenario where predictions exactly match actual values, providing a visual reference for model performance. Axis labels and a title are added. ```python # So let's run the model against the test data fig, ax = plt.subplots() ax.scatter(y_test, y_pred, edgecolors=(0, 0, 0)) ax.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], "k--", lw=4) ax.set_xlabel("Actual") ax.set_ylabel("Predicted") ax.set_title("Truth vs Predicted") ``` -------------------------------- ### Loading and Preprocessing Boston Dataset Python Source: https://github.com/thealgorithms/python/blob/master/machine_learning/gradient_boosting_regressor.py.broken.txt Loads the Boston housing dataset directly from scikit-learn and converts it into a pandas DataFrame for easier manipulation. The target variable (Price) is added as a new column, and the head and descriptive statistics are printed to inspect the data structure and characteristics. ```python # loading the dataset from the sklearn df = load_boston() print(df.keys()) # now let construct a data frame df_boston = pd.DataFrame(df.data, columns=df.feature_names) # let add the target to the dataframe df_boston["Price"] = df.target # print the first five rows using the head function print(df_boston.head()) # Summary statistics print(df_boston.describe().T) ``` -------------------------------- ### Building Quantum Entanglement Circuit with Qiskit (Python) Source: https://github.com/thealgorithms/python/blob/master/quantum/quantum_entanglement.py.DISABLED.txt This function creates a quantum circuit to entangle a specified number of qubits using Qiskit. It initializes the circuit, applies a Hadamard gate to the first qubit, and then applies sequential CNOT gates to entangle the subsequent qubits. Finally, it measures all qubits and simulates the circuit execution using the 'aer_simulator' backend. ```python import qiskit def quantum_entanglement(qubits: int = 2) -> qiskit.result.counts.Counts: """ # >>> quantum_entanglement(2) # {'00': 500, '11': 500} # ┌───┐ ┌─┐ # q_0: ┤ H ├──■──┤M├─── # └───┘┌─┴─┐└╥┘┌─┐ # q_1: ─────┤ X ├─╫─┤M├ # └───┘ ║ └╥┘ # c: 2/═══════════╩══╩═ # 0 1 Args: qubits (int): number of quibits to use. Defaults to 2 Returns: qiskit.result.counts.Counts: mapping of states to its counts """ classical_bits = qubits # Using Aer's simulator simulator = qiskit.Aer.get_backend("aer_simulator") # Creating a Quantum Circuit acting on the q register circuit = qiskit.QuantumCircuit(qubits, classical_bits) # Adding a H gate on qubit 0 (now q0 in superposition) circuit.h(0) for i in range(1, qubits): # Adding CX (CNOT) gate circuit.cx(i - 1, i) # Mapping the quantum measurement to the classical bits circuit.measure(list(range(qubits)), list(range(classical_bits))) # Now measuring any one qubit would affect other qubits to collapse # their super position and have same state as the measured one. # Executing the circuit on the simulator job = qiskit.execute(circuit, simulator, shots=1000) return job.result().get_counts(circuit) ```