repo_name
stringclasses
25 values
repo_full_name
stringclasses
25 values
owner
stringclasses
25 values
stars
int64
117k
496k
license
stringclasses
7 values
repo_description
stringclasses
25 values
filepath
stringlengths
9
75
file_type
stringclasses
3 values
language
stringclasses
2 values
content
stringlengths
24
383k
size_bytes
int64
25
387k
num_lines
int64
2
4.44k
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\morse_code.py
python
Python
#!/usr/bin/env python3 """ Python program to translate to and from Morse code. https://en.wikipedia.org/wiki/Morse_code """ # fmt: off MORSE_CODE_DICT = { "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--...
1,771
59
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\onepad_cipher.py
python
Python
import random class Onepad: @staticmethod def encrypt(text: str) -> tuple[list[int], list[int]]: """ Function to encrypt text using pseudo-random numbers >>> Onepad().encrypt("") ([], []) >>> Onepad().encrypt([]) ([], []) >>> random.seed(1) >>> O...
1,919
65
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\permutation_cipher.py
python
Python
""" The permutation cipher, also called the transposition cipher, is a simple encryption technique that rearranges the characters in a message based on a secret key. It divides the message into blocks and applies a permutation to the characters within each block according to the key. The key is a sequence of unique int...
4,201
144
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\playfair_cipher.py
python
Python
""" https://en.wikipedia.org/wiki/Playfair_cipher#Description The Playfair cipher was developed by Charles Wheatstone in 1854 It's use was heavily promotedby Lord Playfair, hence its name Some features of the Playfair cipher are: 1) It was the first literal diagram substitution cipher 2) It is a manual symmetric enc...
4,665
160
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\polybius.py
python
Python
#!/usr/bin/env python3 """ A Polybius Square is a table that allows someone to translate letters into numbers. https://www.braingle.com/brainteasers/codes/polybius.php """ import numpy as np SQUARE = [ ["a", "b", "c", "d", "e"], ["f", "g", "h", "i", "k"], ["l", "m", "n", "o", "p"], ["q", "r", "s", "...
3,180
97
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\porta_cipher.py
python
Python
alphabet = { "A": ("ABCDEFGHIJKLM", "NOPQRSTUVWXYZ"), "B": ("ABCDEFGHIJKLM", "NOPQRSTUVWXYZ"), "C": ("ABCDEFGHIJKLM", "ZNOPQRSTUVWXY"), "D": ("ABCDEFGHIJKLM", "ZNOPQRSTUVWXY"), "E": ("ABCDEFGHIJKLM", "YZNOPQRSTUVWX"), "F": ("ABCDEFGHIJKLM", "YZNOPQRSTUVWX"), "G": ("ABCDEFGHIJKLM", "XYZNOPQRS...
3,255
104
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\rabin_miller.py
python
Python
# Primality Testing with the Rabin-Miller Algorithm import random def rabin_miller(num: int) -> bool: s = num - 1 t = 0 while s % 2 == 0: s = s // 2 t += 1 for _ in range(5): a = random.randrange(2, num - 1) v = pow(a, s, num) if v != 1: i = 0 ...
3,514
224
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\rail_fence_cipher.py
python
Python
"""https://en.wikipedia.org/wiki/Rail_fence_cipher""" def encrypt(input_string: str, key: int) -> str: """ Shuffles the character of a string by placing each of them in a grid (the height is dependent on the key) in a zigzag formation and reading it left to right. >>> encrypt("Hello World", 4) ...
3,162
103
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\README.md
readme
Markdown
# Ciphers Ciphers are used to protect data from people that are not allowed to have it. They are everywhere on the internet to protect your connections. * <https://en.wikipedia.org/wiki/Cipher> * <http://practicalcryptography.com/ciphers/> * <https://practicalcryptography.com/ciphers/classical-era/>
310
8
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\rot13.py
python
Python
def dencrypt(s: str, n: int = 13) -> str: """ https://en.wikipedia.org/wiki/ROT13 >>> msg = "My secret bank account number is 173-52946 so don't tell anyone!!" >>> s = dencrypt(msg) >>> s "Zl frperg onax nppbhag ahzore vf 173-52946 fb qba'g gryy nalbar!!" >>> dencrypt(s) == msg True ...
878
38
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\rsa_cipher.py
python
Python
import os import sys from . import rsa_key_generator as rkg DEFAULT_BLOCK_SIZE = 128 BYTE_SIZE = 256 def get_blocks_from_text( message: str, block_size: int = DEFAULT_BLOCK_SIZE ) -> list[int]: message_bytes = message.encode("ascii") block_ints = [] for block_start in range(0, len(message_bytes), b...
5,022
150
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\rsa_factorization.py
python
Python
""" An RSA prime factor algorithm. The program can efficiently factor RSA prime number given the private key d and public key e. | Source: on page ``3`` of https://crypto.stanford.edu/~dabo/papers/RSA-survey.pdf | More readable source: https://www.di-mgt.com.au/rsa_factorize_n.html large number can take minutes to f...
1,696
62
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\rsa_key_generator.py
python
Python
import os import random import sys from maths.greatest_common_divisor import gcd_by_iterative from . import cryptomath_module, rabin_miller def main() -> None: print("Making key files...") make_key_files("rsa", 1024) print("Key files generation successful.") def generate_key(key_size: int) -> tuple[tu...
1,982
64
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\running_key_cipher.py
python
Python
""" https://en.wikipedia.org/wiki/Running_key_cipher """ def running_key_encrypt(key: str, plaintext: str) -> str: """ Encrypts the plaintext using the Running Key Cipher. :param key: The running key (long piece of text). :param plaintext: The plaintext to be encrypted. :return: The ciphertext. ...
2,098
76
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\shuffled_shift_cipher.py
python
Python
from __future__ import annotations import random import string class ShuffledShiftCipher: """ This algorithm uses the Caesar Cipher algorithm but removes the option to use brute force to decrypt the message. The passcode is a random password from the selection buffer of 1. uppercase letters of t...
6,922
185
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\simple_keyword_cypher.py
python
Python
def remove_duplicates(key: str) -> str: """ Removes duplicate alphabetic characters in a keyword (letter is ignored after its first appearance). :param key: Keyword to use :return: String with duplicates removed >>> remove_duplicates('Hello World!!') 'Helo Wrd' """ key_no_dups = "...
2,943
99
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\simple_substitution_cipher.py
python
Python
import random import sys LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def main() -> None: message = input("Enter message: ") key = "LFWOAYUISVKMNXPBDCRJTQEGHZ" resp = input("Encrypt/Decrypt [e/d]: ") check_valid_key(key) if resp.lower().startswith("e"): mode = "encrypt" translated = e...
1,947
79
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\transposition_cipher.py
python
Python
import math """ In cryptography, the TRANSPOSITION cipher is a method of encryption where the positions of plaintext are shifted a certain number(determined by the key) that follows a regular system that results in the permuted text, known as the encrypted text. The type of transposition cipher demonstrated under is t...
1,883
69
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\transposition_cipher_encrypt_decrypt_file.py
python
Python
import os import sys import time from . import transposition_cipher as trans_cipher def main() -> None: input_file = "./prehistoric_men.txt" output_file = "./Output.txt" key = int(input("Enter key: ")) mode = input("Encrypt/Decrypt [e/d]: ") if not os.path.exists(input_file): print(f"Fil...
1,207
42
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\trifid_cipher.py
python
Python
""" The trifid cipher uses a table to fractionate each plaintext letter into a trigram, mixes the constituents of the trigrams, and then applies the table in reverse to turn these mixed trigrams into ciphertext letters. https://en.wikipedia.org/wiki/Trifid_cipher """ from __future__ import annotations # fmt: off TES...
7,022
216
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\vernam_cipher.py
python
Python
def vernam_encrypt(plaintext: str, key: str) -> str: """ >>> vernam_encrypt("HELLO","KEY") 'RIJVS' """ ciphertext = "" for i in range(len(plaintext)): ct = ord(key[i % len(key)]) - 65 + ord(plaintext[i]) - 65 while ct > 25: ct = ct - 26 ciphertext += chr(65 + ...
1,119
43
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\vigenere_cipher.py
python
Python
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def main() -> None: message = input("Enter message: ") key = input("Enter key [alphanumeric]: ") mode = input("Encrypt/Decrypt [e/d]: ") if mode.lower().startswith("e"): mode = "encrypt" translated = encrypt_message(key, message) elif mode.lo...
1,846
66
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\xor_cipher.py
python
Python
""" author: Christian Bender date: 21.12.2017 class: XORCipher This class implements the XOR-cipher algorithm and provides some useful methods for encrypting and decrypting strings and files. Overview about methods - encrypt : list of char - decrypt : list of char - encrypt_string : str - decrypt_string : str - encr...
7,196
269
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
computer_vision\cnn_classification.py
python
Python
""" Convolutional Neural Network Objective : To train a CNN model detect if TB is present in Lung X-ray or not. Resources CNN Theory : https://en.wikipedia.org/wiki/Convolutional_neural_network Resources Tensorflow : https://www.tensorflow.org/tutorials/images/cnn Download dataset from : https://lhncbc.nlm.nih.g...
3,281
101
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
computer_vision\flip_augmentation.py
python
Python
import glob import os import random from string import ascii_lowercase, digits import cv2 """ Flip image and bounding box for computer vision task https://paperswithcode.com/method/randomhorizontalflip """ # Params LABEL_DIR = "" IMAGE_DIR = "" OUTPUT_DIR = "" FLIP_TYPE = 1 # (0 is vertical, 1 is horizontal) def ...
4,454
129
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
computer_vision\haralick_descriptors.py
python
Python
""" https://en.wikipedia.org/wiki/Image_texture https://en.wikipedia.org/wiki/Co-occurrence_matrix#Application_to_image_analysis """ import imageio.v2 as imageio import numpy as np def root_mean_square_error(original: np.ndarray, reference: np.ndarray) -> float: """Simple implementation of Root Mean Squared Erro...
15,817
435
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
computer_vision\harris_corner.py
python
Python
import cv2 import numpy as np """ Harris Corner Detector https://en.wikipedia.org/wiki/Harris_Corner_Detector """ class HarrisCorner: def __init__(self, k: float, window_size: int): """ k : is an empirically determined constant in [0.04,0.06] window_size : neighbourhoods considered ...
2,280
72
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
computer_vision\horn_schunck.py
python
Python
""" The Horn-Schunck method estimates the optical flow for every single pixel of a sequence of images. It works by assuming brightness constancy between two consecutive frames and smoothness in the optical flow. Useful resources: Wikipedia: https://en.wikipedia.org/wiki/Horn%E2%80%93Schunck_method Paper: http://image....
4,424
132
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
computer_vision\intensity_based_segmentation.py
python
Python
# Source: "https://www.ijcse.com/docs/IJCSE11-02-03-117.pdf" # Importing necessary libraries import matplotlib.pyplot as plt import numpy as np from PIL import Image def segment_image(image: np.ndarray, thresholds: list[int]) -> np.ndarray: """ Performs image segmentation based on intensity thresholds. ...
1,767
63
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
computer_vision\mean_threshold.py
python
Python
from PIL import Image """ Mean thresholding algorithm for image processing https://en.wikipedia.org/wiki/Thresholding_(image_processing) """ def mean_threshold(image: Image) -> Image: """ image: is a grayscale PIL image object """ height, width = image.size mean = 0 pixels = image.load() ...
764
31
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
computer_vision\mosaic_augmentation.py
python
Python
"""Source: https://github.com/jason9075/opencv-mosaic-data-aug""" import glob import os import random from string import ascii_lowercase, digits import cv2 import numpy as np # Parameters OUTPUT_SIZE = (720, 1280) # Height, Width SCALE_RANGE = (0.4, 0.6) # if height or width lower than this scale, drop it. FILTER_...
7,256
187
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
computer_vision\pooling_functions.py
python
Python
# Source : https://computersciencewiki.org/index.php/Max-pooling_/_Pooling # Importing the libraries import numpy as np from PIL import Image # Maxpooling Function def maxpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray: """ This function is used to perform maxpooling on the input array of 2D ma...
4,483
136
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
computer_vision\README.md
readme
Markdown
# Computer Vision Computer vision is a field of computer science that works on enabling computers to see, identify and process images in the same way that human does, and provide appropriate output. It is like imparting human intelligence and instincts to a computer. Image processing and computer vision are a little ...
808
11
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\astronomical_length_scale_conversion.py
python
Python
""" Conversion of length units. Available Units: Metre, Kilometre, Megametre, Gigametre, Terametre, Petametre, Exametre, Zettametre, Yottametre USAGE : -> Import this file into their respective project. -> Use the function length_conversion() for conversion of length units. -> Parameters : -> value : The number of...
3,151
107
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\binary_to_decimal.py
python
Python
def bin_to_decimal(bin_string: str) -> int: """ Convert a binary value to its decimal equivalent >>> bin_to_decimal("101") 5 >>> bin_to_decimal(" 1010 ") 10 >>> bin_to_decimal("-11101") -29 >>> bin_to_decimal("0") 0 >>> bin_to_decimal("a") Traceback (most recent call l...
1,320
44
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\binary_to_hexadecimal.py
python
Python
BITS_TO_HEX = { "0000": "0", "0001": "1", "0010": "2", "0011": "3", "0100": "4", "0101": "5", "0110": "6", "0111": "7", "1000": "8", "1001": "9", "1010": "a", "1011": "b", "1100": "c", "1101": "d", "1110": "e", "1111": "f", } def bin_to_hexadecimal(binar...
1,766
67
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\binary_to_octal.py
python
Python
""" The function below will convert any binary string to the octal equivalent. >>> bin_to_octal("1111") '17' >>> bin_to_octal("101010101010011") '52523' >>> bin_to_octal("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function >>> bin_to_octal("a-1") Traceback (most recent c...
1,241
46
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\convert_number_to_words.py
python
Python
from enum import Enum from typing import Literal class NumberingSystem(Enum): SHORT = ( (15, "quadrillion"), (12, "trillion"), (9, "billion"), (6, "million"), (3, "thousand"), (2, "hundred"), ) LONG = ( (15, "billiard"), (9, "milliard"), ...
5,895
206
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\decimal_to_any.py
python
Python
"""Convert a positive Decimal Number to Any Other Representation""" from string import ascii_uppercase ALPHABET_VALUES = {str(ord(c) - 55): c for c in ascii_uppercase} def decimal_to_any(num: int, base: int) -> str: """ Convert a positive integer to another base as str. >>> decimal_to_any(0, 2) '0' ...
3,289
106
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\decimal_to_binary.py
python
Python
"""Convert a Decimal Number to a Binary Number.""" def decimal_to_binary_iterative(num: int) -> str: """ Convert an Integer Decimal Number to a Binary Number as str. >>> decimal_to_binary_iterative(0) '0b0' >>> decimal_to_binary_iterative(2) '0b10' >>> decimal_to_binary_iterative(7) '0...
3,437
110
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\decimal_to_hexadecimal.py
python
Python
"""Convert Base 10 (Decimal) Values to Hexadecimal Representations""" # set decimal value for each hexadecimal digit values = { 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15...
2,040
81
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\decimal_to_octal.py
python
Python
"""Convert a Decimal Number to an Octal Number.""" import math # Modified from: # https://github.com/TheAlgorithms/Javascript/blob/master/Conversions/DecimalToOctal.js def decimal_to_octal(num: int) -> str: """Convert a Decimal Number to an Octal Number. >>> all(decimal_to_octal(i) == oct(i) for i ... ...
1,254
44
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\energy_conversions.py
python
Python
""" Conversion of energy units. Available units: joule, kilojoule, megajoule, gigajoule,\ wattsecond, watthour, kilowatthour, newtonmeter, calorie_nutr,\ kilocalorie_nutr, electronvolt, britishthermalunit_it, footpound USAGE : -> Import this file into their respective project. -> Use the function ener...
4,406
115
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\excel_title_to_column.py
python
Python
def excel_title_to_column(column_title: str) -> int: """ Given a string column_title that represents the column title in an Excel sheet, return its corresponding column number. >>> excel_title_to_column("A") 1 >>> excel_title_to_column("B") 2 >>> excel_title_to_column("AB") 28 ...
744
34
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\hex_to_bin.py
python
Python
def hex_to_bin(hex_num: str) -> int: """ Convert a hexadecimal value to its binary equivalent #https://stackoverflow.com/questions/1425493/convert-hex-to-binary Here, we have used the bitwise right shift operator: >> Shifts the bits of the number to the right and fills 0 on voids left as a result. ...
1,556
57
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\hexadecimal_to_decimal.py
python
Python
hex_table = {hex(i)[2:]: i for i in range(16)} # Use [:2] to strip off the leading '0x' def hex_to_decimal(hex_string: str) -> int: """ Convert a hexadecimal value to its decimal equivalent #https://www.programiz.com/python-programming/methods/built-in/hex >>> hex_to_decimal("a") 10 >>> hex_...
1,570
50
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\ipv4_conversion.py
python
Python
# https://www.geeksforgeeks.org/convert-ip-address-to-integer-and-vice-versa/ def ipv4_to_decimal(ipv4_address: str) -> int: """ Convert an IPv4 address to its decimal representation. Args: ip_address: A string representing an IPv4 address (e.g., "192.168.0.1"). Returns: int: The dec...
2,326
86
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\length_conversion.py
python
Python
""" Conversion of length units. Available Units:- Metre,Kilometre,Feet,Inch,Centimeter,Yard,Foot,Mile,Millimeter USAGE : -> Import this file into their respective project. -> Use the function length_conversion() for conversion of length units. -> Parameters : -> value : The number of from units you want to convert...
4,151
133
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\molecular_chemistry.py
python
Python
""" Functions useful for doing molecular chemistry: * molarity_to_normality * moles_to_pressure * moles_to_volume * pressure_and_volume_to_temperature """ def molarity_to_normality(nfactor: int, moles: float, volume: float) -> float: """ Convert molarity to normality. Volume is taken in litres. W...
2,776
92
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\octal_to_binary.py
python
Python
""" * Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) * Description: Convert a Octal number to Binary. References for better understanding: https://en.wikipedia.org/wiki/Binary_number https://en.wikipedia.org/wiki/Octal """ def octal_to_binary(octal_number: str) -> str: """ Convert an ...
1,492
55
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\octal_to_decimal.py
python
Python
def oct_to_decimal(oct_string: str) -> int: """ Convert a octal value to its decimal equivalent >>> oct_to_decimal("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function >>> oct_to_decimal("-") Traceback (most recent call last): ... ...
2,487
80
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\octal_to_hexadecimal.py
python
Python
def octal_to_hex(octal: str) -> str: """ Convert an Octal number to Hexadecimal number. For more information: https://en.wikipedia.org/wiki/Octal >>> octal_to_hex("100") '0x40' >>> octal_to_hex("235") '0x9D' >>> octal_to_hex(17) Traceback (most recent call last): ... Typ...
1,691
66
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\prefix_conversions.py
python
Python
""" Convert International System of Units (SI) and Binary prefixes """ from __future__ import annotations from enum import Enum class SIUnit(Enum): yotta = 24 zetta = 21 exa = 18 peta = 15 tera = 12 giga = 9 mega = 6 kilo = 3 hecto = 2 deca = 1 deci = -1 centi = -2 ...
2,572
105
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\prefix_conversions_string.py
python
Python
""" * Author: Manuel Di Lullo (https://github.com/manueldilullo) * Description: Convert a number to use the correct SI or Binary unit prefix. Inspired by prefix_conversion.py file in this repository by lance-pyles URL: https://en.wikipedia.org/wiki/Metric_prefix#List_of_SI_prefixes URL: https://en.wikipedia.org/wiki/...
3,302
122
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\pressure_conversions.py
python
Python
""" Conversion of pressure units. Available Units:- Pascal,Bar,Kilopascal,Megapascal,psi(pound per square inch), inHg(in mercury column),torr,atm USAGE : -> Import this file into their respective project. -> Use the function pressure_conversion() for conversion of pressure units. -> Parameters : -> value : The numb...
2,980
88
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\README.md
readme
Markdown
# Conversion Conversion programs convert a type of data, a number from a numerical base or unit into one of another type, base or unit, e.g. binary to decimal, integer to string or foot to meters. * <https://en.wikipedia.org/wiki/Data_conversion> * <https://en.wikipedia.org/wiki/Transcoding>
301
7
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\rectangular_to_polar.py
python
Python
import math def rectangular_to_polar(real: float, img: float) -> tuple[float, float]: """ https://en.wikipedia.org/wiki/Polar_coordinate_system >>> rectangular_to_polar(5,-5) (7.07, -45.0) >>> rectangular_to_polar(-1,1) (1.41, 135.0) >>> rectangular_to_polar(-1,-1) (1.41, -135.0) ...
800
33
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\rgb_cmyk_conversion.py
python
Python
def rgb_to_cmyk(r_input: int, g_input: int, b_input: int) -> tuple[int, int, int, int]: """ Simple RGB to CMYK conversion. Returns percentages of CMYK paint. https://www.programmingalgorithms.com/algorithm/rgb-to-cmyk/ Note: this is a very popular algorithm that converts colors linearly and gives o...
2,073
72
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\rgb_hsv_conversion.py
python
Python
""" The RGB color model is an additive color model in which red, green, and blue light are added together in various ways to reproduce a broad array of colors. The name of the model comes from the initials of the three additive primary colors, red, green, and blue. Meanwhile, the HSV representation models how colors ap...
5,948
160
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\roman_numerals.py
python
Python
ROMAN = [ (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ] def roman_to_int(roman: str) -> int: """ LeetCode No. 13 Roman to Integer Given a roman num...
1,703
62
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\speed_conversions.py
python
Python
""" Convert speed units https://en.wikipedia.org/wiki/Kilometres_per_hour https://en.wikipedia.org/wiki/Miles_per_hour https://en.wikipedia.org/wiki/Knot_(unit) https://en.wikipedia.org/wiki/Metre_per_second """ speed_chart: dict[str, float] = { "km/h": 1.0, "m/s": 3.6, "mph": 1.609344, "knot": 1.852,...
1,841
72
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\temperature_conversions.py
python
Python
"""Convert between different units of temperature""" def celsius_to_fahrenheit(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.w...
12,000
386
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\time_conversions.py
python
Python
""" A unit of time is any particular time interval, used as a standard way of measuring or expressing duration. The base unit of time in the International System of Units (SI), and by extension most of the Western world, is the second, defined as about 9 billion oscillations of the caesium atom. https://en.wikipedia....
3,213
87
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\volume_conversions.py
python
Python
""" Conversion of volume units. Available Units:- Cubic metre,Litre,KiloLitre,Gallon,Cubic yard,Cubic foot,cup USAGE : -> Import this file into their respective project. -> Use the function length_conversion() for conversion of volume units. -> Parameters : -> value : The number of from units you want to convert ...
2,795
84
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
conversions\weight_conversion.py
python
Python
""" Conversion of weight units. __author__ = "Anubhav Solanki" __license__ = "MIT" __version__ = "1.1.0" __maintainer__ = "Anubhav Solanki" __email__ = "anubhavsolanki0@gmail.com" USAGE : -> Import this file into their respective project. -> Use the function weight_conversion() for conversion of weight units. -> Para...
11,018
320
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_compression\burrows_wheeler.py
python
Python
""" https://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform The Burrows-Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characte...
7,133
178
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_compression\coordinate_compression.py
python
Python
""" Assumption: - The values to compress are assumed to be comparable, values can be sorted and compared with '<' and '>' operators. """ class CoordinateCompressor: """ A class for coordinate compression. This class allows you to compress and decompress a list of values. Mapping: In ad...
4,057
133
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_compression\huffman.py
python
Python
from __future__ import annotations import sys class Letter: def __init__(self, letter: str, freq: int): self.letter: str = letter self.freq: int = freq self.bitstring: dict[str, str] = {} def __repr__(self) -> str: return f"{self.letter}:{self.freq}" class TreeNode: def...
2,819
93
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_compression\lempel_ziv.py
python
Python
""" One of the several implementations of Lempel-Ziv-Welch compression algorithm https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch """ import math import os import sys def read_file_binary(file_path: str) -> str: """ Reads given file as bytes and returns them as a long string """ result ...
3,714
126
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_compression\lempel_ziv_decompress.py
python
Python
""" One of the several implementations of Lempel-Ziv-Welch decompression algorithm https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch """ import math import sys def read_file_binary(file_path: str) -> str: """ Reads given file as bytes and returns them as a long string """ result = "" ...
3,226
112
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_compression\lz77.py
python
Python
""" LZ77 compression algorithm - lossless data compression published in papers by Abraham Lempel and Jacob Ziv in 1977 - also known as LZ1 or sliding-window compression - form the basis for many variations including LZW, LZSS, LZMA and others It uses a “sliding window” method. Within the sliding window we have: - se...
8,274
226
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_compression\peak_signal_to_noise_ratio.py
python
Python
""" Peak signal-to-noise ratio - PSNR https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio Source: https://tutorials.techonical.com/how-to-calculate-psnr-value-of-two-images-using-python """ import math import os import cv2 import numpy as np PIXEL_MAX = 255.0 def peak_signal_to_noise_ratio(original: float...
1,388
47
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_compression\README.md
readme
Markdown
# Compression Data compression is everywhere, you need it to store data without taking too much space. Either the compression loses some data (then we talk about lossy compression, such as .jpg) or it does not (and then it is lossless compression, such as .png) Lossless compression is mainly used for archive purpose ...
736
11
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_compression\run_length_encoding.py
python
Python
# https://en.wikipedia.org/wiki/Run-length_encoding def run_length_encode(text: str) -> list: """ Performs Run Length Encoding >>> run_length_encode("AAAABBBCCDAA") [('A', 4), ('B', 3), ('C', 2), ('D', 1), ('A', 2)] >>> run_length_encode("A") [('A', 1)] >>> run_length_encode("AA") [('A...
1,373
49
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\arrays\equilibrium_index_in_array.py
python
Python
""" Find the Equilibrium Index of an Array. Reference: https://www.geeksforgeeks.org/equilibrium-index-of-an-array/ Python doctest can be run with the following command: python -m doctest -v equilibrium_index_in_array.py Given a sequence arr[] of size n, this function returns an equilibrium index (if any) or -1 if no...
1,403
59
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\arrays\find_triplets_with_0_sum.py
python
Python
from itertools import combinations def find_triplets_with_0_sum(nums: list[int]) -> list[list[int]]: """ Given a list of integers, return elements a, b, c such that a + b + c = 0. Args: nums: list of integers Returns: list of lists of integers where sum(each_list) == 0 Examples: ...
2,924
88
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\arrays\index_2d_array_in_1d.py
python
Python
""" Retrieves the value of an 0-indexed 1D index from a 2D array. There are two ways to retrieve value(s): 1. Index2DArrayIterator(matrix) -> Iterator[int] This iterator allows you to iterate through a 2D array by passing in the matrix and calling next(your_iterator). You can also use the iterator in a loop. Examples:...
3,238
106
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\arrays\kth_largest_element.py
python
Python
""" Given an array of integers and an integer k, find the kth largest element in the array. https://stackoverflow.com/questions/251781 """ def partition(arr: list[int], low: int, high: int) -> int: """ Partitions list based on the pivot element. This function rearranges the elements in the input list 'e...
3,790
118
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\arrays\median_two_array.py
python
Python
""" https://www.enjoyalgorithms.com/blog/median-of-two-sorted-arrays """ def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float: """ Find the median of two arrays. Args: nums1: The first array. nums2: The second array. Returns: The median of the two arrays. ...
1,614
62
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\arrays\monotonic_array.py
python
Python
# https://leetcode.com/problems/monotonic-array/ def is_monotonic(nums: list[int]) -> bool: """ Check if a list is monotonic. >>> is_monotonic([1, 2, 2, 3]) True >>> is_monotonic([6, 5, 4, 4]) True >>> is_monotonic([1, 3, 2]) False >>> is_monotonic([1,2,3,4,5,6,5]) False >>>...
983
38
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\arrays\pairs_with_given_sum.py
python
Python
#!/usr/bin/env python3 """ Given an array of integers and an integer req_sum, find the number of pairs of array elements whose sum is equal to req_sum. https://practice.geeksforgeeks.org/problems/count-pairs-with-given-sum5022/0 """ from itertools import combinations def pairs_with_sum(arr: list, req_sum: int) -> ...
731
30
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\arrays\permutations.py
python
Python
def permute_recursive(nums: list[int]) -> list[list[int]]: """ Return all permutations. >>> permute_recursive([1, 2, 3]) [[3, 2, 1], [2, 3, 1], [1, 3, 2], [3, 1, 2], [2, 1, 3], [1, 2, 3]] """ result: list[list[int]] = [] if len(nums) == 0: return [[]] for _ in range(len(nums)): ...
1,357
49
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\arrays\prefix_sum.py
python
Python
""" Author : Alexander Pantyukhin Date : November 3, 2022 Implement the class of prefix sum with useful functions based on it. """ class PrefixSum: def __init__(self, array: list[int]) -> None: len_array = len(array) self.prefix_sum = [0] * len_array if len_array > 0: se...
2,667
97
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\arrays\product_sum.py
python
Python
""" Calculate the Product Sum from a Special Array. reference: https://dev.to/sfrasica/algorithms-product-sum-from-an-array-dc6 Python doctests can be run with the following command: python -m doctest -v product_sum.py Calculate the product sum of a "special" array which can contain integers or nested arrays. The pro...
2,681
99
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\arrays\rotate_array.py
python
Python
def rotate_array(arr: list[int], steps: int) -> list[int]: """ Rotates a list to the right by steps positions. Parameters: arr (List[int]): The list of integers to rotate. steps (int): Number of positions to rotate. Can be negative for left rotation. Returns: List[int]: Rotated list. ...
2,015
81
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\arrays\sparse_table.py
python
Python
""" Sparse table is a data structure that allows answering range queries on a static number list, i.e. the elements do not change throughout all the queries. The implementation below will solve the problem of Range Minimum Query: Finding the minimum value of a subset [L..R] of a static number list. Overall time compl...
3,413
96
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\arrays\sudoku_solver.py
python
Python
""" Please do not modify this file! It is published at https://norvig.com/sudoku.html with only minimal changes to work with modern versions of Python. If you have improvements, please make them in a separate file. """ import random import time def cross(items_a, items_b): """ Cross product of elements in ...
8,360
260
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\avl_tree.py
python
Python
""" Implementation of an auto-balanced binary tree! For doctests run following command: python3 -m doctest -v avl_tree.py For testing run: python avl_tree.py """ from __future__ import annotations import math import random from typing import Any class MyQueue: def __init__(self) -> None: self.data: list...
10,051
350
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\basic_binary_tree.py
python
Python
from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass @dataclass class Node: data: int left: Node | None = None right: Node | None = None def __iter__(self) -> Iterator[int]: if self.left: yield from self.left yield self...
2,788
111
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\binary_search_tree.py
python
Python
r""" A binary search Tree Example 8 / \ 3 10 / \ \ 1 6 14 / \ / 4 7 13 >>> t = BinarySearchTree().insert(8, 3, 6, 1, 10, 14, 13, 4, 7) >>> print(" ".join(repr(i.value) for i in t.traversal_tree())) 8 3 1 6 4 7 10 14 13 ...
11,351
357
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\binary_search_tree_recursive.py
python
Python
""" This is a python3 implementation of binary search tree using recursion To run tests: python -m unittest binary_search_tree_recursive.py To run an example: python binary_search_tree_recursive.py """ from __future__ import annotations import unittest from collections.abc import Iterator import pytest class Nod...
17,131
642
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\binary_tree_mirror.py
python
Python
""" Problem Description: Given a binary tree, return its mirror. """ def binary_tree_mirror_dict(binary_tree_mirror_dictionary: dict, root: int): if not root or root not in binary_tree_mirror_dictionary: return left_child, right_child = binary_tree_mirror_dictionary[root][:2] binary_tree_mirror_di...
1,830
46
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\binary_tree_node_sum.py
python
Python
""" Sum of all nodes in a binary tree. Python implementation: O(n) time complexity - Recurses through :meth:`depth_first_search` with each element. O(n) space complexity - At any point in time maximum number of stack frames that could be in memory is `n` ...
1,746
76
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\binary_tree_path_sum.py
python
Python
""" Given the root of a binary tree and an integer target, find the number of paths where the sum of the values along the path equals target. Leetcode reference: https://leetcode.com/problems/path-sum-iii/ """ from __future__ import annotations class Node: """ A Node has value variable and pointers to Node...
2,576
109
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\binary_tree_traversals.py
python
Python
from __future__ import annotations from collections import deque from collections.abc import Generator from dataclasses import dataclass # https://en.wikipedia.org/wiki/Tree_traversal @dataclass class Node: data: int left: Node | None = None right: Node | None = None def make_tree() -> Node | None: ...
5,749
214
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\diameter_of_binary_tree.py
python
Python
""" The diameter/width of a tree is defined as the number of nodes on the longest path between two end nodes. """ from __future__ import annotations from dataclasses import dataclass @dataclass class Node: data: int left: Node | None = None right: Node | None = None def depth(self) -> int: ...
1,718
74
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\diff_views_of_binary_tree.py
python
Python
r""" Problem: Given root of a binary tree, return the: 1. binary-tree-right-side-view 2. binary-tree-left-side-view 3. binary-tree-top-side-view 4. binary-tree-bottom-side-view """ from __future__ import annotations from collections import defaultdict from dataclasses import dataclass @dataclass class TreeNode: ...
5,053
211
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\distribute_coins.py
python
Python
""" Author : Alexander Pantyukhin Date : November 7, 2022 Task: You are given a tree root of a binary tree with n nodes, where each node has node.data coins. There are exactly n coins in whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent...
3,398
138
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\fenwick_tree.py
python
Python
from copy import deepcopy class FenwickTree: """ Fenwick Tree More info: https://en.wikipedia.org/wiki/Fenwick_tree """ def __init__(self, arr: list[int] | None = None, size: int | None = None) -> None: """ Constructor for the Fenwick tree Parameters: arr (li...
6,615
248
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\flatten_binarytree_to_linkedlist.py
python
Python
""" Binary Tree Flattening Algorithm This code defines an algorithm to flatten a binary tree into a linked list represented using the right pointers of the tree nodes. It uses in-place flattening and demonstrates the flattening process along with a display function to visualize the flattened linked list. https://www.g...
3,547
140