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/ciphers/elgamal_key_generator.py
ciphers/elgamal_key_generator.py
import os import random import sys from . import cryptomath_module as cryptomath from . import rabin_miller min_primitive_root = 3 # I have written my code naively same as definition of primitive root # however every time I run this program, memory exceeded... # so I used 4.80 Algorithm in # Handbook of Applied Cryptography(CRC Press, ISBN : 0-8493-8523-7, October 1996) # and it seems to run nicely! def primitive_root(p_val: int) -> int: print("Generating primitive root of p") while True: g = random.randrange(3, p_val) if pow(g, 2, p_val) == 1: continue if pow(g, p_val, p_val) == 1: continue return g def generate_key(key_size: int) -> tuple[tuple[int, int, int, int], tuple[int, int]]: print("Generating prime p...") p = rabin_miller.generate_large_prime(key_size) # select large prime number. e_1 = primitive_root(p) # one primitive root on modulo p. d = random.randrange(3, p) # private_key -> have to be greater than 2 for safety. e_2 = cryptomath.find_mod_inverse(pow(e_1, d, p), p) public_key = (key_size, e_1, e_2, p) private_key = (key_size, d) return public_key, private_key def make_key_files(name: str, key_size: int) -> None: if os.path.exists(f"{name}_pubkey.txt") or os.path.exists(f"{name}_privkey.txt"): print("\nWARNING:") print( f'"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n' "Use a different name or delete these files and re-run this program." ) sys.exit() public_key, private_key = generate_key(key_size) print(f"\nWriting public key to file {name}_pubkey.txt...") with open(f"{name}_pubkey.txt", "w") as fo: fo.write(f"{public_key[0]},{public_key[1]},{public_key[2]},{public_key[3]}") print(f"Writing private key to file {name}_privkey.txt...") with open(f"{name}_privkey.txt", "w") as fo: fo.write(f"{private_key[0]},{private_key[1]}") def main() -> None: print("Making key files...") make_key_files("elgamal", 2048) print("Key files generation successful") if __name__ == "__main__": main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/enigma_machine2.py
ciphers/enigma_machine2.py
""" | Wikipedia: https://en.wikipedia.org/wiki/Enigma_machine | Video explanation: https://youtu.be/QwQVMqfoB2E | Also check out Numberphile's and Computerphile's videos on this topic This module contains function ``enigma`` which emulates the famous Enigma machine from WWII. Module includes: - ``enigma`` function - showcase of function usage - ``9`` randomly generated rotors - reflector (aka static rotor) - original alphabet Created by TrapinchO """ from __future__ import annotations RotorPositionT = tuple[int, int, int] RotorSelectionT = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # -------------------------- default selection -------------------------- # rotors -------------------------- rotor1 = "EGZWVONAHDCLFQMSIPJBYUKXTR" rotor2 = "FOBHMDKEXQNRAULPGSJVTYICZW" rotor3 = "ZJXESIUQLHAVRMDOYGTNFWPBKC" # reflector -------------------------- reflector = { "A": "N", "N": "A", "B": "O", "O": "B", "C": "P", "P": "C", "D": "Q", "Q": "D", "E": "R", "R": "E", "F": "S", "S": "F", "G": "T", "T": "G", "H": "U", "U": "H", "I": "V", "V": "I", "J": "W", "W": "J", "K": "X", "X": "K", "L": "Y", "Y": "L", "M": "Z", "Z": "M", } # -------------------------- extra rotors -------------------------- rotor4 = "RMDJXFUWGISLHVTCQNKYPBEZOA" rotor5 = "SGLCPQWZHKXAREONTFBVIYJUDM" rotor6 = "HVSICLTYKQUBXDWAJZOMFGPREN" rotor7 = "RZWQHFMVDBKICJLNTUXAGYPSOE" rotor8 = "LFKIJODBEGAMQPXVUHYSTCZRWN" rotor9 = "KOAEGVDHXPQZMLFTYWJNBRCIUS" def _validator( rotpos: RotorPositionT, rotsel: RotorSelectionT, pb: str ) -> tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: """ Checks if the values can be used for the ``enigma`` function >>> _validator((1,1,1), (rotor1, rotor2, rotor3), 'POLAND') ((1, 1, 1), ('EGZWVONAHDCLFQMSIPJBYUKXTR', 'FOBHMDKEXQNRAULPGSJVTYICZW', \ 'ZJXESIUQLHAVRMDOYGTNFWPBKC'), \ {'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N'}) :param rotpos: rotor_positon :param rotsel: rotor_selection :param pb: plugb -> validated and transformed :return: (`rotpos`, `rotsel`, `pb`) """ # Checks if there are 3 unique rotors if (unique_rotsel := len(set(rotsel))) < 3: msg = f"Please use 3 unique rotors (not {unique_rotsel})" raise Exception(msg) # Checks if rotor positions are valid rotorpos1, rotorpos2, rotorpos3 = rotpos if not 0 < rotorpos1 <= len(abc): msg = f"First rotor position is not within range of 1..26 ({rotorpos1}" raise ValueError(msg) if not 0 < rotorpos2 <= len(abc): msg = f"Second rotor position is not within range of 1..26 ({rotorpos2})" raise ValueError(msg) if not 0 < rotorpos3 <= len(abc): msg = f"Third rotor position is not within range of 1..26 ({rotorpos3})" raise ValueError(msg) # Validates string and returns dict pbdict = _plugboard(pb) return rotpos, rotsel, pbdict def _plugboard(pbstring: str) -> dict[str, str]: """ https://en.wikipedia.org/wiki/Enigma_machine#Plugboard >>> _plugboard('PICTURES') {'P': 'I', 'I': 'P', 'C': 'T', 'T': 'C', 'U': 'R', 'R': 'U', 'E': 'S', 'S': 'E'} >>> _plugboard('POLAND') {'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N'} In the code, ``pb`` stands for ``plugboard`` Pairs can be separated by spaces :param pbstring: string containing plugboard setting for the Enigma machine :return: dictionary containing converted pairs """ # tests the input string if it # a) is type string # b) has even length (so pairs can be made) if not isinstance(pbstring, str): msg = f"Plugboard setting isn't type string ({type(pbstring)})" raise TypeError(msg) elif len(pbstring) % 2 != 0: msg = f"Odd number of symbols ({len(pbstring)})" raise Exception(msg) elif pbstring == "": return {} pbstring.replace(" ", "") # Checks if all characters are unique tmppbl = set() for i in pbstring: if i not in abc: msg = f"'{i}' not in list of symbols" raise Exception(msg) elif i in tmppbl: msg = f"Duplicate symbol ({i})" raise Exception(msg) else: tmppbl.add(i) del tmppbl # Created the dictionary pb = {} for j in range(0, len(pbstring) - 1, 2): pb[pbstring[j]] = pbstring[j + 1] pb[pbstring[j + 1]] = pbstring[j] return pb def enigma( text: str, rotor_position: RotorPositionT, rotor_selection: RotorSelectionT = (rotor1, rotor2, rotor3), plugb: str = "", ) -> str: """ The only difference with real-world enigma is that ``I`` allowed string input. All characters are converted to uppercase. (non-letter symbol are ignored) | How it works: | (for every letter in the message) - Input letter goes into the plugboard. If it is connected to another one, switch it. - Letter goes through ``3`` rotors. Each rotor can be represented as ``2`` sets of symbol, where one is shuffled. Each symbol from the first set has corresponding symbol in the second set and vice versa. example:: | ABCDEFGHIJKLMNOPQRSTUVWXYZ | e.g. F=D and D=F | VKLEPDBGRNWTFCJOHQAMUZYIXS | - Symbol then goes through reflector (static rotor). There it is switched with paired symbol. The reflector can be represented as ``2`` sets, each with half of the alphanet. There are usually ``10`` pairs of letters. Example:: | ABCDEFGHIJKLM | e.g. E is paired to X | ZYXWVUTSRQPON | so when E goes in X goes out and vice versa - Letter then goes through the rotors again - If the letter is connected to plugboard, it is switched. - Return the letter >>> enigma('Hello World!', (1, 2, 1), plugb='pictures') 'KORYH JUHHI!' >>> enigma('KORYH, juhhi!', (1, 2, 1), plugb='pictures') 'HELLO, WORLD!' >>> enigma('hello world!', (1, 1, 1), plugb='pictures') 'FPNCZ QWOBU!' >>> enigma('FPNCZ QWOBU', (1, 1, 1), plugb='pictures') 'HELLO WORLD' :param text: input message :param rotor_position: tuple with ``3`` values in range ``1``.. ``26`` :param rotor_selection: tuple with ``3`` rotors :param plugb: string containing plugboard configuration (default ``''``) :return: en/decrypted string """ text = text.upper() rotor_position, rotor_selection, plugboard = _validator( rotor_position, rotor_selection, plugb.upper() ) rotorpos1, rotorpos2, rotorpos3 = rotor_position rotor1, rotor2, rotor3 = rotor_selection rotorpos1 -= 1 rotorpos2 -= 1 rotorpos3 -= 1 result = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: symbol = plugboard[symbol] # rotor ra -------------------------- index = abc.index(symbol) + rotorpos1 symbol = rotor1[index % len(abc)] # rotor rb -------------------------- index = abc.index(symbol) + rotorpos2 symbol = rotor2[index % len(abc)] # rotor rc -------------------------- index = abc.index(symbol) + rotorpos3 symbol = rotor3[index % len(abc)] # reflector -------------------------- # this is the reason you don't need another machine to decipher symbol = reflector[symbol] # 2nd rotors symbol = abc[rotor3.index(symbol) - rotorpos3] symbol = abc[rotor2.index(symbol) - rotorpos2] symbol = abc[rotor1.index(symbol) - rotorpos1] # 2nd plugboard if symbol in plugboard: symbol = plugboard[symbol] # moves/resets rotor positions rotorpos1 += 1 if rotorpos1 >= len(abc): rotorpos1 = 0 rotorpos2 += 1 if rotorpos2 >= len(abc): rotorpos2 = 0 rotorpos3 += 1 if rotorpos3 >= len(abc): rotorpos3 = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(symbol) return "".join(result) if __name__ == "__main__": message = "This is my Python script that emulates the Enigma machine from WWII." rotor_pos = (1, 1, 1) pb = "pictures" rotor_sel = (rotor2, rotor4, rotor8) en = enigma(message, rotor_pos, rotor_sel, pb) print("Encrypted message:", en) print("Decrypted message:", enigma(en, rotor_pos, rotor_sel, pb))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/rot13.py
ciphers/rot13.py
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 """ out = "" for c in s: if "A" <= c <= "Z": out += chr(ord("A") + (ord(c) - ord("A") + n) % 26) elif "a" <= c <= "z": out += chr(ord("a") + (ord(c) - ord("a") + n) % 26) else: out += c return out def main() -> None: s0 = input("Enter message: ") s1 = dencrypt(s0, 13) print("Encryption:", s1) s2 = dencrypt(s1, 13) print("Decryption: ", s2) 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/ciphers/brute_force_caesar_cipher.py
ciphers/brute_force_caesar_cipher.py
import string def decrypt(message: str) -> None: """ >>> decrypt('TMDETUX PMDVU') Decryption using Key #0: TMDETUX PMDVU Decryption using Key #1: SLCDSTW OLCUT Decryption using Key #2: RKBCRSV NKBTS Decryption using Key #3: QJABQRU MJASR Decryption using Key #4: PIZAPQT LIZRQ Decryption using Key #5: OHYZOPS KHYQP Decryption using Key #6: NGXYNOR JGXPO Decryption using Key #7: MFWXMNQ IFWON Decryption using Key #8: LEVWLMP HEVNM Decryption using Key #9: KDUVKLO GDUML Decryption using Key #10: JCTUJKN FCTLK Decryption using Key #11: IBSTIJM EBSKJ Decryption using Key #12: HARSHIL DARJI Decryption using Key #13: GZQRGHK CZQIH Decryption using Key #14: FYPQFGJ BYPHG Decryption using Key #15: EXOPEFI AXOGF Decryption using Key #16: DWNODEH ZWNFE Decryption using Key #17: CVMNCDG YVMED Decryption using Key #18: BULMBCF XULDC Decryption using Key #19: ATKLABE WTKCB Decryption using Key #20: ZSJKZAD VSJBA Decryption using Key #21: YRIJYZC URIAZ Decryption using Key #22: XQHIXYB TQHZY Decryption using Key #23: WPGHWXA SPGYX Decryption using Key #24: VOFGVWZ ROFXW Decryption using Key #25: UNEFUVY QNEWV """ for key in range(len(string.ascii_uppercase)): translated = "" for symbol in message: if symbol in string.ascii_uppercase: num = string.ascii_uppercase.find(symbol) num = num - key if num < 0: num = num + len(string.ascii_uppercase) translated = translated + string.ascii_uppercase[num] else: translated = translated + symbol print(f"Decryption using Key #{key}: {translated}") def main() -> None: message = input("Encrypted message: ") message = message.upper() decrypt(message) 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/ciphers/decrypt_caesar_with_chi_squared.py
ciphers/decrypt_caesar_with_chi_squared.py
#!/usr/bin/env python3 from __future__ import annotations def decrypt_caesar_with_chi_squared( ciphertext: str, cipher_alphabet: list[str] | None = None, frequencies_dict: dict[str, float] | None = None, case_sensitive: bool = False, ) -> tuple[int, float, str]: """ Basic Usage =========== Arguments: * `ciphertext` (str): the text to decode (encoded with the caesar cipher) Optional Arguments: * `cipher_alphabet` (list): the alphabet used for the cipher (each letter is a string separated by commas) * `frequencies_dict` (dict): a dictionary of word frequencies where keys are the letters and values are a percentage representation of the frequency as a decimal/float * `case_sensitive` (bool): a boolean value: ``True`` if the case matters during decryption, ``False`` if it doesn't Returns: * A tuple in the form of: (`most_likely_cipher`, `most_likely_cipher_chi_squared_value`, `decoded_most_likely_cipher`) where... - `most_likely_cipher` is an integer representing the shift of the smallest chi-squared statistic (most likely key) - `most_likely_cipher_chi_squared_value` is a float representing the chi-squared statistic of the most likely shift - `decoded_most_likely_cipher` is a string with the decoded cipher (decoded by the most_likely_cipher key) The Chi-squared test ==================== The caesar cipher ----------------- The caesar cipher is a very insecure encryption algorithm, however it has been used since Julius Caesar. The cipher is a simple substitution cipher where each character in the plain text is replaced by a character in the alphabet a certain number of characters after the original character. The number of characters away is called the shift or key. For example: | Plain text: ``hello`` | Key: ``1`` | Cipher text: ``ifmmp`` | (each letter in ``hello`` has been shifted one to the right in the eng. alphabet) As you can imagine, this doesn't provide lots of security. In fact decrypting ciphertext by brute-force is extremely easy even by hand. However one way to do that is the chi-squared test. The chi-squared test -------------------- Each letter in the english alphabet has a frequency, or the amount of times it shows up compared to other letters (usually expressed as a decimal representing the percentage likelihood). The most common letter in the english language is ``e`` with a frequency of ``0.11162`` or ``11.162%``. The test is completed in the following fashion. 1. The ciphertext is decoded in a brute force way (every combination of the ``26`` possible combinations) 2. For every combination, for each letter in the combination, the average amount of times the letter should appear the message is calculated by multiplying the total number of characters by the frequency of the letter. | For example: | In a message of ``100`` characters, ``e`` should appear around ``11.162`` times. 3. Then, to calculate the margin of error (the amount of times the letter SHOULD appear with the amount of times the letter DOES appear), we use the chi-squared test. The following formula is used: Let: - n be the number of times the letter actually appears - p be the predicted value of the number of times the letter should appear (see item ``2``) - let v be the chi-squared test result (referred to here as chi-squared value/statistic) :: (n - p)^2 --------- = v p 4. Each chi squared value for each letter is then added up to the total. The total is the chi-squared statistic for that encryption key. 5. The encryption key with the lowest chi-squared value is the most likely to be the decoded answer. Further Reading =============== * http://practicalcryptography.com/cryptanalysis/text-characterisation/chi-squared-statistic/ * https://en.wikipedia.org/wiki/Letter_frequency * https://en.wikipedia.org/wiki/Chi-squared_test * https://en.m.wikipedia.org/wiki/Caesar_cipher Doctests ======== >>> decrypt_caesar_with_chi_squared( ... 'dof pz aol jhlzhy jpwoly zv wvwbshy? pa pz avv lhzf av jyhjr!' ... ) # doctest: +NORMALIZE_WHITESPACE (7, 3129.228005747531, 'why is the caesar cipher so popular? it is too easy to crack!') >>> decrypt_caesar_with_chi_squared('crybd cdbsxq') (10, 233.35343938980898, 'short string') >>> decrypt_caesar_with_chi_squared('Crybd Cdbsxq', case_sensitive=True) (10, 233.35343938980898, 'Short String') >>> decrypt_caesar_with_chi_squared(12) Traceback (most recent call last): AttributeError: 'int' object has no attribute 'lower' """ alphabet_letters = cipher_alphabet or [chr(i) for i in range(97, 123)] # If the argument is None or the user provided an empty dictionary if not frequencies_dict: # Frequencies of letters in the english language (how much they show up) frequencies = { "a": 0.08497, "b": 0.01492, "c": 0.02202, "d": 0.04253, "e": 0.11162, "f": 0.02228, "g": 0.02015, "h": 0.06094, "i": 0.07546, "j": 0.00153, "k": 0.01292, "l": 0.04025, "m": 0.02406, "n": 0.06749, "o": 0.07507, "p": 0.01929, "q": 0.00095, "r": 0.07587, "s": 0.06327, "t": 0.09356, "u": 0.02758, "v": 0.00978, "w": 0.02560, "x": 0.00150, "y": 0.01994, "z": 0.00077, } else: # Custom frequencies dictionary frequencies = frequencies_dict if not case_sensitive: ciphertext = ciphertext.lower() # Chi squared statistic values chi_squared_statistic_values: dict[int, tuple[float, str]] = {} # cycle through all of the shifts for shift in range(len(alphabet_letters)): decrypted_with_shift = "" # decrypt the message with the shift for letter in ciphertext: try: # Try to index the letter in the alphabet new_key = (alphabet_letters.index(letter.lower()) - shift) % len( alphabet_letters ) decrypted_with_shift += ( alphabet_letters[new_key].upper() if case_sensitive and letter.isupper() else alphabet_letters[new_key] ) except ValueError: # Append the character if it isn't in the alphabet decrypted_with_shift += letter chi_squared_statistic = 0.0 # Loop through each letter in the decoded message with the shift for letter in decrypted_with_shift: if case_sensitive: letter = letter.lower() if letter in frequencies: # Get the amount of times the letter occurs in the message occurrences = decrypted_with_shift.lower().count(letter) # Get the excepcted amount of times the letter should appear based # on letter frequencies expected = frequencies[letter] * occurrences # Complete the chi squared statistic formula chi_letter_value = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value elif letter.lower() in frequencies: # Get the amount of times the letter occurs in the message occurrences = decrypted_with_shift.count(letter) # Get the excepcted amount of times the letter should appear based # on letter frequencies expected = frequencies[letter] * occurrences # Complete the chi squared statistic formula chi_letter_value = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value # Add the data to the chi_squared_statistic_values dictionary chi_squared_statistic_values[shift] = ( chi_squared_statistic, decrypted_with_shift, ) # Get the most likely cipher by finding the cipher with the smallest chi squared # statistic def chi_squared_statistic_values_sorting_key(key: int) -> tuple[float, str]: return chi_squared_statistic_values[key] most_likely_cipher: int = min( chi_squared_statistic_values, key=chi_squared_statistic_values_sorting_key, ) # Get all the data from the most likely cipher (key, decoded message) ( most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, ) = chi_squared_statistic_values[most_likely_cipher] # Return the data on the most likely shift return ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, )
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/playfair_cipher.py
ciphers/playfair_cipher.py
""" 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 encryption technique 3) It is a multiple letter encryption cipher The implementation in the code below encodes alphabets only. It removes spaces, special characters and numbers from the code. Playfair is no longer used by military forces because of known insecurities and of the advent of automated encryption devices. This cipher is regarded as insecure since before World War I. """ import itertools import string from collections.abc import Generator, Iterable def chunker(seq: Iterable[str], size: int) -> Generator[tuple[str, ...]]: it = iter(seq) while True: chunk = tuple(itertools.islice(it, size)) if not chunk: return yield chunk def prepare_input(dirty: str) -> str: """ Prepare the plaintext by up-casing it and separating repeated letters with X's """ dirty = "".join([c.upper() for c in dirty if c in string.ascii_letters]) clean = "" if len(dirty) < 2: return dirty for i in range(len(dirty) - 1): clean += dirty[i] if dirty[i] == dirty[i + 1]: clean += "X" clean += dirty[-1] if len(clean) & 1: clean += "X" return clean def generate_table(key: str) -> list[str]: # I and J are used interchangeably to allow # us to use a 5x5 table (25 letters) alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ" # we're using a list instead of a '2d' array because it makes the math # for setting up the table and doing the actual encoding/decoding simpler table = [] # copy key chars into the table if they are in `alphabet` ignoring duplicates for char in key.upper(): if char not in table and char in alphabet: table.append(char) # fill the rest of the table in with the remaining alphabet chars for char in alphabet: if char not in table: table.append(char) return table def encode(plaintext: str, key: str) -> str: """ Encode the given plaintext using the Playfair cipher. Takes the plaintext and the key as input and returns the encoded string. >>> encode("Hello", "MONARCHY") 'CFSUPM' >>> encode("attack on the left flank", "EMERGENCY") 'DQZSBYFSDZFMFNLOHFDRSG' >>> encode("Sorry!", "SPECIAL") 'AVXETX' >>> encode("Number 1", "NUMBER") 'UMBENF' >>> encode("Photosynthesis!", "THE SUN") 'OEMHQHVCHESUKE' """ table = generate_table(key) plaintext = prepare_input(plaintext) ciphertext = "" for char1, char2 in chunker(plaintext, 2): row1, col1 = divmod(table.index(char1), 5) row2, col2 = divmod(table.index(char2), 5) if row1 == row2: ciphertext += table[row1 * 5 + (col1 + 1) % 5] ciphertext += table[row2 * 5 + (col2 + 1) % 5] elif col1 == col2: ciphertext += table[((row1 + 1) % 5) * 5 + col1] ciphertext += table[((row2 + 1) % 5) * 5 + col2] else: # rectangle ciphertext += table[row1 * 5 + col2] ciphertext += table[row2 * 5 + col1] return ciphertext def decode(ciphertext: str, key: str) -> str: """ Decode the input string using the provided key. >>> decode("BMZFAZRZDH", "HAZARD") 'FIREHAZARD' >>> decode("HNBWBPQT", "AUTOMOBILE") 'DRIVINGX' >>> decode("SLYSSAQS", "CASTLE") 'ATXTACKX' """ table = generate_table(key) plaintext = "" for char1, char2 in chunker(ciphertext, 2): row1, col1 = divmod(table.index(char1), 5) row2, col2 = divmod(table.index(char2), 5) if row1 == row2: plaintext += table[row1 * 5 + (col1 - 1) % 5] plaintext += table[row2 * 5 + (col2 - 1) % 5] elif col1 == col2: plaintext += table[((row1 - 1) % 5) * 5 + col1] plaintext += table[((row2 - 1) % 5) * 5 + col2] else: # rectangle plaintext += table[row1 * 5 + col2] plaintext += table[row2 * 5 + col1] return plaintext if __name__ == "__main__": import doctest doctest.testmod() print("Encoded:", encode("BYE AND THANKS", "GREETING")) print("Decoded:", decode("CXRBANRLBALQ", "GREETING"))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/onepad_cipher.py
ciphers/onepad_cipher.py
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) >>> Onepad().encrypt(" ") ([6969], [69]) >>> random.seed(1) >>> Onepad().encrypt("Hello") ([9729, 114756, 4653, 31309, 10492], [69, 292, 33, 131, 61]) >>> Onepad().encrypt(1) Traceback (most recent call last): ... TypeError: 'int' object is not iterable >>> Onepad().encrypt(1.1) Traceback (most recent call last): ... TypeError: 'float' object is not iterable """ plain = [ord(i) for i in text] key = [] cipher = [] for i in plain: k = random.randint(1, 300) c = (i + k) * k cipher.append(c) key.append(k) return cipher, key @staticmethod def decrypt(cipher: list[int], key: list[int]) -> str: """ Function to decrypt text using pseudo-random numbers. >>> Onepad().decrypt([], []) '' >>> Onepad().decrypt([35], []) '' >>> Onepad().decrypt([], [35]) Traceback (most recent call last): ... IndexError: list index out of range >>> random.seed(1) >>> Onepad().decrypt([9729, 114756, 4653, 31309, 10492], [69, 292, 33, 131, 61]) 'Hello' """ plain = [] for i in range(len(key)): p = int((cipher[i] - (key[i]) ** 2) / key[i]) plain.append(chr(p)) return "".join(plain) if __name__ == "__main__": c, k = Onepad().encrypt("Hello") print(c, k) print(Onepad().decrypt(c, k))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/base16.py
ciphers/base16.py
def base16_encode(data: bytes) -> str: """ Encodes the given bytes into base16. >>> base16_encode(b'Hello World!') '48656C6C6F20576F726C6421' >>> base16_encode(b'HELLO WORLD!') '48454C4C4F20574F524C4421' >>> base16_encode(b'') '' """ # Turn the data into a list of integers (where each integer is a byte), # Then turn each byte into its hexadecimal representation, make sure # it is uppercase, and then join everything together and return it. return "".join([hex(byte)[2:].zfill(2).upper() for byte in list(data)]) def base16_decode(data: str) -> bytes: """ Decodes the given base16 encoded data into bytes. >>> base16_decode('48656C6C6F20576F726C6421') b'Hello World!' >>> base16_decode('48454C4C4F20574F524C4421') b'HELLO WORLD!' >>> base16_decode('') b'' >>> base16_decode('486') Traceback (most recent call last): ... ValueError: Base16 encoded data is invalid: Data does not have an even number of hex digits. >>> base16_decode('48656c6c6f20576f726c6421') Traceback (most recent call last): ... ValueError: Base16 encoded data is invalid: Data is not uppercase hex or it contains invalid characters. >>> base16_decode('This is not base64 encoded data.') Traceback (most recent call last): ... ValueError: Base16 encoded data is invalid: Data is not uppercase hex or it contains invalid characters. """ # Check data validity, following RFC3548 # https://www.ietf.org/rfc/rfc3548.txt if (len(data) % 2) != 0: raise ValueError( """Base16 encoded data is invalid: Data does not have an even number of hex digits.""" ) # Check the character set - the standard base16 alphabet # is uppercase according to RFC3548 section 6 if not set(data) <= set("0123456789ABCDEF"): raise ValueError( """Base16 encoded data is invalid: Data is not uppercase hex or it contains invalid characters.""" ) # For every two hexadecimal digits (= a byte), turn it into an integer. # Then, string the result together into bytes, and return it. return bytes(int(data[i] + data[i + 1], 16) for i in range(0, len(data), 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/ciphers/morse_code.py
ciphers/morse_code.py
#!/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": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", "0": "-----", "&": ".-...", "@": ".--.-.", ":": "---...", ",": "--..--", ".": ".-.-.-", "'": ".----.", '"': ".-..-.", "?": "..--..", "/": "-..-.", "=": "-...-", "+": ".-.-.", "-": "-....-", "(": "-.--.", ")": "-.--.-", "!": "-.-.--", " ": "/" } # Exclamation mark is not in ITU-R recommendation # fmt: on REVERSE_DICT = {value: key for key, value in MORSE_CODE_DICT.items()} def encrypt(message: str) -> str: """ >>> encrypt("Sos!") '... --- ... -.-.--' >>> encrypt("SOS!") == encrypt("sos!") True """ return " ".join(MORSE_CODE_DICT[char] for char in message.upper()) def decrypt(message: str) -> str: """ >>> decrypt('... --- ... -.-.--') 'SOS!' """ return "".join(REVERSE_DICT[char] for char in message.split()) def main() -> None: """ >>> s = "".join(MORSE_CODE_DICT) >>> decrypt(encrypt(s)) == s True """ message = "Morse code here!" print(message) message = encrypt(message) print(message) message = decrypt(message) print(message) if __name__ == "__main__": main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/bifid.py
ciphers/bifid.py
#!/usr/bin/env python3 """ The Bifid Cipher uses a Polybius Square to encipher a message in a way that makes it fairly difficult to decipher without knowing the secret. https://www.braingle.com/brainteasers/codes/bifid.php """ import numpy as np SQUARE = [ ["a", "b", "c", "d", "e"], ["f", "g", "h", "i", "k"], ["l", "m", "n", "o", "p"], ["q", "r", "s", "t", "u"], ["v", "w", "x", "y", "z"], ] class BifidCipher: def __init__(self) -> None: self.SQUARE = np.array(SQUARE) def letter_to_numbers(self, letter: str) -> np.ndarray: """ Return the pair of numbers that represents the given letter in the polybius square >>> np.array_equal(BifidCipher().letter_to_numbers('a'), [1,1]) True >>> np.array_equal(BifidCipher().letter_to_numbers('u'), [4,5]) True """ index1, index2 = np.where(letter == self.SQUARE) indexes = np.concatenate([index1 + 1, index2 + 1]) return indexes def numbers_to_letter(self, index1: int, index2: int) -> str: """ Return the letter corresponding to the position [index1, index2] in the polybius square >>> BifidCipher().numbers_to_letter(4, 5) == "u" True >>> BifidCipher().numbers_to_letter(1, 1) == "a" True """ letter = self.SQUARE[index1 - 1, index2 - 1] return letter def encode(self, message: str) -> str: """ Return the encoded version of message according to the polybius cipher >>> BifidCipher().encode('testmessage') == 'qtltbdxrxlk' True >>> BifidCipher().encode('Test Message') == 'qtltbdxrxlk' True >>> BifidCipher().encode('test j') == BifidCipher().encode('test i') True """ message = message.lower() message = message.replace(" ", "") message = message.replace("j", "i") first_step = np.empty((2, len(message))) for letter_index in range(len(message)): numbers = self.letter_to_numbers(message[letter_index]) first_step[0, letter_index] = numbers[0] first_step[1, letter_index] = numbers[1] second_step = first_step.reshape(2 * len(message)) encoded_message = "" for numbers_index in range(len(message)): index1 = int(second_step[numbers_index * 2]) index2 = int(second_step[(numbers_index * 2) + 1]) letter = self.numbers_to_letter(index1, index2) encoded_message = encoded_message + letter return encoded_message def decode(self, message: str) -> str: """ Return the decoded version of message according to the polybius cipher >>> BifidCipher().decode('qtltbdxrxlk') == 'testmessage' True """ message = message.lower() message.replace(" ", "") first_step = np.empty(2 * len(message)) for letter_index in range(len(message)): numbers = self.letter_to_numbers(message[letter_index]) first_step[letter_index * 2] = numbers[0] first_step[letter_index * 2 + 1] = numbers[1] second_step = first_step.reshape((2, len(message))) decoded_message = "" for numbers_index in range(len(message)): index1 = int(second_step[0, numbers_index]) index2 = int(second_step[1, numbers_index]) letter = self.numbers_to_letter(index1, index2) decoded_message = decoded_message + letter return decoded_message
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/shuffled_shift_cipher.py
ciphers/shuffled_shift_cipher.py
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 the English alphabet 2. lowercase letters of the English alphabet 3. digits from 0 to 9 Using unique characters from the passcode, the normal list of characters, that can be allowed in the plaintext, is pivoted and shuffled. Refer to docstring of __make_key_list() to learn more about the shuffling. Then, using the passcode, a number is calculated which is used to encrypt the plaintext message with the normal shift cipher method, only in this case, the reference, to look back at while decrypting, is shuffled. Each cipher object can possess an optional argument as passcode, without which a new passcode is generated for that object automatically. cip1 = ShuffledShiftCipher('d4usr9TWxw9wMD') cip2 = ShuffledShiftCipher() """ def __init__(self, passcode: str | None = None) -> None: """ Initializes a cipher object with a passcode as it's entity Note: No new passcode is generated if user provides a passcode while creating the object """ self.__passcode = passcode or self.__passcode_creator() self.__key_list = self.__make_key_list() self.__shift_key = self.__make_shift_key() def __str__(self) -> str: """ :return: passcode of the cipher object """ return "".join(self.__passcode) def __neg_pos(self, iterlist: list[int]) -> list[int]: """ Mutates the list by changing the sign of each alternate element :param iterlist: takes a list iterable :return: the mutated list """ for i in range(1, len(iterlist), 2): iterlist[i] *= -1 return iterlist def __passcode_creator(self) -> list[str]: """ Creates a random password from the selection buffer of 1. uppercase letters of the English alphabet 2. lowercase letters of the English alphabet 3. digits from 0 to 9 :rtype: list :return: a password of a random length between 10 to 20 """ choices = string.ascii_letters + string.digits password = [random.choice(choices) for _ in range(random.randint(10, 20))] return password def __make_key_list(self) -> list[str]: """ Shuffles the ordered character choices by pivoting at breakpoints Breakpoints are the set of characters in the passcode eg: if, ABCDEFGHIJKLMNOPQRSTUVWXYZ are the possible characters and CAMERA is the passcode then, breakpoints = [A,C,E,M,R] # sorted set of characters from passcode shuffled parts: [A,CB,ED,MLKJIHGF,RQPON,ZYXWVUTS] shuffled __key_list : ACBEDMLKJIHGFRQPONZYXWVUTS Shuffling only 26 letters of the english alphabet can generate 26! combinations for the shuffled list. In the program we consider, a set of 97 characters (including letters, digits, punctuation and whitespaces), thereby creating a possibility of 97! combinations (which is a 152 digit number in itself), thus diminishing the possibility of a brute force approach. Moreover, shift keys even introduce a multiple of 26 for a brute force approach for each of the already 97! combinations. """ # key_list_options contain nearly all printable except few elements from # string.whitespace key_list_options = ( string.ascii_letters + string.digits + string.punctuation + " \t\n" ) keys_l = [] # creates points known as breakpoints to break the key_list_options at those # points and pivot each substring breakpoints = sorted(set(self.__passcode)) temp_list: list[str] = [] # algorithm for creating a new shuffled list, keys_l, out of key_list_options for i in key_list_options: temp_list.extend(i) # checking breakpoints at which to pivot temporary sublist and add it into # keys_l if i in breakpoints or i == key_list_options[-1]: keys_l.extend(temp_list[::-1]) temp_list.clear() # returning a shuffled keys_l to prevent brute force guessing of shift key return keys_l def __make_shift_key(self) -> int: """ sum() of the mutated list of ascii values of all characters where the mutated list is the one returned by __neg_pos() """ num = sum(self.__neg_pos([ord(x) for x in self.__passcode])) return num if num > 0 else len(self.__passcode) def decrypt(self, encoded_message: str) -> str: """ Performs shifting of the encoded_message w.r.t. the shuffled __key_list to create the decoded_message >>> ssc = ShuffledShiftCipher('4PYIXyqeQZr44') >>> ssc.decrypt("d>**-1z6&'5z'5z:z+-='$'>=zp:>5:#z<'.&>#") 'Hello, this is a modified Caesar cipher' """ decoded_message = "" # decoding shift like Caesar cipher algorithm implementing negative shift or # reverse shift or left shift for i in encoded_message: position = self.__key_list.index(i) decoded_message += self.__key_list[ (position - self.__shift_key) % -len(self.__key_list) ] return decoded_message def encrypt(self, plaintext: str) -> str: """ Performs shifting of the plaintext w.r.t. the shuffled __key_list to create the encoded_message >>> ssc = ShuffledShiftCipher('4PYIXyqeQZr44') >>> ssc.encrypt('Hello, this is a modified Caesar cipher') "d>**-1z6&'5z'5z:z+-='$'>=zp:>5:#z<'.&>#" """ encoded_message = "" # encoding shift like Caesar cipher algorithm implementing positive shift or # forward shift or right shift for i in plaintext: position = self.__key_list.index(i) encoded_message += self.__key_list[ (position + self.__shift_key) % len(self.__key_list) ] return encoded_message def test_end_to_end(msg: str = "Hello, this is a modified Caesar cipher") -> str: """ >>> test_end_to_end() 'Hello, this is a modified Caesar cipher' """ cip1 = ShuffledShiftCipher() return cip1.decrypt(cip1.encrypt(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/ciphers/mixed_keyword_cypher.py
ciphers/mixed_keyword_cypher.py
from string import ascii_uppercase def mixed_keyword( keyword: str, plaintext: str, verbose: bool = False, alphabet: str = ascii_uppercase ) -> str: """ For keyword: hello H E L O A B C D F G I J K M N P Q R S T U V W X Y Z and map vertically >>> mixed_keyword("college", "UNIVERSITY", True) # doctest: +NORMALIZE_WHITESPACE {'A': 'C', 'B': 'A', 'C': 'I', 'D': 'P', 'E': 'U', 'F': 'Z', 'G': 'O', 'H': 'B', 'I': 'J', 'J': 'Q', 'K': 'V', 'L': 'L', 'M': 'D', 'N': 'K', 'O': 'R', 'P': 'W', 'Q': 'E', 'R': 'F', 'S': 'M', 'T': 'S', 'U': 'X', 'V': 'G', 'W': 'H', 'X': 'N', 'Y': 'T', 'Z': 'Y'} 'XKJGUFMJST' >>> mixed_keyword("college", "UNIVERSITY", False) # doctest: +NORMALIZE_WHITESPACE 'XKJGUFMJST' """ keyword = keyword.upper() plaintext = plaintext.upper() alphabet_set = set(alphabet) # create a list of unique characters in the keyword - their order matters # it determines how we will map plaintext characters to the ciphertext unique_chars = [] for char in keyword: if char in alphabet_set and char not in unique_chars: unique_chars.append(char) # the number of those unique characters will determine the number of rows num_unique_chars_in_keyword = len(unique_chars) # create a shifted version of the alphabet shifted_alphabet = unique_chars + [ char for char in alphabet if char not in unique_chars ] # create a modified alphabet by splitting the shifted alphabet into rows modified_alphabet = [ shifted_alphabet[k : k + num_unique_chars_in_keyword] for k in range(0, 26, num_unique_chars_in_keyword) ] # map the alphabet characters to the modified alphabet characters # going 'vertically' through the modified alphabet - consider columns first mapping = {} letter_index = 0 for column in range(num_unique_chars_in_keyword): for row in modified_alphabet: # if current row (the last one) is too short, break out of loop if len(row) <= column: break # map current letter to letter in modified alphabet mapping[alphabet[letter_index]] = row[column] letter_index += 1 if verbose: print(mapping) # create the encrypted text by mapping the plaintext to the modified alphabet return "".join(mapping.get(char, char) for char in plaintext) if __name__ == "__main__": # example use print(mixed_keyword("college", "UNIVERSITY"))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/transposition_cipher.py
ciphers/transposition_cipher.py
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 the ROUTE cipher. """ def main() -> None: message = input("Enter message: ") key = int(input(f"Enter key [2-{len(message) - 1}]: ")) mode = input("Encryption/Decryption [e/d]: ") if mode.lower().startswith("e"): text = encrypt_message(key, message) elif mode.lower().startswith("d"): text = decrypt_message(key, message) # Append pipe symbol (vertical bar) to identify spaces at the end. print(f"Output:\n{text + '|'}") def encrypt_message(key: int, message: str) -> str: """ >>> encrypt_message(6, 'Harshil Darji') 'Hlia rDsahrij' """ cipher_text = [""] * key for col in range(key): pointer = col while pointer < len(message): cipher_text[col] += message[pointer] pointer += key return "".join(cipher_text) def decrypt_message(key: int, message: str) -> str: """ >>> decrypt_message(6, 'Hlia rDsahrij') 'Harshil Darji' """ num_cols = math.ceil(len(message) / key) num_rows = key num_shaded_boxes = (num_cols * num_rows) - len(message) plain_text = [""] * num_cols col = 0 row = 0 for symbol in message: plain_text[col] += symbol col += 1 if (col == num_cols) or ( (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): col = 0 row += 1 return "".join(plain_text) 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/ciphers/rsa_cipher.py
ciphers/rsa_cipher.py
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), block_size): block_int = 0 for i in range(block_start, min(block_start + block_size, len(message_bytes))): block_int += message_bytes[i] * (BYTE_SIZE ** (i % block_size)) block_ints.append(block_int) return block_ints def get_text_from_blocks( block_ints: list[int], message_length: int, block_size: int = DEFAULT_BLOCK_SIZE ) -> str: message: list[str] = [] for block_int in block_ints: block_message: list[str] = [] for i in range(block_size - 1, -1, -1): if len(message) + i < message_length: ascii_number = block_int // (BYTE_SIZE**i) block_int = block_int % (BYTE_SIZE**i) block_message.insert(0, chr(ascii_number)) message.extend(block_message) return "".join(message) def encrypt_message( message: str, key: tuple[int, int], block_size: int = DEFAULT_BLOCK_SIZE ) -> list[int]: encrypted_blocks = [] n, e = key for block in get_blocks_from_text(message, block_size): encrypted_blocks.append(pow(block, e, n)) return encrypted_blocks def decrypt_message( encrypted_blocks: list[int], message_length: int, key: tuple[int, int], block_size: int = DEFAULT_BLOCK_SIZE, ) -> str: decrypted_blocks = [] n, d = key for block in encrypted_blocks: decrypted_blocks.append(pow(block, d, n)) return get_text_from_blocks(decrypted_blocks, message_length, block_size) def read_key_file(key_filename: str) -> tuple[int, int, int]: with open(key_filename) as fo: content = fo.read() key_size, n, eor_d = content.split(",") return (int(key_size), int(n), int(eor_d)) def encrypt_and_write_to_file( message_filename: str, key_filename: str, message: str, block_size: int = DEFAULT_BLOCK_SIZE, ) -> str: key_size, n, e = read_key_file(key_filename) if key_size < block_size * 8: sys.exit( f"ERROR: Block size is {block_size * 8} bits and key size is {key_size} " "bits. The RSA cipher requires the block size to be equal to or greater " "than the key size. Either decrease the block size or use different keys." ) encrypted_blocks = [str(i) for i in encrypt_message(message, (n, e), block_size)] encrypted_content = ",".join(encrypted_blocks) encrypted_content = f"{len(message)}_{block_size}_{encrypted_content}" with open(message_filename, "w") as fo: fo.write(encrypted_content) return encrypted_content def read_from_file_and_decrypt(message_filename: str, key_filename: str) -> str: key_size, n, d = read_key_file(key_filename) with open(message_filename) as fo: content = fo.read() message_length_str, block_size_str, encrypted_message = content.split("_") message_length = int(message_length_str) block_size = int(block_size_str) if key_size < block_size * 8: sys.exit( f"ERROR: Block size is {block_size * 8} bits and key size is {key_size} " "bits. The RSA cipher requires the block size to be equal to or greater " "than the key size. Were the correct key file and encrypted file specified?" ) encrypted_blocks = [] for block in encrypted_message.split(","): encrypted_blocks.append(int(block)) return decrypt_message(encrypted_blocks, message_length, (n, d), block_size) def main() -> None: filename = "encrypted_file.txt" response = input(r"Encrypt\Decrypt [e\d]: ") if response.lower().startswith("e"): mode = "encrypt" elif response.lower().startswith("d"): mode = "decrypt" if mode == "encrypt": if not os.path.exists("rsa_pubkey.txt"): rkg.make_key_files("rsa", 1024) message = input("\nEnter message: ") pubkey_filename = "rsa_pubkey.txt" print(f"Encrypting and writing to {filename}...") encrypted_text = encrypt_and_write_to_file(filename, pubkey_filename, message) print("\nEncrypted text:") print(encrypted_text) elif mode == "decrypt": privkey_filename = "rsa_privkey.txt" print(f"Reading from {filename} and decrypting...") decrypted_text = read_from_file_and_decrypt(filename, privkey_filename) print("writing decryption to rsa_decryption.txt...") with open("rsa_decryption.txt", "w") as dec: dec.write(decrypted_text) print("\nDecryption:") print(decrypted_text) if __name__ == "__main__": main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/gronsfeld_cipher.py
ciphers/gronsfeld_cipher.py
from string import ascii_uppercase def gronsfeld(text: str, key: str) -> str: """ Encrypt plaintext with the Gronsfeld cipher >>> gronsfeld('hello', '412') 'LFNPP' >>> gronsfeld('hello', '123') 'IGOMQ' >>> gronsfeld('', '123') '' >>> gronsfeld('yes, ¥€$ - _!@#%?', '0') 'YES, ¥€$ - _!@#%?' >>> gronsfeld('yes, ¥€$ - _!@#%?', '01') 'YFS, ¥€$ - _!@#%?' >>> gronsfeld('yes, ¥€$ - _!@#%?', '012') 'YFU, ¥€$ - _!@#%?' >>> gronsfeld('yes, ¥€$ - _!@#%?', '') Traceback (most recent call last): ... ZeroDivisionError: division by zero """ ascii_len = len(ascii_uppercase) key_len = len(key) encrypted_text = "" keys = [int(char) for char in key] upper_case_text = text.upper() for i, char in enumerate(upper_case_text): if char in ascii_uppercase: new_position = (ascii_uppercase.index(char) + keys[i % key_len]) % ascii_len shifted_letter = ascii_uppercase[new_position] encrypted_text += shifted_letter else: encrypted_text += char return encrypted_text 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/ciphers/baconian_cipher.py
ciphers/baconian_cipher.py
""" Program to encode and decode Baconian or Bacon's Cipher Wikipedia reference : https://en.wikipedia.org/wiki/Bacon%27s_cipher """ encode_dict = { "a": "AAAAA", "b": "AAAAB", "c": "AAABA", "d": "AAABB", "e": "AABAA", "f": "AABAB", "g": "AABBA", "h": "AABBB", "i": "ABAAA", "j": "BBBAA", "k": "ABAAB", "l": "ABABA", "m": "ABABB", "n": "ABBAA", "o": "ABBAB", "p": "ABBBA", "q": "ABBBB", "r": "BAAAA", "s": "BAAAB", "t": "BAABA", "u": "BAABB", "v": "BBBAB", "w": "BABAA", "x": "BABAB", "y": "BABBA", "z": "BABBB", " ": " ", } decode_dict = {value: key for key, value in encode_dict.items()} def encode(word: str) -> str: """ Encodes to Baconian cipher >>> encode("hello") 'AABBBAABAAABABAABABAABBAB' >>> encode("hello world") 'AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB' >>> encode("hello world!") Traceback (most recent call last): ... Exception: encode() accepts only letters of the alphabet and spaces """ encoded = "" for letter in word.lower(): if letter.isalpha() or letter == " ": encoded += encode_dict[letter] else: raise Exception("encode() accepts only letters of the alphabet and spaces") return encoded def decode(coded: str) -> str: """ Decodes from Baconian cipher >>> decode("AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB") 'hello world' >>> decode("AABBBAABAAABABAABABAABBAB") 'hello' >>> decode("AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB!") Traceback (most recent call last): ... Exception: decode() accepts only 'A', 'B' and spaces """ if set(coded) - {"A", "B", " "} != set(): raise Exception("decode() accepts only 'A', 'B' and spaces") decoded = "" for word in coded.split(): while len(word) != 0: decoded += decode_dict[word[:5]] word = word[5:] decoded += " " return decoded.strip() 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/audio_filters/show_response.py
audio_filters/show_response.py
from __future__ import annotations from abc import abstractmethod from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class FilterType(Protocol): @abstractmethod def process(self, sample: float) -> float: """ Calculate y[n] >>> issubclass(FilterType, Protocol) True """ def get_bounds( fft_results: np.ndarray, samplerate: int ) -> tuple[int | float, int | float]: """ Get bounds for printing fft results >>> import numpy >>> array = numpy.linspace(-20.0, 20.0, 1000) >>> get_bounds(array, 1000) (-20, 20) """ lowest = min([-20, np.min(fft_results[1 : samplerate // 2 - 1])]) highest = max([20, np.max(fft_results[1 : samplerate // 2 - 1])]) return lowest, highest def show_frequency_response(filter_type: FilterType, samplerate: int) -> None: """ Show frequency response of a filter >>> from audio_filters.iir_filter import IIRFilter >>> filt = IIRFilter(4) >>> show_frequency_response(filt, 48000) """ size = 512 inputs = [1] + [0] * (size - 1) outputs = [filter_type.process(item) for item in inputs] filler = [0] * (samplerate - size) # zero-padding outputs += filler fft_out = np.abs(np.fft.fft(outputs)) fft_db = 20 * np.log10(fft_out) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24, samplerate / 2 - 1) plt.xlabel("Frequency (Hz)") plt.xscale("log") # Display within reasonable bounds bounds = get_bounds(fft_db, samplerate) plt.ylim(max([-80, bounds[0]]), min([80, bounds[1]])) plt.ylabel("Gain (dB)") plt.plot(fft_db) plt.show() def show_phase_response(filter_type: FilterType, samplerate: int) -> None: """ Show phase response of a filter >>> from audio_filters.iir_filter import IIRFilter >>> filt = IIRFilter(4) >>> show_phase_response(filt, 48000) """ size = 512 inputs = [1] + [0] * (size - 1) outputs = [filter_type.process(item) for item in inputs] filler = [0] * (samplerate - size) # zero-padding outputs += filler fft_out = np.angle(np.fft.fft(outputs)) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24, samplerate / 2 - 1) plt.xlabel("Frequency (Hz)") plt.xscale("log") plt.ylim(-2 * pi, 2 * pi) plt.ylabel("Phase shift (Radians)") plt.plot(np.unwrap(fft_out, -2 * pi)) plt.show()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/audio_filters/__init__.py
audio_filters/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/audio_filters/butterworth_filter.py
audio_filters/butterworth_filter.py
from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter """ Create 2nd-order IIR filters with Butterworth design. Code based on https://webaudio.github.io/Audio-EQ-Cookbook/audio-eq-cookbook.html Alternatively you can use scipy.signal.butter, which should yield the same results. """ def make_lowpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2), ) -> IIRFilter: """ Creates a low-pass filter >>> filter = make_lowpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.004277569313094809, 0.008555138626189618, 0.004277569313094809] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = (1 - _cos) / 2 b1 = 1 - _cos a0 = 1 + alpha a1 = -2 * _cos a2 = 1 - alpha filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b0]) return filt def make_highpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2), ) -> IIRFilter: """ Creates a high-pass filter >>> filter = make_highpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.9957224306869052, -1.9914448613738105, 0.9957224306869052] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = (1 + _cos) / 2 b1 = -1 - _cos a0 = 1 + alpha a1 = -2 * _cos a2 = 1 - alpha filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b0]) return filt def make_bandpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2), ) -> IIRFilter: """ Creates a band-pass filter >>> filter = make_bandpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.06526309611002579, 0, -0.06526309611002579] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = _sin / 2 b1 = 0 b2 = -b0 a0 = 1 + alpha a1 = -2 * _cos a2 = 1 - alpha filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt def make_allpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2), ) -> IIRFilter: """ Creates an all-pass filter >>> filter = make_allpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.9077040443587427, -1.9828897227476208, 1.0922959556412573] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = 1 - alpha b1 = -2 * _cos b2 = 1 + alpha filt = IIRFilter(2) filt.set_coefficients([b2, b1, b0], [b0, b1, b2]) return filt def make_peak( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2), ) -> IIRFilter: """ Creates a peak filter >>> filter = make_peak(1000, 48000, 6) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0653405327119334, -1.9828897227476208, 0.9346594672880666, 1.1303715025601122, -1.9828897227476208, 0.8696284974398878] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) big_a = 10 ** (gain_db / 40) b0 = 1 + alpha * big_a b1 = -2 * _cos b2 = 1 - alpha * big_a a0 = 1 + alpha / big_a a1 = -2 * _cos a2 = 1 - alpha / big_a filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt def make_lowshelf( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2), ) -> IIRFilter: """ Creates a low-shelf filter >>> filter = make_lowshelf(1000, 48000, 6) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [3.0409336710888786, -5.608870992220748, 2.602157875636628, 3.139954022810743, -5.591841778072785, 2.5201667380627257] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) big_a = 10 ** (gain_db / 40) pmc = (big_a + 1) - (big_a - 1) * _cos ppmc = (big_a + 1) + (big_a - 1) * _cos mpc = (big_a - 1) - (big_a + 1) * _cos pmpc = (big_a - 1) + (big_a + 1) * _cos aa2 = 2 * sqrt(big_a) * alpha b0 = big_a * (pmc + aa2) b1 = 2 * big_a * mpc b2 = big_a * (pmc - aa2) a0 = ppmc + aa2 a1 = -2 * pmpc a2 = ppmc - aa2 filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt def make_highshelf( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2), ) -> IIRFilter: """ Creates a high-shelf filter >>> filter = make_highshelf(1000, 48000, 6) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [2.2229172136088806, -3.9587208137297303, 1.7841414181566304, 4.295432981120543, -7.922740859457287, 3.6756456963725253] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) big_a = 10 ** (gain_db / 40) pmc = (big_a + 1) - (big_a - 1) * _cos ppmc = (big_a + 1) + (big_a - 1) * _cos mpc = (big_a - 1) - (big_a + 1) * _cos pmpc = (big_a - 1) + (big_a + 1) * _cos aa2 = 2 * sqrt(big_a) * alpha b0 = big_a * (ppmc + aa2) b1 = -2 * big_a * pmpc b2 = big_a * (ppmc - aa2) a0 = pmc + aa2 a1 = 2 * mpc a2 = pmc - aa2 filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/audio_filters/iir_filter.py
audio_filters/iir_filter.py
from __future__ import annotations class IIRFilter: r""" N-Order IIR filter Assumes working with float samples normalized on [-1, 1] --- Implementation details: Based on the 2nd-order function from https://en.wikipedia.org/wiki/Digital_biquad_filter, this generalized N-order function was made. Using the following transfer function .. math:: H(z)=\frac{b_{0}+b_{1}z^{-1}+b_{2}z^{-2}+...+b_{k}z^{-k}} {a_{0}+a_{1}z^{-1}+a_{2}z^{-2}+...+a_{k}z^{-k}} we can rewrite this to .. math:: y[n]={\frac{1}{a_{0}}} \left(\left(b_{0}x[n]+b_{1}x[n-1]+b_{2}x[n-2]+...+b_{k}x[n-k]\right)- \left(a_{1}y[n-1]+a_{2}y[n-2]+...+a_{k}y[n-k]\right)\right) """ def __init__(self, order: int) -> None: self.order = order # a_{0} ... a_{k} self.a_coeffs = [1.0] + [0.0] * order # b_{0} ... b_{k} self.b_coeffs = [1.0] + [0.0] * order # x[n-1] ... x[n-k] self.input_history = [0.0] * self.order # y[n-1] ... y[n-k] self.output_history = [0.0] * self.order def set_coefficients(self, a_coeffs: list[float], b_coeffs: list[float]) -> None: """ Set the coefficients for the IIR filter. These should both be of size `order` + 1. :math:`a_0` may be left out, and it will use 1.0 as default value. This method works well with scipy's filter design functions >>> # Make a 2nd-order 1000Hz butterworth lowpass filter >>> import scipy.signal >>> b_coeffs, a_coeffs = scipy.signal.butter(2, 1000, ... btype='lowpass', ... fs=48000) >>> filt = IIRFilter(2) >>> filt.set_coefficients(a_coeffs, b_coeffs) """ if len(a_coeffs) < self.order: a_coeffs = [1.0, *a_coeffs] if len(a_coeffs) != self.order + 1: msg = ( f"Expected a_coeffs to have {self.order + 1} elements " f"for {self.order}-order filter, got {len(a_coeffs)}" ) raise ValueError(msg) if len(b_coeffs) != self.order + 1: msg = ( f"Expected b_coeffs to have {self.order + 1} elements " f"for {self.order}-order filter, got {len(a_coeffs)}" ) raise ValueError(msg) self.a_coeffs = a_coeffs self.b_coeffs = b_coeffs def process(self, sample: float) -> float: """ Calculate :math:`y[n]` >>> filt = IIRFilter(2) >>> filt.process(0) 0.0 """ result = 0.0 # Start at index 1 and do index 0 at the end. for i in range(1, self.order + 1): result += ( self.b_coeffs[i] * self.input_history[i - 1] - self.a_coeffs[i] * self.output_history[i - 1] ) result = (result + self.b_coeffs[0] * sample) / self.a_coeffs[0] self.input_history[1:] = self.input_history[:-1] self.output_history[1:] = self.output_history[:-1] self.input_history[0] = sample self.output_history[0] = result return result
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/test_digital_image_processing.py
digital_image_processing/test_digital_image_processing.py
""" PyTest's for Digital Image Processing """ import numpy as np from cv2 import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uint8 from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs img = imread(r"digital_image_processing/image_data/lena_small.jpg") gray = cvtColor(img, COLOR_BGR2GRAY) # Test: convert_to_negative() def test_convert_to_negative(): negative_img = cn.convert_to_negative(img) # assert negative_img array for at least one True assert negative_img.any() # Test: change_contrast() def test_change_contrast(): with Image.open("digital_image_processing/image_data/lena_small.jpg") as img: # Work around assertion for response assert str(cc.change_contrast(img, 110)).startswith( "<PIL.Image.Image image mode=RGB size=100x100 at" ) # canny.gen_gaussian_kernel() def test_gen_gaussian_kernel(): resp = canny.gen_gaussian_kernel(9, sigma=1.4) # Assert ambiguous array assert resp.all() # canny.py def test_canny(): canny_img = imread("digital_image_processing/image_data/lena_small.jpg", 0) # assert ambiguous array for all == True assert canny_img.all() canny_array = canny.canny(canny_img) # assert canny array for at least one True assert canny_array.any() # filters/gaussian_filter.py def test_gen_gaussian_kernel_filter(): assert gg.gaussian_filter(gray, 5, sigma=0.9).all() def test_convolve_filter(): # laplace diagonals laplace = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]]) res = conv.img_convolve(gray, laplace).astype(uint8) assert res.any() def test_median_filter(): assert med.median_filter(gray, 3).any() def test_sobel_filter(): grad, theta = sob.sobel_filter(gray) assert grad.any() assert theta.any() def test_sepia(): sepia = sp.make_sepia(img, 20) assert sepia.all() def test_burkes(file_path: str = "digital_image_processing/image_data/lena_small.jpg"): burkes = bs.Burkes(imread(file_path, 1), 120) burkes.process() assert burkes.output_img.any() def test_nearest_neighbour( file_path: str = "digital_image_processing/image_data/lena_small.jpg", ): nn = rs.NearestNeighbour(imread(file_path, 1), 400, 200) nn.process() assert nn.output.any() def test_local_binary_pattern(): # pull request 10161 before: # "digital_image_processing/image_data/lena.jpg" # after: "digital_image_processing/image_data/lena_small.jpg" from os import getenv # Speed up our Continuous Integration tests file_name = "lena_small.jpg" if getenv("CI") else "lena.jpg" file_path = f"digital_image_processing/image_data/{file_name}" # Reading the image and converting it to grayscale image = imread(file_path, 0) # Test for get_neighbors_pixel function() return not None x_coordinate = 0 y_coordinate = 0 center = image[x_coordinate][y_coordinate] neighbors_pixels = lbp.get_neighbors_pixel( image, x_coordinate, y_coordinate, center ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image lbp_image = np.zeros((image.shape[0], image.shape[1])) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(image.shape[0]): for j in range(image.shape[1]): lbp_image[i][j] = lbp.local_binary_value(image, i, j) assert lbp_image.any()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/change_brightness.py
digital_image_processing/change_brightness.py
from PIL import Image def change_brightness(img: Image, level: float) -> Image: """ Change the brightness of a PIL Image to a given level. """ def brightness(c: int) -> float: """ Fundamental Transformation/Operation that'll be performed on every bit. """ return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError("level must be between -255.0 (black) and 255.0 (white)") return img.point(brightness) if __name__ == "__main__": # Load image with Image.open("image_data/lena.jpg") as img: # Change brightness to 100 brigt_img = change_brightness(img, 100) brigt_img.save("image_data/lena_brightness.png", format="png")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/change_contrast.py
digital_image_processing/change_contrast.py
""" Changing contrast with PIL This algorithm is used in https://noivce.pythonanywhere.com/ Python web app. psf/black: True ruff : True """ from PIL import Image def change_contrast(img: Image, level: int) -> Image: """ Function to change contrast """ factor = (259 * (level + 255)) / (255 * (259 - level)) def contrast(c: int) -> int: """ Fundamental Transformation/Operation that'll be performed on every bit. """ return int(128 + factor * (c - 128)) return img.point(contrast) if __name__ == "__main__": # Load image with Image.open("image_data/lena.jpg") as img: # Change contrast to 170 cont_img = change_contrast(img, 170) cont_img.save("image_data/lena_high_contrast.png", format="png")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/__init__.py
digital_image_processing/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/sepia.py
digital_image_processing/sepia.py
""" Implemented an algorithm using opencv to tone an image with sepia technique """ from cv2 import destroyAllWindows, imread, imshow, waitKey def make_sepia(img, factor: int): """ Function create sepia tone. Source: https://en.wikipedia.org/wiki/Sepia_(color) """ pixel_h, pixel_v = img.shape[0], img.shape[1] def to_grayscale(blue, green, red): """ Helper function to create pixel's greyscale representation Src: https://pl.wikipedia.org/wiki/YUV """ return 0.2126 * red + 0.587 * green + 0.114 * blue def normalize(value): """Helper function to normalize R/G/B value -> return 255 if value > 255""" return min(value, 255) for i in range(pixel_h): for j in range(pixel_v): greyscale = int(to_grayscale(*img[i][j])) img[i][j] = [ normalize(greyscale), normalize(greyscale + factor), normalize(greyscale + 2 * factor), ] return img if __name__ == "__main__": # read original image images = { percentage: imread("image_data/lena.jpg", 1) for percentage in (10, 20, 30, 40) } for percentage, img in images.items(): make_sepia(img, percentage) for percentage, img in images.items(): imshow(f"Original image with sepia (factor: {percentage})", img) waitKey(0) destroyAllWindows()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/index_calculation.py
digital_image_processing/index_calculation.py
# Author: João Gustavo A. Amorim # Author email: joaogustavoamorim@gmail.com # Coding date: jan 2019 # python/black: True # Imports import numpy as np # Class implemented to calculus the index class IndexCalculation: """ # Class Summary This algorithm consists in calculating vegetation indices, these indices can be used for precision agriculture for example (or remote sensing). There are functions to define the data and to calculate the implemented indices. # Vegetation index https://en.wikipedia.org/wiki/Vegetation_Index A Vegetation Index (VI) is a spectral transformation of two or more bands designed to enhance the contribution of vegetation properties and allow reliable spatial and temporal inter-comparisons of terrestrial photosynthetic activity and canopy structural variations # Information about channels (Wavelength range for each) * nir - near-infrared https://www.malvernpanalytical.com/br/products/technology/near-infrared-spectroscopy Wavelength Range 700 nm to 2500 nm * Red Edge https://en.wikipedia.org/wiki/Red_edge Wavelength Range 680 nm to 730 nm * red https://en.wikipedia.org/wiki/Color Wavelength Range 635 nm to 700 nm * blue https://en.wikipedia.org/wiki/Color Wavelength Range 450 nm to 490 nm * green https://en.wikipedia.org/wiki/Color Wavelength Range 520 nm to 560 nm # Implemented index list #"abbreviationOfIndexName" -- list of channels used #"ARVI2" -- red, nir #"CCCI" -- red, redEdge, nir #"CVI" -- red, green, nir #"GLI" -- red, green, blue #"NDVI" -- red, nir #"BNDVI" -- blue, nir #"redEdgeNDVI" -- red, redEdge #"GNDVI" -- green, nir #"GBNDVI" -- green, blue, nir #"GRNDVI" -- red, green, nir #"RBNDVI" -- red, blue, nir #"PNDVI" -- red, green, blue, nir #"ATSAVI" -- red, nir #"BWDRVI" -- blue, nir #"CIgreen" -- green, nir #"CIrededge" -- redEdge, nir #"CI" -- red, blue #"CTVI" -- red, nir #"GDVI" -- green, nir #"EVI" -- red, blue, nir #"GEMI" -- red, nir #"GOSAVI" -- green, nir #"GSAVI" -- green, nir #"Hue" -- red, green, blue #"IVI" -- red, nir #"IPVI" -- red, nir #"I" -- red, green, blue #"RVI" -- red, nir #"MRVI" -- red, nir #"MSAVI" -- red, nir #"NormG" -- red, green, nir #"NormNIR" -- red, green, nir #"NormR" -- red, green, nir #"NGRDI" -- red, green #"RI" -- red, green #"S" -- red, green, blue #"IF" -- red, green, blue #"DVI" -- red, nir #"TVI" -- red, nir #"NDRE" -- redEdge, nir #list of all index implemented #allIndex = ["ARVI2", "CCCI", "CVI", "GLI", "NDVI", "BNDVI", "redEdgeNDVI", "GNDVI", "GBNDVI", "GRNDVI", "RBNDVI", "PNDVI", "ATSAVI", "BWDRVI", "CIgreen", "CIrededge", "CI", "CTVI", "GDVI", "EVI", "GEMI", "GOSAVI", "GSAVI", "Hue", "IVI", "IPVI", "I", "RVI", "MRVI", "MSAVI", "NormG", "NormNIR", "NormR", "NGRDI", "RI", "S", "IF", "DVI", "TVI", "NDRE"] #list of index with not blue channel #notBlueIndex = ["ARVI2", "CCCI", "CVI", "NDVI", "redEdgeNDVI", "GNDVI", "GRNDVI", "ATSAVI", "CIgreen", "CIrededge", "CTVI", "GDVI", "GEMI", "GOSAVI", "GSAVI", "IVI", "IPVI", "RVI", "MRVI", "MSAVI", "NormG", "NormNIR", "NormR", "NGRDI", "RI", "DVI", "TVI", "NDRE"] #list of index just with RGB channels #RGBIndex = ["GLI", "CI", "Hue", "I", "NGRDI", "RI", "S", "IF"] """ def __init__(self, red=None, green=None, blue=None, red_edge=None, nir=None): self.set_matricies(red=red, green=green, blue=blue, red_edge=red_edge, nir=nir) def set_matricies(self, red=None, green=None, blue=None, red_edge=None, nir=None): if red is not None: self.red = red if green is not None: self.green = green if blue is not None: self.blue = blue if red_edge is not None: self.redEdge = red_edge if nir is not None: self.nir = nir return True def calculation( self, index="", red=None, green=None, blue=None, red_edge=None, nir=None ): """ performs the calculation of the index with the values instantiated in the class :str index: abbreviation of index name to perform """ self.set_matricies(red=red, green=green, blue=blue, red_edge=red_edge, nir=nir) funcs = { "ARVI2": self.arv12, "CCCI": self.ccci, "CVI": self.cvi, "GLI": self.gli, "NDVI": self.ndvi, "BNDVI": self.bndvi, "redEdgeNDVI": self.red_edge_ndvi, "GNDVI": self.gndvi, "GBNDVI": self.gbndvi, "GRNDVI": self.grndvi, "RBNDVI": self.rbndvi, "PNDVI": self.pndvi, "ATSAVI": self.atsavi, "BWDRVI": self.bwdrvi, "CIgreen": self.ci_green, "CIrededge": self.ci_rededge, "CI": self.ci, "CTVI": self.ctvi, "GDVI": self.gdvi, "EVI": self.evi, "GEMI": self.gemi, "GOSAVI": self.gosavi, "GSAVI": self.gsavi, "Hue": self.hue, "IVI": self.ivi, "IPVI": self.ipvi, "I": self.i, "RVI": self.rvi, "MRVI": self.mrvi, "MSAVI": self.m_savi, "NormG": self.norm_g, "NormNIR": self.norm_nir, "NormR": self.norm_r, "NGRDI": self.ngrdi, "RI": self.ri, "S": self.s, "IF": self._if, "DVI": self.dvi, "TVI": self.tvi, "NDRE": self.ndre, } try: return funcs[index]() except KeyError: print("Index not in the list!") return False def arv12(self): """ Atmospherically Resistant Vegetation Index 2 https://www.indexdatabase.de/db/i-single.php?id=396 :return: index -0.18+1.17*(self.nir-self.red)/(self.nir+self.red) """ return -0.18 + (1.17 * ((self.nir - self.red) / (self.nir + self.red))) def ccci(self): """ Canopy Chlorophyll Content Index https://www.indexdatabase.de/db/i-single.php?id=224 :return: index """ return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / ( (self.nir - self.red) / (self.nir + self.red) ) def cvi(self): """ Chlorophyll vegetation index https://www.indexdatabase.de/db/i-single.php?id=391 :return: index """ return self.nir * (self.red / (self.green**2)) def gli(self): """ self.green leaf index https://www.indexdatabase.de/db/i-single.php?id=375 :return: index """ return (2 * self.green - self.red - self.blue) / ( 2 * self.green + self.red + self.blue ) def ndvi(self): """ Normalized Difference self.nir/self.red Normalized Difference Vegetation Index, Calibrated NDVI - CDVI https://www.indexdatabase.de/db/i-single.php?id=58 :return: index """ return (self.nir - self.red) / (self.nir + self.red) def bndvi(self): """ Normalized Difference self.nir/self.blue self.blue-normalized difference vegetation index https://www.indexdatabase.de/db/i-single.php?id=135 :return: index """ return (self.nir - self.blue) / (self.nir + self.blue) def red_edge_ndvi(self): """ Normalized Difference self.rededge/self.red https://www.indexdatabase.de/db/i-single.php?id=235 :return: index """ return (self.redEdge - self.red) / (self.redEdge + self.red) def gndvi(self): """ Normalized Difference self.nir/self.green self.green NDVI https://www.indexdatabase.de/db/i-single.php?id=401 :return: index """ return (self.nir - self.green) / (self.nir + self.green) def gbndvi(self): """ self.green-self.blue NDVI https://www.indexdatabase.de/db/i-single.php?id=186 :return: index """ return (self.nir - (self.green + self.blue)) / ( self.nir + (self.green + self.blue) ) def grndvi(self): """ self.green-self.red NDVI https://www.indexdatabase.de/db/i-single.php?id=185 :return: index """ return (self.nir - (self.green + self.red)) / ( self.nir + (self.green + self.red) ) def rbndvi(self): """ self.red-self.blue NDVI https://www.indexdatabase.de/db/i-single.php?id=187 :return: index """ return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red)) def pndvi(self): """ Pan NDVI https://www.indexdatabase.de/db/i-single.php?id=188 :return: index """ return (self.nir - (self.green + self.red + self.blue)) / ( self.nir + (self.green + self.red + self.blue) ) def atsavi(self, x=0.08, a=1.22, b=0.03): """ Adjusted transformed soil-adjusted VI https://www.indexdatabase.de/db/i-single.php?id=209 :return: index """ return a * ( (self.nir - a * self.red - b) / (a * self.nir + self.red - a * b + x * (1 + a**2)) ) def bwdrvi(self): """ self.blue-wide dynamic range vegetation index https://www.indexdatabase.de/db/i-single.php?id=136 :return: index """ return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue) def ci_green(self): """ Chlorophyll Index self.green https://www.indexdatabase.de/db/i-single.php?id=128 :return: index """ return (self.nir / self.green) - 1 def ci_rededge(self): """ Chlorophyll Index self.redEdge https://www.indexdatabase.de/db/i-single.php?id=131 :return: index """ return (self.nir / self.redEdge) - 1 def ci(self): """ Coloration Index https://www.indexdatabase.de/db/i-single.php?id=11 :return: index """ return (self.red - self.blue) / self.red def ctvi(self): """ Corrected Transformed Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=244 :return: index """ ndvi = self.ndvi() return ((ndvi + 0.5) / (abs(ndvi + 0.5))) * (abs(ndvi + 0.5) ** (1 / 2)) def gdvi(self): """ Difference self.nir/self.green self.green Difference Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=27 :return: index """ return self.nir - self.green def evi(self): """ Enhanced Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=16 :return: index """ return 2.5 * ( (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1) ) def gemi(self): """ Global Environment Monitoring Index https://www.indexdatabase.de/db/i-single.php?id=25 :return: index """ n = (2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / ( self.nir + self.red + 0.5 ) return n * (1 - 0.25 * n) - (self.red - 0.125) / (1 - self.red) def gosavi(self, y=0.16): """ self.green Optimized Soil Adjusted Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=29 mit Y = 0,16 :return: index """ return (self.nir - self.green) / (self.nir + self.green + y) def gsavi(self, n=0.5): """ self.green Soil Adjusted Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=31 mit N = 0,5 :return: index """ return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n) def hue(self): """ Hue https://www.indexdatabase.de/db/i-single.php?id=34 :return: index """ return np.arctan( ((2 * self.red - self.green - self.blue) / 30.5) * (self.green - self.blue) ) def ivi(self, a=None, b=None): """ Ideal vegetation index https://www.indexdatabase.de/db/i-single.php?id=276 b=intercept of vegetation line a=soil line slope :return: index """ return (self.nir - b) / (a * self.red) def ipvi(self): """ Infraself.red percentage vegetation index https://www.indexdatabase.de/db/i-single.php?id=35 :return: index """ return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1) def i(self): """ Intensity https://www.indexdatabase.de/db/i-single.php?id=36 :return: index """ return (self.red + self.green + self.blue) / 30.5 def rvi(self): """ Ratio-Vegetation-Index http://www.seos-project.eu/modules/remotesensing/remotesensing-c03-s01-p01.html :return: index """ return self.nir / self.red def mrvi(self): """ Modified Normalized Difference Vegetation Index RVI https://www.indexdatabase.de/db/i-single.php?id=275 :return: index """ return (self.rvi() - 1) / (self.rvi() + 1) def m_savi(self): """ Modified Soil Adjusted Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=44 :return: index """ return ( (2 * self.nir + 1) - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2) ) / 2 def norm_g(self): """ Norm G https://www.indexdatabase.de/db/i-single.php?id=50 :return: index """ return self.green / (self.nir + self.red + self.green) def norm_nir(self): """ Norm self.nir https://www.indexdatabase.de/db/i-single.php?id=51 :return: index """ return self.nir / (self.nir + self.red + self.green) def norm_r(self): """ Norm R https://www.indexdatabase.de/db/i-single.php?id=52 :return: index """ return self.red / (self.nir + self.red + self.green) def ngrdi(self): """ Normalized Difference self.green/self.red Normalized self.green self.red difference index, Visible Atmospherically Resistant Indices self.green (VIself.green) https://www.indexdatabase.de/db/i-single.php?id=390 :return: index """ return (self.green - self.red) / (self.green + self.red) def ri(self): """ Normalized Difference self.red/self.green self.redness Index https://www.indexdatabase.de/db/i-single.php?id=74 :return: index """ return (self.red - self.green) / (self.red + self.green) def s(self): """ Saturation https://www.indexdatabase.de/db/i-single.php?id=77 :return: index """ max_value = np.max([np.max(self.red), np.max(self.green), np.max(self.blue)]) min_value = np.min([np.min(self.red), np.min(self.green), np.min(self.blue)]) return (max_value - min_value) / max_value def _if(self): """ Shape Index https://www.indexdatabase.de/db/i-single.php?id=79 :return: index """ return (2 * self.red - self.green - self.blue) / (self.green - self.blue) def dvi(self): """ Simple Ratio self.nir/self.red Difference Vegetation Index, Vegetation Index Number (VIN) https://www.indexdatabase.de/db/i-single.php?id=12 :return: index """ return self.nir / self.red def tvi(self): """ Transformed Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=98 :return: index """ return (self.ndvi() + 0.5) ** (1 / 2) def ndre(self): return (self.nir - self.redEdge) / (self.nir + self.redEdge) """ # genering a random matrices to test this class red = np.ones((1000,1000, 1),dtype="float64") * 46787 green = np.ones((1000,1000, 1),dtype="float64") * 23487 blue = np.ones((1000,1000, 1),dtype="float64") * 14578 redEdge = np.ones((1000,1000, 1),dtype="float64") * 51045 nir = np.ones((1000,1000, 1),dtype="float64") * 52200 # Examples of how to use the class # instantiating the class cl = IndexCalculation() # instantiating the class with the values #cl = indexCalculation(red=red, green=green, blue=blue, redEdge=redEdge, nir=nir) # how set the values after instantiate the class cl, (for update the data or when don't # instantiating the class with the values) cl.setMatrices(red=red, green=green, blue=blue, redEdge=redEdge, nir=nir) # calculating the indices for the instantiated values in the class # Note: the CCCI index can be changed to any index implemented in the class. indexValue_form1 = cl.calculation("CCCI", red=red, green=green, blue=blue, redEdge=redEdge, nir=nir).astype(np.float64) indexValue_form2 = cl.CCCI() # calculating the index with the values directly -- you can set just the values # preferred note: the *calculation* function performs the function *setMatrices* indexValue_form3 = cl.calculation("CCCI", red=red, green=green, blue=blue, redEdge=redEdge, nir=nir).astype(np.float64) print("Form 1: "+np.array2string(indexValue_form1, precision=20, separator=', ', floatmode='maxprec_equal')) print("Form 2: "+np.array2string(indexValue_form2, precision=20, separator=', ', floatmode='maxprec_equal')) print("Form 3: "+np.array2string(indexValue_form3, precision=20, separator=', ', floatmode='maxprec_equal')) # A list of examples results for different type of data at NDVI # float16 -> 0.31567383 #NDVI (red = 50, nir = 100) # float32 -> 0.31578946 #NDVI (red = 50, nir = 100) # float64 -> 0.3157894736842105 #NDVI (red = 50, nir = 100) # longdouble -> 0.3157894736842105 #NDVI (red = 50, nir = 100) """
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/convert_to_negative.py
digital_image_processing/convert_to_negative.py
""" Implemented an algorithm using opencv to convert a colored image into its negative """ from cv2 import destroyAllWindows, imread, imshow, waitKey def convert_to_negative(img): # getting number of pixels in the image pixel_h, pixel_v = img.shape[0], img.shape[1] # converting each pixel's color to its negative for i in range(pixel_h): for j in range(pixel_v): img[i][j] = [255, 255, 255] - img[i][j] return img if __name__ == "__main__": # read original image img = imread("image_data/lena.jpg", 1) # convert to its negative neg = convert_to_negative(img) # show result image imshow("negative of original image", img) waitKey(0) destroyAllWindows()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/histogram_equalization/histogram_stretch.py
digital_image_processing/histogram_equalization/histogram_stretch.py
""" Created on Fri Sep 28 15:22:29 2018 @author: Binish125 """ import copy import os import cv2 import numpy as np from matplotlib import pyplot as plt class ConstantStretch: def __init__(self): self.img = "" self.original_image = "" self.last_list = [] self.rem = 0 self.L = 256 self.sk = 0 self.k = 0 self.number_of_rows = 0 self.number_of_cols = 0 def stretch(self, input_image): self.img = cv2.imread(input_image, 0) self.original_image = copy.deepcopy(self.img) x, _, _ = plt.hist(self.img.ravel(), 256, [0, 256], label="x") self.k = np.sum(x) for i in range(len(x)): prk = x[i] / self.k self.sk += prk last = (self.L - 1) * self.sk if self.rem != 0: self.rem = int(last % last) last = int(last + 1 if self.rem >= 0.5 else last) self.last_list.append(last) self.number_of_rows = int(np.ma.count(self.img) / self.img[1].size) self.number_of_cols = self.img[1].size for i in range(self.number_of_cols): for j in range(self.number_of_rows): num = self.img[j][i] if num != self.last_list[num]: self.img[j][i] = self.last_list[num] cv2.imwrite("output_data/output.jpg", self.img) def plot_histogram(self): plt.hist(self.img.ravel(), 256, [0, 256]) def show_image(self): cv2.imshow("Output-Image", self.img) cv2.imshow("Input-Image", self.original_image) cv2.waitKey(5000) cv2.destroyAllWindows() if __name__ == "__main__": file_path = os.path.join(os.path.basename(__file__), "image_data/input.jpg") stretcher = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/histogram_equalization/__init__.py
digital_image_processing/histogram_equalization/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/histogram_equalization/image_data/__init__.py
digital_image_processing/histogram_equalization/image_data/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/histogram_equalization/output_data/__init__.py
digital_image_processing/histogram_equalization/output_data/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/image_data/__init__.py
digital_image_processing/image_data/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/resize/resize.py
digital_image_processing/resize/resize.py
"""Multiple image resizing techniques""" import numpy as np from cv2 import destroyAllWindows, imread, imshow, waitKey class NearestNeighbour: """ Simplest and fastest version of image resizing. Source: https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation """ def __init__(self, img, dst_width: int, dst_height: int): if dst_width < 0 or dst_height < 0: raise ValueError("Destination width/height should be > 0") self.img = img self.src_w = img.shape[1] self.src_h = img.shape[0] self.dst_w = dst_width self.dst_h = dst_height self.ratio_x = self.src_w / self.dst_w self.ratio_y = self.src_h / self.dst_h self.output = self.output_img = ( np.ones((self.dst_h, self.dst_w, 3), np.uint8) * 255 ) def process(self): for i in range(self.dst_h): for j in range(self.dst_w): self.output[i][j] = self.img[self.get_y(i)][self.get_x(j)] def get_x(self, x: int) -> int: """ Get parent X coordinate for destination X :param x: Destination X coordinate :return: Parent X coordinate based on `x ratio` >>> nn = NearestNeighbour(imread("digital_image_processing/image_data/lena.jpg", ... 1), 100, 100) >>> nn.ratio_x = 0.5 >>> nn.get_x(4) 2 """ return int(self.ratio_x * x) def get_y(self, y: int) -> int: """ Get parent Y coordinate for destination Y :param y: Destination X coordinate :return: Parent X coordinate based on `y ratio` >>> nn = NearestNeighbour(imread("digital_image_processing/image_data/lena.jpg", ... 1), 100, 100) >>> nn.ratio_y = 0.5 >>> nn.get_y(4) 2 """ return int(self.ratio_y * y) if __name__ == "__main__": dst_w, dst_h = 800, 600 im = imread("image_data/lena.jpg", 1) n = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( f"Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}", n.output ) waitKey(0) destroyAllWindows()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/resize/__init__.py
digital_image_processing/resize/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/filters/gaussian_filter.py
digital_image_processing/filters/gaussian_filter.py
""" Implementation of gaussian filter algorithm """ from itertools import product from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uint8, zeros def gen_gaussian_kernel(k_size, sigma): center = k_size // 2 x, y = mgrid[0 - center : k_size - center, 0 - center : k_size - center] g = 1 / (2 * pi * sigma) * exp(-(square(x) + square(y)) / (2 * square(sigma))) return g def gaussian_filter(image, k_size, sigma): height, width = image.shape[0], image.shape[1] # dst image height and width dst_height = height - k_size + 1 dst_width = width - k_size + 1 # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows image_array = zeros((dst_height * dst_width, k_size * k_size)) for row, (i, j) in enumerate(product(range(dst_height), range(dst_width))): window = ravel(image[i : i + k_size, j : j + k_size]) image_array[row, :] = window # turn the kernel into shape(k*k, 1) gaussian_kernel = gen_gaussian_kernel(k_size, sigma) filter_array = ravel(gaussian_kernel) # reshape and get the dst image dst = dot(image_array, filter_array).reshape(dst_height, dst_width).astype(uint8) return dst if __name__ == "__main__": # read original image img = imread(r"../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size gaussian3x3 = gaussian_filter(gray, 3, sigma=1) gaussian5x5 = gaussian_filter(gray, 5, sigma=0.8) # show result images imshow("gaussian filter with 3x3 mask", gaussian3x3) imshow("gaussian filter with 5x5 mask", gaussian5x5) waitKey()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/filters/sobel_filter.py
digital_image_processing/filters/sobel_filter.py
# @Author : lightXu # @File : sobel_filter.py # @Time : 2019/7/8 0008 下午 16:26 import numpy as np from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from digital_image_processing.filters.convolve import img_convolve def sobel_filter(image): kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) kernel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]) dst_x = np.abs(img_convolve(image, kernel_x)) dst_y = np.abs(img_convolve(image, kernel_y)) # modify the pix within [0, 255] dst_x = dst_x * 255 / np.max(dst_x) dst_y = dst_y * 255 / np.max(dst_y) dst_xy = np.sqrt((np.square(dst_x)) + (np.square(dst_y))) dst_xy = dst_xy * 255 / np.max(dst_xy) dst = dst_xy.astype(np.uint8) theta = np.arctan2(dst_y, dst_x) return dst, theta if __name__ == "__main__": # read original image img = imread("../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) sobel_grad, sobel_theta = sobel_filter(gray) # show result images imshow("sobel filter", sobel_grad) imshow("sobel theta", sobel_theta) waitKey(0)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/filters/convolve.py
digital_image_processing/filters/convolve.py
# @Author : lightXu # @File : convolve.py # @Time : 2019/7/8 0008 下午 16:13 from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import array, dot, pad, ravel, uint8, zeros def im2col(image, block_size): rows, cols = image.shape dst_height = cols - block_size[1] + 1 dst_width = rows - block_size[0] + 1 image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0])) row = 0 for i in range(dst_height): for j in range(dst_width): window = ravel(image[i : i + block_size[0], j : j + block_size[1]]) image_array[row, :] = window row += 1 return image_array def img_convolve(image, filter_kernel): height, width = image.shape[0], image.shape[1] k_size = filter_kernel.shape[0] pad_size = k_size // 2 # Pads image with the edge values of array. image_tmp = pad(image, pad_size, mode="edge") # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows image_array = im2col(image_tmp, (k_size, k_size)) # turn the kernel into shape(k*k, 1) kernel_array = ravel(filter_kernel) # reshape and get the dst image dst = dot(image_array, kernel_array).reshape(height, width) return dst if __name__ == "__main__": # read original image img = imread(r"../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # Laplace operator Laplace_kernel = array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]) out = img_convolve(gray, Laplace_kernel).astype(uint8) imshow("Laplacian", out) waitKey(0)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/filters/local_binary_pattern.py
digital_image_processing/filters/local_binary_pattern.py
import cv2 import numpy as np def get_neighbors_pixel( image: np.ndarray, x_coordinate: int, y_coordinate: int, center: int ) -> int: """ Comparing local neighborhood pixel value with threshold value of centre pixel. Exception is required when neighborhood value of a center pixel value is null. i.e. values present at boundaries. :param image: The image we're working with :param x_coordinate: x-coordinate of the pixel :param y_coordinate: The y coordinate of the pixel :param center: center pixel value :return: The value of the pixel is being returned. """ try: return int(image[x_coordinate][y_coordinate] >= center) except (IndexError, TypeError): return 0 def local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int) -> int: """ It takes an image, an x and y coordinate, and returns the decimal value of the local binary patternof the pixel at that coordinate :param image: the image to be processed :param x_coordinate: x coordinate of the pixel :param y_coordinate: the y coordinate of the pixel :return: The decimal value of the binary value of the pixels around the center pixel. """ center = image[x_coordinate][y_coordinate] powers = [1, 2, 4, 8, 16, 32, 64, 128] # skip get_neighbors_pixel if center is null if center is None: return 0 # Starting from the top right, assigning value to pixels clockwise binary_values = [ get_neighbors_pixel(image, x_coordinate - 1, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate - 1, y_coordinate, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate - 1, center), get_neighbors_pixel(image, x_coordinate, y_coordinate - 1, center), get_neighbors_pixel(image, x_coordinate - 1, y_coordinate - 1, center), ] # Converting the binary value to decimal. return sum( binary_value * power for binary_value, power in zip(binary_values, powers) ) if __name__ == "__main__": # Reading the image and converting it to grayscale. image = cv2.imread( "digital_image_processing/image_data/lena.jpg", cv2.IMREAD_GRAYSCALE ) # Create a numpy array as the same height and width of read image lbp_image = np.zeros((image.shape[0], image.shape[1])) # Iterating through the image and calculating the # local binary pattern value for each pixel. for i in range(image.shape[0]): for j in range(image.shape[1]): lbp_image[i][j] = local_binary_value(image, i, j) cv2.imshow("local binary pattern", lbp_image) cv2.waitKey(0) cv2.destroyAllWindows()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/filters/__init__.py
digital_image_processing/filters/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/filters/median_filter.py
digital_image_processing/filters/median_filter.py
""" Implementation of median filter algorithm """ from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import divide, int8, multiply, ravel, sort, zeros_like def median_filter(gray_img, mask=3): """ :param gray_img: gray image :param mask: mask size :return: image with median filter """ # set image borders bd = int(mask / 2) # copy image size median_img = zeros_like(gray_img) for i in range(bd, gray_img.shape[0] - bd): for j in range(bd, gray_img.shape[1] - bd): # get mask according with mask kernel = ravel(gray_img[i - bd : i + bd + 1, j - bd : j + bd + 1]) # calculate mask median median = sort(kernel)[int8(divide((multiply(mask, mask)), 2) + 1)] median_img[i, j] = median return median_img if __name__ == "__main__": # read original image img = imread("../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size median3x3 = median_filter(gray, 3) median5x5 = median_filter(gray, 5) # show result images imshow("median filter with 3x3 mask", median3x3) imshow("median filter with 5x5 mask", median5x5) waitKey(0)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/filters/laplacian_filter.py
digital_image_processing/filters/laplacian_filter.py
# @Author : ojas-wani # @File : laplacian_filter.py # @Date : 10/04/2023 import numpy as np from cv2 import ( BORDER_DEFAULT, COLOR_BGR2GRAY, CV_64F, cvtColor, filter2D, imread, imshow, waitKey, ) from digital_image_processing.filters.gaussian_filter import gaussian_filter def my_laplacian(src: np.ndarray, ksize: int) -> np.ndarray: """ :param src: the source image, which should be a grayscale or color image. :param ksize: the size of the kernel used to compute the Laplacian filter, which can be 1, 3, 5, or 7. >>> my_laplacian(src=np.array([]), ksize=0) Traceback (most recent call last): ... ValueError: ksize must be in (1, 3, 5, 7) """ kernels = { 1: np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]]), 3: np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]), 5: np.array( [ [0, 0, -1, 0, 0], [0, -1, -2, -1, 0], [-1, -2, 16, -2, -1], [0, -1, -2, -1, 0], [0, 0, -1, 0, 0], ] ), 7: np.array( [ [0, 0, 0, -1, 0, 0, 0], [0, 0, -2, -3, -2, 0, 0], [0, -2, -7, -10, -7, -2, 0], [-1, -3, -10, 68, -10, -3, -1], [0, -2, -7, -10, -7, -2, 0], [0, 0, -2, -3, -2, 0, 0], [0, 0, 0, -1, 0, 0, 0], ] ), } if ksize not in kernels: msg = f"ksize must be in {tuple(kernels)}" raise ValueError(msg) # Apply the Laplacian kernel using convolution return filter2D( src, CV_64F, kernels[ksize], 0, borderType=BORDER_DEFAULT, anchor=(0, 0) ) if __name__ == "__main__": # read original image img = imread(r"../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # Applying gaussian filter blur_image = gaussian_filter(gray, 3, sigma=1) # Apply multiple Kernel to detect edges laplacian_image = my_laplacian(ksize=3, src=blur_image) imshow("Original image", img) imshow("Detected edges using laplacian filter", laplacian_image) waitKey(0)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/filters/bilateral_filter.py
digital_image_processing/filters/bilateral_filter.py
""" Implementation of Bilateral filter Inputs: img: A 2d image with values in between 0 and 1 varS: variance in space dimension. varI: variance in Intensity. N: Kernel size(Must be an odd number) Output: img:A 2d zero padded image with values in between 0 and 1 """ import math import sys import cv2 import numpy as np def vec_gaussian(img: np.ndarray, variance: float) -> np.ndarray: # For applying gaussian function for each element in matrix. sigma = math.sqrt(variance) cons = 1 / (sigma * math.sqrt(2 * math.pi)) return cons * np.exp(-((img / sigma) ** 2) * 0.5) def get_slice(img: np.ndarray, x: int, y: int, kernel_size: int) -> np.ndarray: half = kernel_size // 2 return img[x - half : x + half + 1, y - half : y + half + 1] def get_gauss_kernel(kernel_size: int, spatial_variance: float) -> np.ndarray: # Creates a gaussian kernel of given dimension. arr = np.zeros((kernel_size, kernel_size)) for i in range(kernel_size): for j in range(kernel_size): arr[i, j] = math.sqrt( abs(i - kernel_size // 2) ** 2 + abs(j - kernel_size // 2) ** 2 ) return vec_gaussian(arr, spatial_variance) def bilateral_filter( img: np.ndarray, spatial_variance: float, intensity_variance: float, kernel_size: int, ) -> np.ndarray: img2 = np.zeros(img.shape) gauss_ker = get_gauss_kernel(kernel_size, spatial_variance) size_x, size_y = img.shape for i in range(kernel_size // 2, size_x - kernel_size // 2): for j in range(kernel_size // 2, size_y - kernel_size // 2): img_s = get_slice(img, i, j, kernel_size) img_i = img_s - img_s[kernel_size // 2, kernel_size // 2] img_ig = vec_gaussian(img_i, intensity_variance) weights = np.multiply(gauss_ker, img_ig) vals = np.multiply(img_s, weights) val = np.sum(vals) / np.sum(weights) img2[i, j] = val return img2 def parse_args(args: list) -> tuple: filename = args[1] if args[1:] else "../image_data/lena.jpg" spatial_variance = float(args[2]) if args[2:] else 1.0 intensity_variance = float(args[3]) if args[3:] else 1.0 if args[4:]: kernel_size = int(args[4]) kernel_size = kernel_size + abs(kernel_size % 2 - 1) else: kernel_size = 5 return filename, spatial_variance, intensity_variance, kernel_size if __name__ == "__main__": filename, spatial_variance, intensity_variance, kernel_size = parse_args(sys.argv) img = cv2.imread(filename, 0) cv2.imshow("input image", img) out = img / 255 out = out.astype("float32") out = bilateral_filter(out, spatial_variance, intensity_variance, kernel_size) out = out * 255 out = np.uint8(out) cv2.imshow("output image", out) cv2.waitKey(0) cv2.destroyAllWindows()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/filters/gabor_filter.py
digital_image_processing/filters/gabor_filter.py
# Implementation of the Gaborfilter # https://en.wikipedia.org/wiki/Gabor_filter import numpy as np from cv2 import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filter2D, imread, imshow, waitKey def gabor_filter_kernel( ksize: int, sigma: int, theta: int, lambd: int, gamma: int, psi: int ) -> np.ndarray: """ :param ksize: The kernelsize of the convolutional filter (ksize x ksize) :param sigma: standard deviation of the gaussian bell curve :param theta: The orientation of the normal to the parallel stripes of Gabor function. :param lambd: Wavelength of the sinusoidal component. :param gamma: The spatial aspect ratio and specifies the ellipticity of the support of Gabor function. :param psi: The phase offset of the sinusoidal function. >>> gabor_filter_kernel(3, 8, 0, 10, 0, 0).tolist() [[0.8027212023735046, 1.0, 0.8027212023735046], [0.8027212023735046, 1.0, \ 0.8027212023735046], [0.8027212023735046, 1.0, 0.8027212023735046]] """ # prepare kernel # the kernel size have to be odd if (ksize % 2) == 0: ksize = ksize + 1 gabor = np.zeros((ksize, ksize), dtype=np.float32) # each value for y in range(ksize): for x in range(ksize): # distance from center px = x - ksize // 2 py = y - ksize // 2 # degree to radiant _theta = theta / 180 * np.pi cos_theta = np.cos(_theta) sin_theta = np.sin(_theta) # get kernel x _x = cos_theta * px + sin_theta * py # get kernel y _y = -sin_theta * px + cos_theta * py # fill kernel gabor[y, x] = np.exp(-(_x**2 + gamma**2 * _y**2) / (2 * sigma**2)) * np.cos( 2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image img = imread("../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges out = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 120, 150]: """ ksize = 10 sigma = 8 lambd = 10 gamma = 0 psi = 0 """ kernel_10 = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filter2D(gray, CV_8UC3, kernel_10) out = out / out.max() * 255 out = out.astype(np.uint8) imshow("Original", gray) imshow("Gabor filter with 20x20 mask and 6 directions", out) waitKey(0)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/morphological_operations/dilation_operation.py
digital_image_processing/morphological_operations/dilation_operation.py
from pathlib import Path import numpy as np from PIL import Image def rgb_to_gray(rgb: np.ndarray) -> np.ndarray: """ Return gray image from rgb image >>> rgb_to_gray(np.array([[[127, 255, 0]]])) array([[187.6453]]) >>> rgb_to_gray(np.array([[[0, 0, 0]]])) array([[0.]]) >>> rgb_to_gray(np.array([[[2, 4, 1]]])) array([[3.0598]]) >>> rgb_to_gray(np.array([[[26, 255, 14], [5, 147, 20], [1, 200, 0]]])) array([[159.0524, 90.0635, 117.6989]]) """ r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def gray_to_binary(gray: np.ndarray) -> np.ndarray: """ Return binary image from gray image >>> gray_to_binary(np.array([[127, 255, 0]])) array([[False, True, False]]) >>> gray_to_binary(np.array([[0]])) array([[False]]) >>> gray_to_binary(np.array([[26.2409, 4.9315, 1.4729]])) array([[False, False, False]]) >>> gray_to_binary(np.array([[26, 255, 14], [5, 147, 20], [1, 200, 0]])) array([[False, True, False], [False, True, False], [False, True, False]]) """ return (gray > 127) & (gray <= 255) def dilation(image: np.ndarray, kernel: np.ndarray) -> np.ndarray: """ Return dilated image >>> dilation(np.array([[True, False, True]]), np.array([[0, 1, 0]])) array([[False, False, False]]) >>> dilation(np.array([[False, False, True]]), np.array([[1, 0, 1]])) array([[False, False, False]]) """ output = np.zeros_like(image) image_padded = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image # Iterate over image & apply kernel for x in range(image.shape[1]): for y in range(image.shape[0]): summation = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() output[y, x] = int(summation > 0) return output if __name__ == "__main__": # read original image lena_path = Path(__file__).resolve().parent / "image_data" / "lena.jpg" lena = np.array(Image.open(lena_path)) # kernel to be applied structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) output = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image pil_img = Image.fromarray(output).convert("RGB") pil_img.save("result_dilation.png")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/morphological_operations/erosion_operation.py
digital_image_processing/morphological_operations/erosion_operation.py
from pathlib import Path import numpy as np from PIL import Image def rgb_to_gray(rgb: np.ndarray) -> np.ndarray: """ Return gray image from rgb image >>> rgb_to_gray(np.array([[[127, 255, 0]]])) array([[187.6453]]) >>> rgb_to_gray(np.array([[[0, 0, 0]]])) array([[0.]]) >>> rgb_to_gray(np.array([[[2, 4, 1]]])) array([[3.0598]]) >>> rgb_to_gray(np.array([[[26, 255, 14], [5, 147, 20], [1, 200, 0]]])) array([[159.0524, 90.0635, 117.6989]]) """ r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def gray_to_binary(gray: np.ndarray) -> np.ndarray: """ Return binary image from gray image >>> gray_to_binary(np.array([[127, 255, 0]])) array([[False, True, False]]) >>> gray_to_binary(np.array([[0]])) array([[False]]) >>> gray_to_binary(np.array([[26.2409, 4.9315, 1.4729]])) array([[False, False, False]]) >>> gray_to_binary(np.array([[26, 255, 14], [5, 147, 20], [1, 200, 0]])) array([[False, True, False], [False, True, False], [False, True, False]]) """ return (gray > 127) & (gray <= 255) def erosion(image: np.ndarray, kernel: np.ndarray) -> np.ndarray: """ Return eroded image >>> erosion(np.array([[True, True, False]]), np.array([[0, 1, 0]])) array([[False, False, False]]) >>> erosion(np.array([[True, False, False]]), np.array([[1, 1, 0]])) array([[False, False, False]]) """ output = np.zeros_like(image) image_padded = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image # Iterate over image & apply kernel for x in range(image.shape[1]): for y in range(image.shape[0]): summation = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() output[y, x] = int(summation == 5) return output if __name__ == "__main__": # read original image lena_path = Path(__file__).resolve().parent / "image_data" / "lena.jpg" lena = np.array(Image.open(lena_path)) # kernel to be applied structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) # Apply erosion operation to a binary image output = erosion(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image pil_img = Image.fromarray(output).convert("RGB") pil_img.save("result_erosion.png")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/morphological_operations/__init__.py
digital_image_processing/morphological_operations/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/edge_detection/canny.py
digital_image_processing/edge_detection/canny.py
import cv2 import numpy as np from digital_image_processing.filters.convolve import img_convolve from digital_image_processing.filters.sobel_filter import sobel_filter PI = 180 def gen_gaussian_kernel(k_size, sigma): center = k_size // 2 x, y = np.mgrid[0 - center : k_size - center, 0 - center : k_size - center] g = ( 1 / (2 * np.pi * sigma) * np.exp(-(np.square(x) + np.square(y)) / (2 * np.square(sigma))) ) return g def suppress_non_maximum(image_shape, gradient_direction, sobel_grad): """ Non-maximum suppression. If the edge strength of the current pixel is the largest compared to the other pixels in the mask with the same direction, the value will be preserved. Otherwise, the value will be suppressed. """ destination = np.zeros(image_shape) for row in range(1, image_shape[0] - 1): for col in range(1, image_shape[1] - 1): direction = gradient_direction[row, col] if ( 0 <= direction < PI / 8 or 15 * PI / 8 <= direction <= 2 * PI or 7 * PI / 8 <= direction <= 9 * PI / 8 ): w = sobel_grad[row, col - 1] e = sobel_grad[row, col + 1] if sobel_grad[row, col] >= w and sobel_grad[row, col] >= e: destination[row, col] = sobel_grad[row, col] elif ( PI / 8 <= direction < 3 * PI / 8 or 9 * PI / 8 <= direction < 11 * PI / 8 ): sw = sobel_grad[row + 1, col - 1] ne = sobel_grad[row - 1, col + 1] if sobel_grad[row, col] >= sw and sobel_grad[row, col] >= ne: destination[row, col] = sobel_grad[row, col] elif ( 3 * PI / 8 <= direction < 5 * PI / 8 or 11 * PI / 8 <= direction < 13 * PI / 8 ): n = sobel_grad[row - 1, col] s = sobel_grad[row + 1, col] if sobel_grad[row, col] >= n and sobel_grad[row, col] >= s: destination[row, col] = sobel_grad[row, col] elif ( 5 * PI / 8 <= direction < 7 * PI / 8 or 13 * PI / 8 <= direction < 15 * PI / 8 ): nw = sobel_grad[row - 1, col - 1] se = sobel_grad[row + 1, col + 1] if sobel_grad[row, col] >= nw and sobel_grad[row, col] >= se: destination[row, col] = sobel_grad[row, col] return destination def detect_high_low_threshold( image_shape, destination, threshold_low, threshold_high, weak, strong ): """ High-Low threshold detection. If an edge pixel's gradient value is higher than the high threshold value, it is marked as a strong edge pixel. If an edge pixel's gradient value is smaller than the high threshold value and larger than the low threshold value, it is marked as a weak edge pixel. If an edge pixel's value is smaller than the low threshold value, it will be suppressed. """ for row in range(1, image_shape[0] - 1): for col in range(1, image_shape[1] - 1): if destination[row, col] >= threshold_high: destination[row, col] = strong elif destination[row, col] <= threshold_low: destination[row, col] = 0 else: destination[row, col] = weak def track_edge(image_shape, destination, weak, strong): """ Edge tracking. Usually a weak edge pixel caused from true edges will be connected to a strong edge pixel while noise responses are unconnected. As long as there is one strong edge pixel that is involved in its 8-connected neighborhood, that weak edge point can be identified as one that should be preserved. """ for row in range(1, image_shape[0]): for col in range(1, image_shape[1]): if destination[row, col] == weak: if 255 in ( destination[row, col + 1], destination[row, col - 1], destination[row - 1, col], destination[row + 1, col], destination[row - 1, col - 1], destination[row + 1, col - 1], destination[row - 1, col + 1], destination[row + 1, col + 1], ): destination[row, col] = strong else: destination[row, col] = 0 def canny(image, threshold_low=15, threshold_high=30, weak=128, strong=255): # gaussian_filter gaussian_out = img_convolve(image, gen_gaussian_kernel(9, sigma=1.4)) # get the gradient and degree by sobel_filter sobel_grad, sobel_theta = sobel_filter(gaussian_out) gradient_direction = PI + np.rad2deg(sobel_theta) destination = suppress_non_maximum(image.shape, gradient_direction, sobel_grad) detect_high_low_threshold( image.shape, destination, threshold_low, threshold_high, weak, strong ) track_edge(image.shape, destination, weak, strong) return destination if __name__ == "__main__": # read original image in gray mode lena = cv2.imread(r"../image_data/lena.jpg", 0) # canny edge detection canny_destination = canny(lena) cv2.imshow("canny", canny_destination) cv2.waitKey(0)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/edge_detection/__init__.py
digital_image_processing/edge_detection/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/dithering/__init__.py
digital_image_processing/dithering/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/dithering/burkes.py
digital_image_processing/dithering/burkes.py
""" Implementation Burke's algorithm (dithering) """ import numpy as np from cv2 import destroyAllWindows, imread, imshow, waitKey class Burkes: """ Burke's algorithm is using for converting grayscale image to black and white version Source: Source: https://en.wikipedia.org/wiki/Dither Note: * Best results are given with threshold= ~1/2 * max greyscale value. * This implementation get RGB image and converts it to greyscale in runtime. """ def __init__(self, input_img, threshold: int): self.min_threshold = 0 # max greyscale value for #FFFFFF self.max_threshold = int(self.get_greyscale(255, 255, 255)) if not self.min_threshold < threshold < self.max_threshold: msg = f"Factor value should be from 0 to {self.max_threshold}" raise ValueError(msg) self.input_img = input_img self.threshold = threshold self.width, self.height = self.input_img.shape[1], self.input_img.shape[0] # error table size (+4 columns and +1 row) greater than input image because of # lack of if statements self.error_table = [ [0 for _ in range(self.height + 4)] for __ in range(self.width + 1) ] self.output_img = np.ones((self.width, self.height, 3), np.uint8) * 255 @classmethod def get_greyscale(cls, blue: int, green: int, red: int) -> float: """ >>> Burkes.get_greyscale(3, 4, 5) 4.185 >>> Burkes.get_greyscale(0, 0, 0) 0.0 >>> Burkes.get_greyscale(255, 255, 255) 255.0 """ """ Formula from https://en.wikipedia.org/wiki/HSL_and_HSV cf Lightness section, and Fig 13c. We use the first of four possible. """ return 0.114 * blue + 0.587 * green + 0.299 * red def process(self) -> None: for y in range(self.height): for x in range(self.width): greyscale = int(self.get_greyscale(*self.input_img[y][x])) if self.threshold > greyscale + self.error_table[y][x]: self.output_img[y][x] = (0, 0, 0) current_error = greyscale + self.error_table[y][x] else: self.output_img[y][x] = (255, 255, 255) current_error = greyscale + self.error_table[y][x] - 255 """ Burkes error propagation (`*` is current pixel): * 8/32 4/32 2/32 4/32 8/32 4/32 2/32 """ self.error_table[y][x + 1] += int(8 / 32 * current_error) self.error_table[y][x + 2] += int(4 / 32 * current_error) self.error_table[y + 1][x] += int(8 / 32 * current_error) self.error_table[y + 1][x + 1] += int(4 / 32 * current_error) self.error_table[y + 1][x + 2] += int(2 / 32 * current_error) self.error_table[y + 1][x - 1] += int(4 / 32 * current_error) self.error_table[y + 1][x - 2] += int(2 / 32 * current_error) if __name__ == "__main__": # create Burke's instances with original images in greyscale burkes_instances = [ Burkes(imread("image_data/lena.jpg", 1), threshold) for threshold in (1, 126, 130, 140) ] for burkes in burkes_instances: burkes.process() for burkes in burkes_instances: imshow( f"Original image with dithering threshold: {burkes.threshold}", burkes.output_img, ) waitKey(0) destroyAllWindows()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/rotation/rotation.py
digital_image_processing/rotation/rotation.py
from pathlib import Path import cv2 import numpy as np from matplotlib import pyplot as plt def get_rotation( img: np.ndarray, pt1: np.ndarray, pt2: np.ndarray, rows: int, cols: int ) -> np.ndarray: """ Get image rotation :param img: np.ndarray :param pt1: 3x2 list :param pt2: 3x2 list :param rows: columns image shape :param cols: rows image shape :return: np.ndarray """ matrix = cv2.getAffineTransform(pt1, pt2) return cv2.warpAffine(img, matrix, (rows, cols)) if __name__ == "__main__": # read original image image = cv2.imread( str(Path(__file__).resolve().parent.parent / "image_data" / "lena.jpg") ) # turn image in gray scale value gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # get image shape img_rows, img_cols = gray_img.shape # set different points to rotate image pts1 = np.array([[50, 50], [200, 50], [50, 200]], np.float32) pts2 = np.array([[10, 100], [200, 50], [100, 250]], np.float32) pts3 = np.array([[50, 50], [150, 50], [120, 200]], np.float32) pts4 = np.array([[10, 100], [80, 50], [180, 250]], np.float32) # add all rotated images in a list images = [ gray_img, get_rotation(gray_img, pts1, pts2, img_rows, img_cols), get_rotation(gray_img, pts2, pts3, img_rows, img_cols), get_rotation(gray_img, pts2, pts4, img_rows, img_cols), ] # plot different image rotations fig = plt.figure(1) titles = ["Original", "Rotation 1", "Rotation 2", "Rotation 3"] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, "gray") plt.title(titles[i]) plt.axis("off") plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/digital_image_processing/rotation/__init__.py
digital_image_processing/rotation/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/genetic_algorithm/basic_string.py
genetic_algorithm/basic_string.py
""" Simple multithreaded algorithm to show how the 4 phases of a genetic algorithm works (Evaluation, Selection, Crossover and Mutation) https://en.wikipedia.org/wiki/Genetic_algorithm Author: D4rkia """ from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. N_POPULATION = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. N_SELECTED = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. MUTATION_PROBABILITY = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1000)) def evaluate(item: str, main_target: str) -> tuple[str, float]: """ Evaluate how similar the item is with the target by just counting each char in the right position >>> evaluate("Helxo Worlx", "Hello World") ('Helxo Worlx', 9.0) """ score = len([g for position, g in enumerate(item) if g == main_target[position]]) return (item, float(score)) def crossover(parent_1: str, parent_2: str) -> tuple[str, str]: """ Slice and combine two strings at a random point. >>> random.seed(42) >>> crossover("123456", "abcdef") ('12345f', 'abcde6') """ random_slice = random.randint(0, len(parent_1) - 1) child_1 = parent_1[:random_slice] + parent_2[random_slice:] child_2 = parent_2[:random_slice] + parent_1[random_slice:] return (child_1, child_2) def mutate(child: str, genes: list[str]) -> str: """ Mutate a random gene of a child with another one from the list. >>> random.seed(123) >>> mutate("123456", list("ABCDEF")) '12345A' """ child_list = list(child) if random.uniform(0, 1) < MUTATION_PROBABILITY: child_list[random.randint(0, len(child)) - 1] = random.choice(genes) return "".join(child_list) # Select, crossover and mutate a new population. def select( parent_1: tuple[str, float], population_score: list[tuple[str, float]], genes: list[str], ) -> list[str]: """ Select the second parent and generate new population >>> random.seed(42) >>> parent_1 = ("123456", 8.0) >>> population_score = [("abcdef", 4.0), ("ghijkl", 5.0), ("mnopqr", 7.0)] >>> genes = list("ABCDEF") >>> child_n = int(min(parent_1[1] + 1, 10)) >>> population = [] >>> for _ in range(child_n): ... parent_2 = population_score[random.randrange(len(population_score))][0] ... child_1, child_2 = crossover(parent_1[0], parent_2) ... population.extend((mutate(child_1, genes), mutate(child_2, genes))) >>> len(population) == (int(parent_1[1]) + 1) * 2 True """ pop = [] # Generate more children proportionally to the fitness score. child_n = int(parent_1[1] * 100) + 1 child_n = 10 if child_n >= 10 else child_n for _ in range(child_n): parent_2 = population_score[random.randint(0, N_SELECTED)][0] child_1, child_2 = crossover(parent_1[0], parent_2) # Append new string to the population list. pop.append(mutate(child_1, genes)) pop.append(mutate(child_2, genes)) return pop def basic(target: str, genes: list[str], debug: bool = True) -> tuple[int, int, str]: """ Verify that the target contains no genes besides the ones inside genes variable. >>> from string import ascii_lowercase >>> basic("doctest", ascii_lowercase, debug=False)[2] 'doctest' >>> genes = list(ascii_lowercase) >>> genes.remove("e") >>> basic("test", genes) Traceback (most recent call last): ... ValueError: ['e'] is not in genes list, evolution cannot converge >>> genes.remove("s") >>> basic("test", genes) Traceback (most recent call last): ... ValueError: ['e', 's'] is not in genes list, evolution cannot converge >>> genes.remove("t") >>> basic("test", genes) Traceback (most recent call last): ... ValueError: ['e', 's', 't'] is not in genes list, evolution cannot converge """ # Verify if N_POPULATION is bigger than N_SELECTED if N_POPULATION < N_SELECTED: msg = f"{N_POPULATION} must be bigger than {N_SELECTED}" raise ValueError(msg) # Verify that the target contains no genes besides the ones inside genes variable. not_in_genes_list = sorted({c for c in target if c not in genes}) if not_in_genes_list: msg = f"{not_in_genes_list} is not in genes list, evolution cannot converge" raise ValueError(msg) # Generate random starting population. population = [] for _ in range(N_POPULATION): population.append("".join([random.choice(genes) for i in range(len(target))])) # Just some logs to know what the algorithms is doing. generation, total_population = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(population) # Random population created. Now it's time to evaluate. # (Option 1) Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item, target) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # (Option 2) We just need to call evaluate for every item inside the population. population_score = [evaluate(item, target) for item in population] # Check if there is a matching evolution. population_score = sorted(population_score, key=lambda x: x[1], reverse=True) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( f"\nGeneration: {generation}" f"\nTotal Population:{total_population}" f"\nBest score: {population_score[0][1]}" f"\nBest string: {population_score[0][0]}" ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. population_best = population[: int(N_POPULATION / 3)] population.clear() population.extend(population_best) # Normalize population score to be between 0 and 1. population_score = [ (item, score / len(target)) for item, score in population_score ] # This is selection for i in range(N_SELECTED): population.extend(select(population_score[int(i)], population_score, genes)) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(population) > N_POPULATION: break if __name__ == "__main__": target_str = ( "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!" ) genes_list = list( " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm" "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\" ) generation, population, target = basic(target_str, genes_list) print( f"\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}" )
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/genetic_algorithm/__init__.py
genetic_algorithm/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/quantum/q_fourier_transform.py
quantum/q_fourier_transform.py
""" Build the quantum fourier transform (qft) for a desire number of quantum bits using Qiskit framework. This experiment run in IBM Q simulator with 10000 shots. This circuit can be use as a building block to design the Shor's algorithm in quantum computing. As well as, quantum phase estimation among others. . References: https://en.wikipedia.org/wiki/Quantum_Fourier_transform https://qiskit.org/textbook/ch-algorithms/quantum-fourier-transform.html """ import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def quantum_fourier_transform(number_of_qubits: int = 3) -> qiskit.result.counts.Counts: """ # >>> quantum_fourier_transform(2) # {'00': 2500, '01': 2500, '11': 2500, '10': 2500} # quantum circuit for number_of_qubits = 3: ┌───┐ qr_0: ──────■──────────────────────■───────┤ H ├─X─ │ ┌───┐ │P(π/2) └───┘ │ qr_1: ──────┼────────■───────┤ H ├─■─────────────┼─ ┌───┐ │P(π/4) │P(π/2) └───┘ │ qr_2: ┤ H ├─■────────■───────────────────────────X─ └───┘ cr: 3/═════════════════════════════════════════════ Args: n : number of qubits Returns: qiskit.result.counts.Counts: distribute counts. >>> quantum_fourier_transform(2) {'00': 2500, '01': 2500, '10': 2500, '11': 2500} >>> quantum_fourier_transform(-1) Traceback (most recent call last): ... ValueError: number of qubits must be > 0. >>> quantum_fourier_transform('a') Traceback (most recent call last): ... TypeError: number of qubits must be a integer. >>> quantum_fourier_transform(100) Traceback (most recent call last): ... ValueError: number of qubits too large to simulate(>10). >>> quantum_fourier_transform(0.5) Traceback (most recent call last): ... ValueError: number of qubits must be exact integer. """ if isinstance(number_of_qubits, str): raise TypeError("number of qubits must be a integer.") if number_of_qubits <= 0: raise ValueError("number of qubits must be > 0.") if math.floor(number_of_qubits) != number_of_qubits: raise ValueError("number of qubits must be exact integer.") if number_of_qubits > 10: raise ValueError("number of qubits too large to simulate(>10).") qr = QuantumRegister(number_of_qubits, "qr") cr = ClassicalRegister(number_of_qubits, "cr") quantum_circuit = QuantumCircuit(qr, cr) counter = number_of_qubits for i in range(counter): quantum_circuit.h(number_of_qubits - i - 1) counter -= 1 for j in range(counter): quantum_circuit.cp(np.pi / 2 ** (counter - j), j, counter) for k in range(number_of_qubits // 2): quantum_circuit.swap(k, number_of_qubits - k - 1) # measure all the qubits quantum_circuit.measure(qr, cr) # simulate with 10000 shots backend = Aer.get_backend("qasm_simulator") job = execute(quantum_circuit, backend, shots=10000) return job.result().get_counts(quantum_circuit) if __name__ == "__main__": print( f"Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}" )
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/quantum/__init__.py
quantum/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/intro_sort.py
sorts/intro_sort.py
""" Introspective Sort is a hybrid sort (Quick Sort + Heap Sort + Insertion Sort) if the size of the list is under 16, use insertion sort https://en.wikipedia.org/wiki/Introsort """ import math def insertion_sort(array: list, start: int = 0, end: int = 0) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> insertion_sort(array, 0, len(array)) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] >>> array = [21, 15, 11, 45, -2, -11, 46] >>> insertion_sort(array, 0, len(array)) [-11, -2, 11, 15, 21, 45, 46] >>> array = [-2, 0, 89, 11, 48, 79, 12] >>> insertion_sort(array, 0, len(array)) [-2, 0, 11, 12, 48, 79, 89] >>> array = ['a', 'z', 'd', 'p', 'v', 'l', 'o', 'o'] >>> insertion_sort(array, 0, len(array)) ['a', 'd', 'l', 'o', 'o', 'p', 'v', 'z'] >>> array = [73.568, 73.56, -45.03, 1.7, 0, 89.45] >>> insertion_sort(array, 0, len(array)) [-45.03, 0, 1.7, 73.56, 73.568, 89.45] """ end = end or len(array) for i in range(start, end): temp_index = i temp_index_value = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: array[temp_index] = array[temp_index - 1] temp_index -= 1 array[temp_index] = temp_index_value return array def heapify(array: list, index: int, heap_size: int) -> None: # Max Heap """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> heapify(array, len(array) // 2, len(array)) """ largest = index left_index = 2 * index + 1 # Left Node right_index = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: largest = left_index if right_index < heap_size and array[largest] < array[right_index]: largest = right_index if largest != index: array[index], array[largest] = array[largest], array[index] heapify(array, largest, heap_size) def heap_sort(array: list) -> list: """ >>> heap_sort([4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12]) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] >>> heap_sort([-2, -11, 0, 0, 0, 87, 45, -69, 78, 12, 10, 103, 89, 52]) [-69, -11, -2, 0, 0, 0, 10, 12, 45, 52, 78, 87, 89, 103] >>> heap_sort(['b', 'd', 'e', 'f', 'g', 'p', 'x', 'z', 'b', 's', 'e', 'u', 'v']) ['b', 'b', 'd', 'e', 'e', 'f', 'g', 'p', 's', 'u', 'v', 'x', 'z'] >>> heap_sort([6.2, -45.54, 8465.20, 758.56, -457.0, 0, 1, 2.879, 1.7, 11.7]) [-457.0, -45.54, 0, 1, 1.7, 2.879, 6.2, 11.7, 758.56, 8465.2] """ n = len(array) for i in range(n // 2, -1, -1): heapify(array, i, n) for i in range(n - 1, 0, -1): array[i], array[0] = array[0], array[i] heapify(array, 0, i) return array def median_of_3( array: list, first_index: int, middle_index: int, last_index: int ) -> int: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> median_of_3(array, 0, ((len(array) - 0) // 2) + 1, len(array) - 1) 12 >>> array = [13, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> median_of_3(array, 0, ((len(array) - 0) // 2) + 1, len(array) - 1) 13 >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 15, 14, 27, 79, 23, 45, 14, 16] >>> median_of_3(array, 0, ((len(array) - 0) // 2) + 1, len(array) - 1) 14 """ if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def partition(array: list, low: int, high: int, pivot: int) -> int: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> partition(array, 0, len(array), 12) 8 >>> array = [21, 15, 11, 45, -2, -11, 46] >>> partition(array, 0, len(array), 15) 3 >>> array = ['a', 'z', 'd', 'p', 'v', 'l', 'o', 'o'] >>> partition(array, 0, len(array), 'p') 5 >>> array = [6.2, -45.54, 8465.20, 758.56, -457.0, 0, 1, 2.879, 1.7, 11.7] >>> partition(array, 0, len(array), 2.879) 6 """ i = low j = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i array[i], array[j] = array[j], array[i] i += 1 def sort(array: list) -> list: """ :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> sort([4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12]) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] >>> sort([-1, -5, -3, -13, -44]) [-44, -13, -5, -3, -1] >>> sort([]) [] >>> sort([5]) [5] >>> sort([-3, 0, -7, 6, 23, -34]) [-34, -7, -3, 0, 6, 23] >>> sort([1.7, 1.0, 3.3, 2.1, 0.3 ]) [0.3, 1.0, 1.7, 2.1, 3.3] >>> sort(['d', 'a', 'b', 'e', 'c']) ['a', 'b', 'c', 'd', 'e'] """ if len(array) == 0: return array max_depth = 2 * math.ceil(math.log2(len(array))) size_threshold = 16 return intro_sort(array, 0, len(array), size_threshold, max_depth) def intro_sort( array: list, start: int, end: int, size_threshold: int, max_depth: int ) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12] >>> max_depth = 2 * math.ceil(math.log2(len(array))) >>> intro_sort(array, 0, len(array), 16, max_depth) [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79] """ while end - start > size_threshold: if max_depth == 0: return heap_sort(array) max_depth -= 1 pivot = median_of_3(array, start, start + ((end - start) // 2) + 1, end - 1) p = partition(array, start, end, pivot) intro_sort(array, p, end, size_threshold, max_depth) end = p return insertion_sort(array, start, end) if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma : ").strip() unsorted = [float(item) for item in user_input.split(",")] print(f"{sort(unsorted) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/strand_sort.py
sorts/strand_sort.py
import operator def strand_sort(arr: list, reverse: bool = False, solution: list | None = None) -> list: """ Strand sort implementation source: https://en.wikipedia.org/wiki/Strand_sort :param arr: Unordered input list :param reverse: Descent ordering flag :param solution: Ordered items container Examples: >>> strand_sort([4, 2, 5, 3, 0, 1]) [0, 1, 2, 3, 4, 5] >>> strand_sort([4, 2, 5, 3, 0, 1], reverse=True) [5, 4, 3, 2, 1, 0] """ _operator = operator.lt if reverse else operator.gt solution = solution or [] if not arr: return solution sublist = [arr.pop(0)] for i, item in enumerate(arr): if _operator(item, sublist[-1]): sublist.append(item) arr.pop(i) # merging sublist into solution list if not solution: solution.extend(sublist) else: while sublist: item = sublist.pop(0) for i, xx in enumerate(solution): if not _operator(item, xx): solution.insert(i, item) break else: solution.append(item) strand_sort(arr, reverse, solution) return solution if __name__ == "__main__": assert strand_sort([4, 3, 5, 1, 2]) == [1, 2, 3, 4, 5] assert strand_sort([4, 3, 5, 1, 2], reverse=True) == [5, 4, 3, 2, 1]
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/wiggle_sort.py
sorts/wiggle_sort.py
""" Wiggle Sort. Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... For example: if input numbers = [3, 5, 2, 1, 6, 4] one possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4]. """ def wiggle_sort(nums: list) -> list: """ Python implementation of wiggle. Example: >>> wiggle_sort([0, 5, 3, 2, 2]) [0, 5, 2, 3, 2] >>> wiggle_sort([]) [] >>> wiggle_sort([-2, -5, -45]) [-45, -2, -5] >>> wiggle_sort([-2.1, -5.68, -45.11]) [-45.11, -2.1, -5.68] """ for i, _ in enumerate(nums): if (i % 2 == 1) == (nums[i - 1] > nums[i]): nums[i - 1], nums[i] = nums[i], nums[i - 1] return nums if __name__ == "__main__": print("Enter the array elements:") array = list(map(int, input().split())) print("The unsorted array is:") print(array) print("Array after Wiggle sort:") print(wiggle_sort(array))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/odd_even_transposition_parallel.py
sorts/odd_even_transposition_parallel.py
""" This is an implementation of odd-even transposition sort. It works by performing a series of parallel swaps between odd and even pairs of variables in the list. This implementation represents each variable in the list with a process and each process communicates with its neighboring processes in the list to perform comparisons. They are synchronized with locks and message passing but other forms of synchronization could be used. """ import multiprocessing as mp # lock used to ensure that two processes do not access a pipe at the same time # NOTE This breaks testing on build runner. May work better locally # process_lock = mp.Lock() """ The function run by the processes that sorts the list position = the position in the list the process represents, used to know which neighbor we pass our value to value = the initial value at list[position] LSend, RSend = the pipes we use to send to our left and right neighbors LRcv, RRcv = the pipes we use to receive from our left and right neighbors resultPipe = the pipe used to send results back to main """ def oe_process( position, value, l_send, r_send, lr_cv, rr_cv, result_pipe, multiprocessing_context, ): process_lock = multiprocessing_context.Lock() # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(10): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor with process_lock: r_send[1].send(value) # receive your right neighbor's value with process_lock: temp = rr_cv[0].recv() # take the lower value since you are on the left value = min(value, temp) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor with process_lock: l_send[1].send(value) # receive your left neighbor's value with process_lock: temp = lr_cv[0].recv() # take the higher value since you are on the right value = max(value, temp) # after all swaps are performed, send the values back to main result_pipe[1].send(value) """ the function which creates the processes that perform the parallel swaps arr = the list to be sorted """ def odd_even_transposition(arr): """ >>> odd_even_transposition(list(range(10)[::-1])) == sorted(list(range(10)[::-1])) True >>> odd_even_transposition(["a", "x", "c"]) == sorted(["x", "a", "c"]) True >>> odd_even_transposition([1.9, 42.0, 2.8]) == sorted([1.9, 42.0, 2.8]) True >>> odd_even_transposition([False, True, False]) == sorted([False, False, True]) True >>> odd_even_transposition([1, 32.0, 9]) == sorted([False, False, True]) False >>> odd_even_transposition([1, 32.0, 9]) == sorted([1.0, 32, 9.0]) True >>> unsorted_list = [-442, -98, -554, 266, -491, 985, -53, -529, 82, -429] >>> odd_even_transposition(unsorted_list) == sorted(unsorted_list) True >>> unsorted_list = [-442, -98, -554, 266, -491, 985, -53, -529, 82, -429] >>> odd_even_transposition(unsorted_list) == sorted(unsorted_list + [1]) False """ # spawn method is considered safer than fork multiprocessing_context = mp.get_context("spawn") process_array_ = [] result_pipe = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(multiprocessing_context.Pipe()) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop temp_rs = multiprocessing_context.Pipe() temp_rr = multiprocessing_context.Pipe() process_array_.append( multiprocessing_context.Process( target=oe_process, args=( 0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0], multiprocessing_context, ), ) ) temp_lr = temp_rs temp_ls = temp_rr for i in range(1, len(arr) - 1): temp_rs = multiprocessing_context.Pipe() temp_rr = multiprocessing_context.Pipe() process_array_.append( multiprocessing_context.Process( target=oe_process, args=( i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i], multiprocessing_context, ), ) ) temp_lr = temp_rs temp_ls = temp_rr process_array_.append( multiprocessing_context.Process( target=oe_process, args=( len(arr) - 1, arr[len(arr) - 1], temp_ls, None, temp_lr, None, result_pipe[len(arr) - 1], multiprocessing_context, ), ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(len(result_pipe)): arr[p] = result_pipe[p][0].recv() process_array_[p].join() return arr # creates a reverse sorted list and sorts it def main(): arr = list(range(10, 0, -1)) print("Initial List") print(*arr) arr = odd_even_transposition(arr) print("Sorted List\n") print(*arr) if __name__ == "__main__": main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/exchange_sort.py
sorts/exchange_sort.py
def exchange_sort(numbers: list[int]) -> list[int]: """ Uses exchange sort to sort a list of numbers. Source: https://en.wikipedia.org/wiki/Sorting_algorithm#Exchange_sort >>> exchange_sort([5, 4, 3, 2, 1]) [1, 2, 3, 4, 5] >>> exchange_sort([-1, -2, -3]) [-3, -2, -1] >>> exchange_sort([1, 2, 3, 4, 5]) [1, 2, 3, 4, 5] >>> exchange_sort([0, 10, -2, 5, 3]) [-2, 0, 3, 5, 10] >>> exchange_sort([]) [] """ numbers_length = len(numbers) for i in range(numbers_length): for j in range(i + 1, numbers_length): if numbers[j] < numbers[i]: numbers[i], numbers[j] = numbers[j], numbers[i] return numbers if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(exchange_sort(unsorted))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/iterative_merge_sort.py
sorts/iterative_merge_sort.py
""" Implementation of iterative merge sort in Python Author: Aman Gupta For doctests run following command: python3 -m doctest -v iterative_merge_sort.py For manual testing run: python3 iterative_merge_sort.py """ from __future__ import annotations def merge(input_list: list, low: int, mid: int, high: int) -> list: """ sorting left-half and right-half individually then merging them into result """ result = [] left, right = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0)) input_list[low : high + 1] = result + left + right return input_list # iteration over the unsorted list def iter_merge_sort(input_list: list) -> list: """ Return a sorted copy of the input list >>> iter_merge_sort([5, 9, 8, 7, 1, 2, 7]) [1, 2, 5, 7, 7, 8, 9] >>> iter_merge_sort([1]) [1] >>> iter_merge_sort([2, 1]) [1, 2] >>> iter_merge_sort([2, 1, 3]) [1, 2, 3] >>> iter_merge_sort([4, 3, 2, 1]) [1, 2, 3, 4] >>> iter_merge_sort([5, 4, 3, 2, 1]) [1, 2, 3, 4, 5] >>> iter_merge_sort(['c', 'b', 'a']) ['a', 'b', 'c'] >>> iter_merge_sort([0.3, 0.2, 0.1]) [0.1, 0.2, 0.3] >>> iter_merge_sort(['dep', 'dang', 'trai']) ['dang', 'dep', 'trai'] >>> iter_merge_sort([6]) [6] >>> iter_merge_sort([]) [] >>> iter_merge_sort([-2, -9, -1, -4]) [-9, -4, -2, -1] >>> iter_merge_sort([1.1, 1, 0.0, -1, -1.1]) [-1.1, -1, 0.0, 1, 1.1] >>> iter_merge_sort(['c', 'b', 'a']) ['a', 'b', 'c'] >>> iter_merge_sort('cba') ['a', 'b', 'c'] """ if len(input_list) <= 1: return input_list input_list = list(input_list) # iteration for two-way merging p = 2 while p <= len(input_list): # getting low, high and middle value for merge-sort of single list for i in range(0, len(input_list), p): low = i high = i + p - 1 mid = (low + high + 1) // 2 input_list = merge(input_list, low, mid, high) # final merge of last two parts if p * 2 >= len(input_list): mid = i input_list = merge(input_list, 0, mid, len(input_list) - 1) break p *= 2 return input_list if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() if user_input == "": unsorted = [] else: unsorted = [int(item.strip()) for item in user_input.split(",")] print(iter_merge_sort(unsorted))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/double_sort.py
sorts/double_sort.py
from typing import Any def double_sort(collection: list[Any]) -> list[Any]: """This sorting algorithm sorts an array using the principle of bubble sort, but does it both from left to right and right to left. Hence, it's called "Double sort" :param collection: mutable ordered sequence of elements :return: the same collection in ascending order Examples: >>> double_sort([-1 ,-2 ,-3 ,-4 ,-5 ,-6 ,-7]) [-7, -6, -5, -4, -3, -2, -1] >>> double_sort([]) [] >>> double_sort([-1 ,-2 ,-3 ,-4 ,-5 ,-6]) [-6, -5, -4, -3, -2, -1] >>> double_sort([-3, 10, 16, -42, 29]) == sorted([-3, 10, 16, -42, 29]) True """ no_of_elements = len(collection) for _ in range( int(((no_of_elements - 1) / 2) + 1) ): # we don't need to traverse to end of list as for j in range(no_of_elements - 1): # apply the bubble sort algorithm from left to right (or forwards) if collection[j + 1] < collection[j]: collection[j], collection[j + 1] = collection[j + 1], collection[j] # apply the bubble sort algorithm from right to left (or backwards) if collection[no_of_elements - 1 - j] < collection[no_of_elements - 2 - j]: ( collection[no_of_elements - 1 - j], collection[no_of_elements - 2 - j], ) = ( collection[no_of_elements - 2 - j], collection[no_of_elements - 1 - j], ) return collection if __name__ == "__main__": # allow the user to input the elements of the list on one line unsorted = [int(x) for x in input("Enter the list to be sorted: ").split() if x] print("the sorted list is") print(f"{double_sort(unsorted) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/binary_insertion_sort.py
sorts/binary_insertion_sort.py
""" This is a pure Python implementation of the binary insertion sort algorithm For doctests run following command: python -m doctest -v binary_insertion_sort.py or python3 -m doctest -v binary_insertion_sort.py For manual testing run: python binary_insertion_sort.py """ def binary_insertion_sort(collection: list) -> list: """ Sorts a list using the binary insertion sort algorithm. :param collection: A mutable ordered collection with comparable items. :return: The same collection ordered in ascending order. Examples: >>> binary_insertion_sort([0, 4, 1234, 4, 1]) [0, 1, 4, 4, 1234] >>> binary_insertion_sort([]) == sorted([]) True >>> binary_insertion_sort([-1, -2, -3]) == sorted([-1, -2, -3]) True >>> lst = ['d', 'a', 'b', 'e', 'c'] >>> binary_insertion_sort(lst) == sorted(lst) True >>> import random >>> collection = random.sample(range(-50, 50), 100) >>> binary_insertion_sort(collection) == sorted(collection) True >>> import string >>> collection = random.choices(string.ascii_letters + string.digits, k=100) >>> binary_insertion_sort(collection) == sorted(collection) True """ n = len(collection) for i in range(1, n): value_to_insert = collection[i] low = 0 high = i - 1 while low <= high: mid = (low + high) // 2 if value_to_insert < collection[mid]: high = mid - 1 else: low = mid + 1 for j in range(i, low, -1): collection[j] = collection[j - 1] collection[low] = value_to_insert return collection if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() try: unsorted = [int(item) for item in user_input.split(",")] except ValueError: print("Invalid input. Please enter valid integers separated by commas.") raise print(f"{binary_insertion_sort(unsorted) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/unknown_sort.py
sorts/unknown_sort.py
""" Python implementation of a sort algorithm. Best Case Scenario : O(n) Worst Case Scenario : O(n^2) because native Python functions:min, max and remove are already O(n) """ def merge_sort(collection): """Pure implementation of the fastest merge sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: a collection ordered by ascending Examples: >>> merge_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> merge_sort([]) [] >>> merge_sort([-2, -5, -45]) [-45, -5, -2] """ start, end = [], [] while len(collection) > 1: min_one, max_one = min(collection), max(collection) start.append(min_one) end.append(max_one) collection.remove(min_one) collection.remove(max_one) end.reverse() return start + collection + end if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(*merge_sort(unsorted), sep=",")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/pigeon_sort.py
sorts/pigeon_sort.py
""" This is an implementation of Pigeon Hole Sort. For doctests run following command: python3 -m doctest -v pigeon_sort.py or python -m doctest -v pigeon_sort.py For manual testing run: python pigeon_sort.py """ from __future__ import annotations def pigeon_sort(array: list[int]) -> list[int]: """ Implementation of pigeon hole sort algorithm :param array: Collection of comparable items :return: Collection sorted in ascending order >>> pigeon_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> pigeon_sort([]) [] >>> pigeon_sort([-2, -5, -45]) [-45, -5, -2] """ if len(array) == 0: return array _min, _max = min(array), max(array) # Compute the variables holes_range = _max - _min + 1 holes, holes_repeat = [0] * holes_range, [0] * holes_range # Make the sorting. for i in array: index = i - _min holes[index] = i holes_repeat[index] += 1 # Makes the array back by replacing the numbers. index = 0 for i in range(holes_range): while holes_repeat[i] > 0: array[index] = holes[i] index += 1 holes_repeat[i] -= 1 # Returns the sorted array. return array if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by comma:\n") unsorted = [int(x) for x in user_input.split(",")] print(pigeon_sort(unsorted))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/bead_sort.py
sorts/bead_sort.py
""" Bead sort only works for sequences of non-negative integers. https://en.wikipedia.org/wiki/Bead_sort """ def bead_sort(sequence: list) -> list: """ >>> bead_sort([6, 11, 12, 4, 1, 5]) [1, 4, 5, 6, 11, 12] >>> bead_sort([9, 8, 7, 6, 5, 4 ,3, 2, 1]) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> bead_sort([5, 0, 4, 3]) [0, 3, 4, 5] >>> bead_sort([8, 2, 1]) [1, 2, 8] >>> bead_sort([1, .9, 0.0, 0, -1, -.9]) Traceback (most recent call last): ... TypeError: Sequence must be list of non-negative integers >>> bead_sort("Hello world") Traceback (most recent call last): ... TypeError: Sequence must be list of non-negative integers """ if any(not isinstance(x, int) or x < 0 for x in sequence): raise TypeError("Sequence must be list of non-negative integers") for _ in range(len(sequence)): for i, (rod_upper, rod_lower) in enumerate(zip(sequence, sequence[1:])): # noqa: RUF007 if rod_upper > rod_lower: sequence[i] -= rod_upper - rod_lower sequence[i + 1] += rod_upper - rod_lower return sequence if __name__ == "__main__": assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9]
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/counting_sort.py
sorts/counting_sort.py
""" This is pure Python implementation of counting sort algorithm For doctests run following command: python -m doctest -v counting_sort.py or python3 -m doctest -v counting_sort.py For manual testing run: python counting_sort.py """ def counting_sort(collection): """Pure implementation of counting sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> counting_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> counting_sort([]) [] >>> counting_sort([-2, -5, -45]) [-45, -5, -2] """ # if the collection is empty, returns empty if collection == []: return [] # get some information about the collection coll_len = len(collection) coll_max = max(collection) coll_min = min(collection) # create the counting array counting_arr_length = coll_max + 1 - coll_min counting_arr = [0] * counting_arr_length # count how much a number appears in the collection for number in collection: counting_arr[number - coll_min] += 1 # sum each position with it's predecessors. now, counting_arr[i] tells # us how many elements <= i has in the collection for i in range(1, counting_arr_length): counting_arr[i] = counting_arr[i] + counting_arr[i - 1] # create the output collection ordered = [0] * coll_len # place the elements in the output, respecting the original order (stable # sort) from end to begin, updating counting_arr for i in reversed(range(coll_len)): ordered[counting_arr[collection[i] - coll_min] - 1] = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def counting_sort_string(string): """ >>> counting_sort_string("thisisthestring") 'eghhiiinrsssttt' """ return "".join([chr(i) for i in counting_sort([ord(c) for c in string])]) if __name__ == "__main__": # Test string sort assert counting_sort_string("thisisthestring") == "eghhiiinrsssttt" user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(counting_sort(unsorted))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/quick_sort_3_partition.py
sorts/quick_sort_3_partition.py
def quick_sort_3partition(sorting: list, left: int, right: int) -> None: """ " Python implementation of quick sort algorithm with 3-way partition. The idea of 3-way quick sort is based on "Dutch National Flag algorithm". :param sorting: sort list :param left: left endpoint of sorting :param right: right endpoint of sorting :return: None Examples: >>> array1 = [5, -1, -1, 5, 5, 24, 0] >>> quick_sort_3partition(array1, 0, 6) >>> array1 [-1, -1, 0, 5, 5, 5, 24] >>> array2 = [9, 0, 2, 6] >>> quick_sort_3partition(array2, 0, 3) >>> array2 [0, 2, 6, 9] >>> array3 = [] >>> quick_sort_3partition(array3, 0, 0) >>> array3 [] """ if right <= left: return a = i = left b = right pivot = sorting[left] while i <= b: if sorting[i] < pivot: sorting[a], sorting[i] = sorting[i], sorting[a] a += 1 i += 1 elif sorting[i] > pivot: sorting[b], sorting[i] = sorting[i], sorting[b] b -= 1 else: i += 1 quick_sort_3partition(sorting, left, a - 1) quick_sort_3partition(sorting, b + 1, right) def quick_sort_lomuto_partition(sorting: list, left: int, right: int) -> None: """ A pure Python implementation of quick sort algorithm(in-place) with Lomuto partition scheme: https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme :param sorting: sort list :param left: left endpoint of sorting :param right: right endpoint of sorting :return: None Examples: >>> nums1 = [0, 5, 3, 1, 2] >>> quick_sort_lomuto_partition(nums1, 0, 4) >>> nums1 [0, 1, 2, 3, 5] >>> nums2 = [] >>> quick_sort_lomuto_partition(nums2, 0, 0) >>> nums2 [] >>> nums3 = [-2, 5, 0, -4] >>> quick_sort_lomuto_partition(nums3, 0, 3) >>> nums3 [-4, -2, 0, 5] """ if left < right: pivot_index = lomuto_partition(sorting, left, right) quick_sort_lomuto_partition(sorting, left, pivot_index - 1) quick_sort_lomuto_partition(sorting, pivot_index + 1, right) def lomuto_partition(sorting: list, left: int, right: int) -> int: """ Example: >>> lomuto_partition([1,5,7,6], 0, 3) 2 """ pivot = sorting[right] store_index = left for i in range(left, right): if sorting[i] < pivot: sorting[store_index], sorting[i] = sorting[i], sorting[store_index] store_index += 1 sorting[right], sorting[store_index] = sorting[store_index], sorting[right] return store_index def three_way_radix_quicksort(sorting: list) -> list: """ Three-way radix quicksort: https://en.wikipedia.org/wiki/Quicksort#Three-way_radix_quicksort First divide the list into three parts. Then recursively sort the "less than" and "greater than" partitions. >>> three_way_radix_quicksort([]) [] >>> three_way_radix_quicksort([1]) [1] >>> three_way_radix_quicksort([-5, -2, 1, -2, 0, 1]) [-5, -2, -2, 0, 1, 1] >>> three_way_radix_quicksort([1, 2, 5, 1, 2, 0, 0, 5, 2, -1]) [-1, 0, 0, 1, 1, 2, 2, 2, 5, 5] """ if len(sorting) <= 1: return sorting return ( three_way_radix_quicksort([i for i in sorting if i < sorting[0]]) + [i for i in sorting if i == sorting[0]] + three_way_radix_quicksort([i for i in sorting if i > sorting[0]]) ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] quick_sort_3partition(unsorted, 0, len(unsorted) - 1) print(unsorted)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/quick_sort.py
sorts/quick_sort.py
""" A pure Python implementation of the quick sort algorithm For doctests run following command: python3 -m doctest -v quick_sort.py For manual testing run: python3 quick_sort.py """ from __future__ import annotations from random import randrange def quick_sort(collection: list) -> list: """A pure Python implementation of quicksort algorithm. :param collection: a mutable collection of comparable items :return: the same collection ordered in ascending order Examples: >>> quick_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> quick_sort([]) [] >>> quick_sort([-2, 5, 0, -45]) [-45, -2, 0, 5] """ # Base case: if the collection has 0 or 1 elements, it is already sorted if len(collection) < 2: return collection # Randomly select a pivot index and remove the pivot element from the collection pivot_index = randrange(len(collection)) pivot = collection.pop(pivot_index) # Partition the remaining elements into two groups: lesser or equal, and greater lesser = [item for item in collection if item <= pivot] greater = [item for item in collection if item > pivot] # Recursively sort the lesser and greater groups, and combine with the pivot return [*quick_sort(lesser), pivot, *quick_sort(greater)] if __name__ == "__main__": # Get user input and convert it into a list of integers user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] # Print the result of sorting the user-provided list print(quick_sort(unsorted))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/odd_even_sort.py
sorts/odd_even_sort.py
""" Odd even sort implementation. https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort """ def odd_even_sort(input_list: list) -> list: """ Sort input with odd even sort. This algorithm uses the same idea of bubblesort, but by first dividing in two phase (odd and even). Originally developed for use on parallel processors with local interconnections. :param collection: mutable ordered sequence of elements :return: same collection in ascending order Examples: >>> odd_even_sort([5 , 4 ,3 ,2 ,1]) [1, 2, 3, 4, 5] >>> odd_even_sort([]) [] >>> odd_even_sort([-10 ,-1 ,10 ,2]) [-10, -1, 2, 10] >>> odd_even_sort([1 ,2 ,3 ,4]) [1, 2, 3, 4] """ is_sorted = False while is_sorted is False: # Until all the indices are traversed keep looping is_sorted = True for i in range(0, len(input_list) - 1, 2): # iterating over all even indices if input_list[i] > input_list[i + 1]: input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i] # swapping if elements not in order is_sorted = False for i in range(1, len(input_list) - 1, 2): # iterating over all odd indices if input_list[i] > input_list[i + 1]: input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i] # swapping if elements not in order is_sorted = False return input_list if __name__ == "__main__": print("Enter list to be sorted") input_list = [int(x) for x in input().split()] # inputing elements of the list in one line sorted_list = odd_even_sort(input_list) print("The sorted list is") print(sorted_list)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/recursive_mergesort_array.py
sorts/recursive_mergesort_array.py
"""A merge sort which accepts an array as input and recursively splits an array in half and sorts and combines them. """ """https://en.wikipedia.org/wiki/Merge_sort """ def merge(arr: list[int]) -> list[int]: """Return a sorted array. >>> merge([10,9,8,7,6,5,4,3,2,1]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> merge([1,2,3,4,5,6,7,8,9,10]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> merge([10,22,1,2,3,9,15,23]) [1, 2, 3, 9, 10, 15, 22, 23] >>> merge([100]) [100] >>> merge([]) [] """ if len(arr) > 1: middle_length = len(arr) // 2 # Finds the middle of the array left_array = arr[ :middle_length ] # Creates an array of the elements in the first half. right_array = arr[ middle_length: ] # Creates an array of the elements in the second half. left_size = len(left_array) right_size = len(right_array) merge(left_array) # Starts sorting the left. merge(right_array) # Starts sorting the right left_index = 0 # Left Counter right_index = 0 # Right Counter index = 0 # Position Counter while ( left_index < left_size and right_index < right_size ): # Runs until the lowers size of the left and right are sorted. if left_array[left_index] < right_array[right_index]: arr[index] = left_array[left_index] left_index += 1 else: arr[index] = right_array[right_index] right_index += 1 index += 1 while ( left_index < left_size ): # Adds the left over elements in the left half of the array arr[index] = left_array[left_index] left_index += 1 index += 1 while ( right_index < right_size ): # Adds the left over elements in the right half of the array arr[index] = right_array[right_index] right_index += 1 index += 1 return arr 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/sorts/stooge_sort.py
sorts/stooge_sort.py
def stooge_sort(arr: list[int]) -> list[int]: """ Examples: >>> stooge_sort([18.1, 0, -7.1, -1, 2, 2]) [-7.1, -1, 0, 2, 2, 18.1] >>> stooge_sort([]) [] """ stooge(arr, 0, len(arr) - 1) return arr def stooge(arr: list[int], i: int, h: int) -> None: if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: arr[i], arr[h] = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: t = (int)((h - i + 1) / 3) # Recursively sort first 2/3 elements stooge(arr, i, (h - t)) # Recursively sort last 2/3 elements stooge(arr, i + t, (h)) # Recursively sort first 2/3 elements stooge(arr, i, (h - t)) if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(stooge_sort(unsorted))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/heap_sort.py
sorts/heap_sort.py
""" A pure Python implementation of the heap sort algorithm. """ def heapify(unsorted: list[int], index: int, heap_size: int) -> None: """ :param unsorted: unsorted list containing integers numbers :param index: index :param heap_size: size of the heap :return: None >>> unsorted = [1, 4, 3, 5, 2] >>> heapify(unsorted, 0, len(unsorted)) >>> unsorted [4, 5, 3, 1, 2] >>> heapify(unsorted, 0, len(unsorted)) >>> unsorted [5, 4, 3, 1, 2] """ largest = index left_index = 2 * index + 1 right_index = 2 * index + 2 if left_index < heap_size and unsorted[left_index] > unsorted[largest]: largest = left_index if right_index < heap_size and unsorted[right_index] > unsorted[largest]: largest = right_index if largest != index: unsorted[largest], unsorted[index] = (unsorted[index], unsorted[largest]) heapify(unsorted, largest, heap_size) def heap_sort(unsorted: list[int]) -> list[int]: """ A pure Python implementation of the heap sort algorithm :param collection: a mutable ordered collection of heterogeneous comparable items :return: the same collection ordered by ascending Examples: >>> heap_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> heap_sort([]) [] >>> heap_sort([-2, -5, -45]) [-45, -5, -2] >>> heap_sort([3, 7, 9, 28, 123, -5, 8, -30, -200, 0, 4]) [-200, -30, -5, 0, 3, 4, 7, 8, 9, 28, 123] """ n = len(unsorted) for i in range(n // 2 - 1, -1, -1): heapify(unsorted, i, n) for i in range(n - 1, 0, -1): unsorted[0], unsorted[i] = unsorted[i], unsorted[0] heapify(unsorted, 0, i) return unsorted if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma:\n").strip() if user_input: unsorted = [int(item) for item in user_input.split(",")] print(f"{heap_sort(unsorted) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/comb_sort.py
sorts/comb_sort.py
""" This is pure Python implementation of comb sort algorithm. Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz Dobosiewicz in 1980. It was rediscovered by Stephen Lacey and Richard Box in 1991. Comb sort improves on bubble sort algorithm. In bubble sort, distance (or gap) between two compared elements is always one. Comb sort improvement is that gap can be much more than 1, in order to prevent slowing down by small values at the end of a list. More info on: https://en.wikipedia.org/wiki/Comb_sort For doctests run following command: python -m doctest -v comb_sort.py or python3 -m doctest -v comb_sort.py For manual testing run: python comb_sort.py """ def comb_sort(data: list) -> list: """Pure implementation of comb sort algorithm in Python :param data: mutable collection with comparable items :return: the same collection in ascending order Examples: >>> comb_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> comb_sort([]) [] >>> comb_sort([99, 45, -7, 8, 2, 0, -15, 3]) [-15, -7, 0, 2, 3, 8, 45, 99] """ shrink_factor = 1.3 gap = len(data) completed = False while not completed: # Update the gap value for a next comb gap = int(gap / shrink_factor) if gap <= 1: completed = True index = 0 while index + gap < len(data): if data[index] > data[index + gap]: # Swap values data[index], data[index + gap] = data[index + gap], data[index] completed = False index += 1 return data if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(comb_sort(unsorted))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/tim_sort.py
sorts/tim_sort.py
def binary_search(lst, item, start, end): if start == end: return start if lst[start] > item else start + 1 if start > end: return start mid = (start + end) // 2 if lst[mid] < item: return binary_search(lst, item, mid + 1, end) elif lst[mid] > item: return binary_search(lst, item, start, mid - 1) else: return mid def insertion_sort(lst): length = len(lst) for index in range(1, length): value = lst[index] pos = binary_search(lst, value, 0, index - 1) lst = [*lst[:pos], value, *lst[pos:index], *lst[index + 1 :]] return lst def merge(left, right): if not left: return right if not right: return left if left[0] < right[0]: return [left[0], *merge(left[1:], right)] return [right[0], *merge(left, right[1:])] def tim_sort(lst): """ >>> tim_sort("Python") ['P', 'h', 'n', 'o', 't', 'y'] >>> tim_sort((1.1, 1, 0, -1, -1.1)) [-1.1, -1, 0, 1, 1.1] >>> tim_sort(list(reversed(list(range(7))))) [0, 1, 2, 3, 4, 5, 6] >>> tim_sort([3, 2, 1]) == insertion_sort([3, 2, 1]) True >>> tim_sort([3, 2, 1]) == sorted([3, 2, 1]) True """ length = len(lst) runs, sorted_runs = [], [] new_run = [lst[0]] sorted_array = [] i = 1 while i < length: if lst[i] < lst[i - 1]: runs.append(new_run) new_run = [lst[i]] else: new_run.append(lst[i]) i += 1 runs.append(new_run) for run in runs: sorted_runs.append(insertion_sort(run)) for run in sorted_runs: sorted_array = merge(sorted_array, run) return sorted_array def main(): lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7] sorted_lst = tim_sort(lst) print(sorted_lst) if __name__ == "__main__": main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/external_sort.py
sorts/external_sort.py
#!/usr/bin/env python # # Sort large text files in a minimum amount of memory # import argparse import os class FileSplitter: BLOCK_FILENAME_FORMAT = "block_{0}.dat" def __init__(self, filename): self.filename = filename self.block_filenames = [] def write_block(self, data, block_number): filename = self.BLOCK_FILENAME_FORMAT.format(block_number) with open(filename, "w") as file: file.write(data) self.block_filenames.append(filename) def get_block_filenames(self): return self.block_filenames def split(self, block_size, sort_key=None): i = 0 with open(self.filename) as file: while True: lines = file.readlines(block_size) if lines == []: break if sort_key is None: lines.sort() else: lines.sort(key=sort_key) self.write_block("".join(lines), i) i += 1 def cleanup(self): map(os.remove, self.block_filenames) class NWayMerge: def select(self, choices): min_index = -1 min_str = None for i in range(len(choices)): if min_str is None or choices[i] < min_str: min_index = i return min_index class FilesArray: def __init__(self, files): self.files = files self.empty = set() self.num_buffers = len(files) self.buffers = dict.fromkeys(range(self.num_buffers)) def get_dict(self): return { i: self.buffers[i] for i in range(self.num_buffers) if i not in self.empty } def refresh(self): for i in range(self.num_buffers): if self.buffers[i] is None and i not in self.empty: self.buffers[i] = self.files[i].readline() if self.buffers[i] == "": self.empty.add(i) self.files[i].close() return len(self.empty) != self.num_buffers def unshift(self, index): value = self.buffers[index] self.buffers[index] = None return value class FileMerger: def __init__(self, merge_strategy): self.merge_strategy = merge_strategy def merge(self, filenames, outfilename, buffer_size): buffers = FilesArray(self.get_file_handles(filenames, buffer_size)) with open(outfilename, "w", buffer_size) as outfile: while buffers.refresh(): min_index = self.merge_strategy.select(buffers.get_dict()) outfile.write(buffers.unshift(min_index)) def get_file_handles(self, filenames, buffer_size): files = {} for i in range(len(filenames)): files[i] = open(filenames[i], "r", buffer_size) # noqa: UP015 return files class ExternalSort: def __init__(self, block_size): self.block_size = block_size def sort(self, filename, sort_key=None): num_blocks = self.get_number_blocks(filename, self.block_size) splitter = FileSplitter(filename) splitter.split(self.block_size, sort_key) merger = FileMerger(NWayMerge()) buffer_size = self.block_size / (num_blocks + 1) merger.merge(splitter.get_block_filenames(), filename + ".out", buffer_size) splitter.cleanup() def get_number_blocks(self, filename, block_size): return (os.stat(filename).st_size / block_size) + 1 def parse_memory(string): if string[-1].lower() == "k": return int(string[:-1]) * 1024 elif string[-1].lower() == "m": return int(string[:-1]) * 1024 * 1024 elif string[-1].lower() == "g": return int(string[:-1]) * 1024 * 1024 * 1024 else: return int(string) def main(): parser = argparse.ArgumentParser() parser.add_argument( "-m", "--mem", help="amount of memory to use for sorting", default="100M" ) parser.add_argument( "filename", metavar="<filename>", nargs=1, help="name of file to sort" ) args = parser.parse_args() sorter = ExternalSort(parse_memory(args.mem)) sorter.sort(args.filename[0]) if __name__ == "__main__": main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/stalin_sort.py
sorts/stalin_sort.py
""" Stalin Sort algorithm: Removes elements that are out of order. Elements that are not greater than or equal to the previous element are discarded. Reference: https://medium.com/@kaweendra/the-ultimate-sorting-algorithm-6513d6968420 """ def stalin_sort(sequence: list[int]) -> list[int]: """ Sorts a list using the Stalin sort algorithm. >>> stalin_sort([4, 3, 5, 2, 1, 7]) [4, 5, 7] >>> stalin_sort([1, 2, 3, 4]) [1, 2, 3, 4] >>> stalin_sort([4, 5, 5, 2, 3]) [4, 5, 5] >>> stalin_sort([6, 11, 12, 4, 1, 5]) [6, 11, 12] >>> stalin_sort([5, 0, 4, 3]) [5] >>> stalin_sort([5, 4, 3, 2, 1]) [5] >>> stalin_sort([1, 2, 3, 4, 5]) [1, 2, 3, 4, 5] >>> stalin_sort([1, 2, 8, 7, 6]) [1, 2, 8] """ result = [sequence[0]] for element in sequence[1:]: if element >= result[-1]: result.append(element) 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/sorts/patience_sort.py
sorts/patience_sort.py
from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge """ A pure Python implementation of the patience sort algorithm For more information: https://en.wikipedia.org/wiki/Patience_sorting This algorithm is based on the card game patience For doctests run following command: python3 -m doctest -v patience_sort.py For manual testing run: python3 patience_sort.py """ @total_ordering class Stack(list): def __lt__(self, other): return self[-1] < other[-1] def __eq__(self, other): return self[-1] == other[-1] def patience_sort(collection: list) -> list: """A pure implementation of patience sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> patience_sort([1, 9, 5, 21, 17, 6]) [1, 5, 6, 9, 17, 21] >>> patience_sort([]) [] >>> patience_sort([-3, -17, -48]) [-48, -17, -3] """ stacks: list[Stack] = [] # sort into stacks for element in collection: new_stacks = Stack([element]) i = bisect_left(stacks, new_stacks) if i != len(stacks): stacks[i].append(element) else: stacks.append(new_stacks) # use a heap-based merge to merge stack efficiently collection[:] = merge(*(reversed(stack) for stack in stacks)) return collection if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(patience_sort(unsorted))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/bogo_sort.py
sorts/bogo_sort.py
""" This is a pure Python implementation of the bogosort algorithm, also known as permutation sort, stupid sort, slowsort, shotgun sort, or monkey sort. Bogosort generates random permutations until it guesses the correct one. More info on: https://en.wikipedia.org/wiki/Bogosort For doctests run following command: python -m doctest -v bogo_sort.py or python3 -m doctest -v bogo_sort.py For manual testing run: python bogo_sort.py """ import random def bogo_sort(collection): """Pure implementation of the bogosort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> bogo_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> bogo_sort([]) [] >>> bogo_sort([-2, -5, -45]) [-45, -5, -2] """ def is_sorted(collection): for i in range(len(collection) - 1): if collection[i] > collection[i + 1]: return False return True while not is_sorted(collection): random.shuffle(collection) return collection if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(bogo_sort(unsorted))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/insertion_sort.py
sorts/insertion_sort.py
""" A pure Python implementation of the insertion sort algorithm This algorithm sorts a collection by comparing adjacent elements. When it finds that order is not respected, it moves the element compared backward until the order is correct. It then goes back directly to the element's initial position resuming forward comparison. For doctests run following command: python3 -m doctest -v insertion_sort.py For manual testing run: python3 insertion_sort.py """ from collections.abc import MutableSequence from typing import Any, Protocol, TypeVar class Comparable(Protocol): def __lt__(self, other: Any, /) -> bool: ... T = TypeVar("T", bound=Comparable) def insertion_sort[T: Comparable](collection: MutableSequence[T]) -> MutableSequence[T]: """A pure Python implementation of the insertion sort algorithm :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> insertion_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> insertion_sort([]) == sorted([]) True >>> insertion_sort([-2, -5, -45]) == sorted([-2, -5, -45]) True >>> insertion_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c']) True >>> import random >>> collection = random.sample(range(-50, 50), 100) >>> insertion_sort(collection) == sorted(collection) True >>> import string >>> collection = random.choices(string.ascii_letters + string.digits, k=100) >>> insertion_sort(collection) == sorted(collection) True """ for insert_index in range(1, len(collection)): insert_value = collection[insert_index] while insert_index > 0 and insert_value < collection[insert_index - 1]: collection[insert_index] = collection[insert_index - 1] insert_index -= 1 collection[insert_index] = insert_value return collection if __name__ == "__main__": from doctest import testmod testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(f"{insertion_sort(unsorted) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/shell_sort.py
sorts/shell_sort.py
""" https://en.wikipedia.org/wiki/Shellsort#Pseudocode """ def shell_sort(collection: list[int]) -> list[int]: """Pure implementation of shell sort algorithm in Python :param collection: Some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending >>> shell_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> shell_sort([]) [] >>> shell_sort([-2, -5, -45]) [-45, -5, -2] """ # Marcin Ciura's gap sequence gaps = [701, 301, 132, 57, 23, 10, 4, 1] for gap in gaps: for i in range(gap, len(collection)): insert_value = collection[i] j = i while j >= gap and collection[j - gap] > insert_value: collection[j] = collection[j - gap] j -= gap if j != i: collection[j] = insert_value return collection if __name__ == "__main__": from doctest import testmod testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(shell_sort(unsorted))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/pigeonhole_sort.py
sorts/pigeonhole_sort.py
# Python program to implement Pigeonhole Sorting in python # Algorithm for the pigeonhole sorting def pigeonhole_sort(a): """ >>> a = [8, 3, 2, 7, 4, 6, 8] >>> b = sorted(a) # a nondestructive sort >>> pigeonhole_sort(a) # a destructive sort >>> a == b True """ # size of range of values in the list (ie, number of pigeonholes we need) min_val = min(a) # min() finds the minimum value max_val = max(a) # max() finds the maximum value size = max_val - min_val + 1 # size is difference of max and min values plus one # list of pigeonholes of size equal to the variable size holes = [0] * size # Populate the pigeonholes. for x in a: assert isinstance(x, int), "integers only please" holes[x - min_val] += 1 # Putting the elements back into the array in an order. i = 0 for count in range(size): while holes[count] > 0: holes[count] -= 1 a[i] = count + min_val i += 1 def main(): a = [8, 3, 2, 7, 4, 6, 8] pigeonhole_sort(a) print("Sorted order is:", " ".join(a)) if __name__ == "__main__": main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/recursive_insertion_sort.py
sorts/recursive_insertion_sort.py
""" A recursive implementation of the insertion sort algorithm """ from __future__ import annotations def rec_insertion_sort(collection: list, n: int): """ Given a collection of numbers and its length, sorts the collections in ascending order :param collection: A mutable collection of comparable elements :param n: The length of collections >>> col = [1, 2, 1] >>> rec_insertion_sort(col, len(col)) >>> col [1, 1, 2] >>> col = [2, 1, 0, -1, -2] >>> rec_insertion_sort(col, len(col)) >>> col [-2, -1, 0, 1, 2] >>> col = [1] >>> rec_insertion_sort(col, len(col)) >>> col [1] """ # Checks if the entire collection has been sorted if len(collection) <= 1 or n <= 1: return insert_next(collection, n - 1) rec_insertion_sort(collection, n - 1) def insert_next(collection: list, index: int): """ Inserts the '(index-1)th' element into place >>> col = [3, 2, 4, 2] >>> insert_next(col, 1) >>> col [2, 3, 4, 2] >>> col = [3, 2, 3] >>> insert_next(col, 2) >>> col [3, 2, 3] >>> col = [] >>> insert_next(col, 1) >>> col [] """ # Checks order between adjacent elements if index >= len(collection) or collection[index - 1] <= collection[index]: return # Swaps adjacent elements since they are not in ascending order collection[index - 1], collection[index] = ( collection[index], collection[index - 1], ) insert_next(collection, index + 1) if __name__ == "__main__": numbers = input("Enter integers separated by spaces: ") number_list: list[int] = [int(num) for num in numbers.split()] rec_insertion_sort(number_list, len(number_list)) print(number_list)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/bitonic_sort.py
sorts/bitonic_sort.py
""" Python program for Bitonic Sort. Note that this program works only when size of input is a power of 2. """ from __future__ import annotations def comp_and_swap(array: list[int], index1: int, index2: int, direction: int) -> None: """Compare the value at given index1 and index2 of the array and swap them as per the given direction. The parameter direction indicates the sorting direction, ASCENDING(1) or DESCENDING(0); if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged. >>> arr = [12, 42, -21, 1] >>> comp_and_swap(arr, 1, 2, 1) >>> arr [12, -21, 42, 1] >>> comp_and_swap(arr, 1, 2, 0) >>> arr [12, 42, -21, 1] >>> comp_and_swap(arr, 0, 3, 1) >>> arr [1, 42, -21, 12] >>> comp_and_swap(arr, 0, 3, 0) >>> arr [12, 42, -21, 1] """ if (direction == 1 and array[index1] > array[index2]) or ( direction == 0 and array[index1] < array[index2] ): array[index1], array[index2] = array[index2], array[index1] def bitonic_merge(array: list[int], low: int, length: int, direction: int) -> None: """ It recursively sorts a bitonic sequence in ascending order, if direction = 1, and in descending if direction = 0. The sequence to be sorted starts at index position low, the parameter length is the number of elements to be sorted. >>> arr = [12, 42, -21, 1] >>> bitonic_merge(arr, 0, 4, 1) >>> arr [-21, 1, 12, 42] >>> bitonic_merge(arr, 0, 4, 0) >>> arr [42, 12, 1, -21] """ if length > 1: middle = int(length / 2) for i in range(low, low + middle): comp_and_swap(array, i, i + middle, direction) bitonic_merge(array, low, middle, direction) bitonic_merge(array, low + middle, middle, direction) def bitonic_sort(array: list[int], low: int, length: int, direction: int) -> None: """ This function first produces a bitonic sequence by recursively sorting its two halves in opposite sorting orders, and then calls bitonic_merge to make them in the same order. >>> arr = [12, 34, 92, -23, 0, -121, -167, 145] >>> bitonic_sort(arr, 0, 8, 1) >>> arr [-167, -121, -23, 0, 12, 34, 92, 145] >>> bitonic_sort(arr, 0, 8, 0) >>> arr [145, 92, 34, 12, 0, -23, -121, -167] """ if length > 1: middle = int(length / 2) bitonic_sort(array, low, middle, 1) bitonic_sort(array, low + middle, middle, 0) bitonic_merge(array, low, length, direction) if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item.strip()) for item in user_input.split(",")] bitonic_sort(unsorted, 0, len(unsorted), 1) print("\nSorted array in ascending order is: ", end="") print(*unsorted, sep=", ") bitonic_merge(unsorted, 0, len(unsorted), 0) print("Sorted array in descending order is: ", end="") print(*unsorted, sep=", ")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/odd_even_transposition_single_threaded.py
sorts/odd_even_transposition_single_threaded.py
""" Source: https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort This is a non-parallelized implementation of odd-even transposition sort. Normally the swaps in each set happen simultaneously, without that the algorithm is no better than bubble sort. """ def odd_even_transposition(arr: list) -> list: """ >>> odd_even_transposition([5, 4, 3, 2, 1]) [1, 2, 3, 4, 5] >>> odd_even_transposition([13, 11, 18, 0, -1]) [-1, 0, 11, 13, 18] >>> odd_even_transposition([-.1, 1.1, .1, -2.9]) [-2.9, -0.1, 0.1, 1.1] """ arr_size = len(arr) for _ in range(arr_size): for i in range(_ % 2, arr_size - 1, 2): if arr[i + 1] < arr[i]: arr[i], arr[i + 1] = arr[i + 1], arr[i] return arr if __name__ == "__main__": arr = list(range(10, 0, -1)) print(f"Original: {arr}. Sorted: {odd_even_transposition(arr)}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/bucket_sort.py
sorts/bucket_sort.py
#!/usr/bin/env python3 """ Illustrate how to implement bucket sort algorithm. Author: OMKAR PATHAK This program will illustrate how to implement bucket sort algorithm Wikipedia says: Bucket sort, or bin sort, is a sorting algorithm that works by distributing the elements of an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm. It is a distribution sort, and is a cousin of radix sort in the most to least significant digit flavour. Bucket sort is a generalization of pigeonhole sort. Bucket sort can be implemented with comparisons and therefore can also be considered a comparison sort algorithm. The computational complexity estimates involve the number of buckets. Time Complexity of Solution: Worst case scenario occurs when all the elements are placed in a single bucket. The overall performance would then be dominated by the algorithm used to sort each bucket. In this case, O(n log n), because of TimSort Average Case O(n + (n^2)/k + k), where k is the number of buckets If k = O(n), time complexity is O(n) Source: https://en.wikipedia.org/wiki/Bucket_sort """ from __future__ import annotations def bucket_sort(my_list: list, bucket_count: int = 10) -> list: """ >>> data = [-1, 2, -5, 0] >>> bucket_sort(data) == sorted(data) True >>> data = [9, 8, 7, 6, -12] >>> bucket_sort(data) == sorted(data) True >>> data = [.4, 1.2, .1, .2, -.9] >>> bucket_sort(data) == sorted(data) True >>> bucket_sort([]) == sorted([]) True >>> data = [-1e10, 1e10] >>> bucket_sort(data) == sorted(data) True >>> import random >>> collection = random.sample(range(-50, 50), 50) >>> bucket_sort(collection) == sorted(collection) True >>> data = [1, 2, 2, 1, 1, 3] >>> bucket_sort(data) == sorted(data) True >>> data = [5, 5, 5, 5, 5] >>> bucket_sort(data) == sorted(data) True >>> data = [1000, -1000, 500, -500, 0] >>> bucket_sort(data) == sorted(data) True >>> data = [5.5, 2.2, -1.1, 3.3, 0.0] >>> bucket_sort(data) == sorted(data) True >>> bucket_sort([1]) == [1] True >>> data = [-1.1, -1.5, -3.4, 2.5, 3.6, -3.3] >>> bucket_sort(data) == sorted(data) True >>> data = [9, 2, 7, 1, 5] >>> bucket_sort(data) == sorted(data) True """ if len(my_list) == 0 or bucket_count <= 0: return [] min_value, max_value = min(my_list), max(my_list) if min_value == max_value: return my_list bucket_size = (max_value - min_value) / bucket_count buckets: list[list] = [[] for _ in range(bucket_count)] for val in my_list: index = min(int((val - min_value) / bucket_size), bucket_count - 1) buckets[index].append(val) return [val for bucket in buckets for val in sorted(bucket)] if __name__ == "__main__": from doctest import testmod testmod() assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bucket_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15] assert bucket_sort([1.1, 1.2, -1.2, 0, 2.4]) == [-1.2, 0, 1.1, 1.2, 2.4] assert bucket_sort([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5] assert bucket_sort([-5, -1, -6, -2]) == [-6, -5, -2, -1]
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/dutch_national_flag_sort.py
sorts/dutch_national_flag_sort.py
""" A pure implementation of Dutch national flag (DNF) sort algorithm in Python. Dutch National Flag algorithm is an algorithm originally designed by Edsger Dijkstra. It is the most optimal sort for 3 unique values (eg. 0, 1, 2) in a sequence. DNF can sort a sequence of n size with [0 <= a[i] <= 2] at guaranteed O(n) complexity in a single pass. The flag of the Netherlands consists of three colors: white, red, and blue. The task is to randomly arrange balls of white, red, and blue in such a way that balls of the same color are placed together. DNF sorts a sequence of 0, 1, and 2's in linear time that does not consume any extra space. This algorithm can be implemented only on a sequence that contains three unique elements. 1) Time complexity is O(n). 2) Space complexity is O(1). More info on: https://en.wikipedia.org/wiki/Dutch_national_flag_problem For doctests run following command: python3 -m doctest -v dutch_national_flag_sort.py For manual testing run: python dnf_sort.py """ # Python program to sort a sequence containing only 0, 1 and 2 in a single pass. red = 0 # The first color of the flag. white = 1 # The second color of the flag. blue = 2 # The third color of the flag. colors = (red, white, blue) def dutch_national_flag_sort(sequence: list) -> list: """ A pure Python implementation of Dutch National Flag sort algorithm. :param data: 3 unique integer values (e.g., 0, 1, 2) in an sequence :return: The same collection in ascending order >>> dutch_national_flag_sort([]) [] >>> dutch_national_flag_sort([0]) [0] >>> dutch_national_flag_sort([2, 1, 0, 0, 1, 2]) [0, 0, 1, 1, 2, 2] >>> dutch_national_flag_sort([0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]) [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2] >>> dutch_national_flag_sort("abacab") Traceback (most recent call last): ... ValueError: The elements inside the sequence must contains only (0, 1, 2) values >>> dutch_national_flag_sort("Abacab") Traceback (most recent call last): ... ValueError: The elements inside the sequence must contains only (0, 1, 2) values >>> dutch_national_flag_sort([3, 2, 3, 1, 3, 0, 3]) Traceback (most recent call last): ... ValueError: The elements inside the sequence must contains only (0, 1, 2) values >>> dutch_national_flag_sort([-1, 2, -1, 1, -1, 0, -1]) Traceback (most recent call last): ... ValueError: The elements inside the sequence must contains only (0, 1, 2) values >>> dutch_national_flag_sort([1.1, 2, 1.1, 1, 1.1, 0, 1.1]) Traceback (most recent call last): ... ValueError: The elements inside the sequence must contains only (0, 1, 2) values """ if not sequence: return [] if len(sequence) == 1: return list(sequence) low = 0 high = len(sequence) - 1 mid = 0 while mid <= high: if sequence[mid] == colors[0]: sequence[low], sequence[mid] = sequence[mid], sequence[low] low += 1 mid += 1 elif sequence[mid] == colors[1]: mid += 1 elif sequence[mid] == colors[2]: sequence[mid], sequence[high] = sequence[high], sequence[mid] high -= 1 else: msg = f"The elements inside the sequence must contains only {colors} values" raise ValueError(msg) return sequence if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by commas:\n").strip() unsorted = [int(item.strip()) for item in user_input.split(",")] print(f"{dutch_national_flag_sort(unsorted)}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/radix_sort.py
sorts/radix_sort.py
""" This is a pure Python implementation of the radix sort algorithm Source: https://en.wikipedia.org/wiki/Radix_sort """ from __future__ import annotations RADIX = 10 def radix_sort(list_of_ints: list[int]) -> list[int]: """ Examples: >>> radix_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> radix_sort(list(range(15))) == sorted(range(15)) True >>> radix_sort(list(range(14,-1,-1))) == sorted(range(15)) True >>> radix_sort([1,100,10,1000]) == sorted([1,100,10,1000]) True """ placement = 1 max_digit = max(list_of_ints) while placement <= max_digit: # declare and initialize empty buckets buckets: list[list] = [[] for _ in range(RADIX)] # split list_of_ints between the buckets for i in list_of_ints: tmp = int((i / placement) % RADIX) buckets[tmp].append(i) # put each buckets' contents into list_of_ints a = 0 for b in range(RADIX): for i in buckets[b]: list_of_ints[a] = i a += 1 # move to next placement *= RADIX return list_of_ints 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/sorts/circle_sort.py
sorts/circle_sort.py
""" This is a Python implementation of the circle sort algorithm For doctests run following command: python3 -m doctest -v circle_sort.py For manual testing run: python3 circle_sort.py """ def circle_sort(collection: list) -> list: """A pure Python implementation of circle sort algorithm :param collection: a mutable collection of comparable items in any order :return: the same collection in ascending order Examples: >>> circle_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> circle_sort([]) [] >>> circle_sort([-2, 5, 0, -45]) [-45, -2, 0, 5] >>> collections = ([], [0, 5, 3, 2, 2], [-2, 5, 0, -45]) >>> all(sorted(collection) == circle_sort(collection) for collection in collections) True """ if len(collection) < 2: return collection def circle_sort_util(collection: list, low: int, high: int) -> bool: """ >>> arr = [5,4,3,2,1] >>> circle_sort_util(lst, 0, 2) True >>> arr [3, 4, 5, 2, 1] """ swapped = False if low == high: return swapped left = low right = high while left < right: if collection[left] > collection[right]: collection[left], collection[right] = ( collection[right], collection[left], ) swapped = True left += 1 right -= 1 if left == right and collection[left] > collection[right + 1]: collection[left], collection[right + 1] = ( collection[right + 1], collection[left], ) swapped = True mid = low + int((high - low) / 2) left_swap = circle_sort_util(collection, low, mid) right_swap = circle_sort_util(collection, mid + 1, high) return swapped or left_swap or right_swap is_not_sorted = True while is_not_sorted is True: is_not_sorted = circle_sort_util(collection, 0, len(collection) - 1) return collection if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(circle_sort(unsorted))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/natural_sort.py
sorts/natural_sort.py
from __future__ import annotations import re def natural_sort(input_list: list[str]) -> list[str]: """ Sort the given list of strings in the way that humans expect. The normal Python sort algorithm sorts lexicographically, so you might not get the results that you expect... >>> example1 = ['2 ft 7 in', '1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '7 ft 6 in'] >>> sorted(example1) ['1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '2 ft 7 in', '7 ft 6 in'] >>> # The natural sort algorithm sort based on meaning and not computer code point. >>> natural_sort(example1) ['1 ft 5 in', '2 ft 7 in', '2 ft 11 in', '7 ft 6 in', '10 ft 2 in'] >>> example2 = ['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9'] >>> sorted(example2) ['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9'] >>> natural_sort(example2) ['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13'] """ def alphanum_key(key): return [int(s) if s.isdigit() else s.lower() for s in re.split("([0-9]+)", key)] return sorted(input_list, key=alphanum_key) 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/sorts/topological_sort.py
sorts/topological_sort.py
"""Topological Sort.""" # a # / \ # b c # / \ # d e edges: dict[str, list[str]] = { "a": ["c", "b"], "b": ["d", "e"], "c": [], "d": [], "e": [], } vertices: list[str] = ["a", "b", "c", "d", "e"] def topological_sort(start: str, visited: list[str], sort: list[str]) -> list[str]: """Perform topological sort on a directed acyclic graph.""" current = start # add current to visited visited.append(current) neighbors = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: sort = topological_sort(neighbor, visited, sort) # if all neighbors visited add current to sort sort.append(current) # if all vertices haven't been visited select a new one to visit if len(visited) != len(vertices): for vertice in vertices: if vertice not in visited: sort = topological_sort(vertice, visited, sort) # return sort return sort if __name__ == "__main__": sort = topological_sort("a", [], []) print(sort)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/pancake_sort.py
sorts/pancake_sort.py
""" This is a pure Python implementation of the pancake sort algorithm For doctests run following command: python3 -m doctest -v pancake_sort.py or python -m doctest -v pancake_sort.py For manual testing run: python pancake_sort.py """ def pancake_sort(arr): """Sort Array with Pancake Sort. :param arr: Collection containing comparable items :return: Collection ordered in ascending order of items Examples: >>> pancake_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> pancake_sort([]) [] >>> pancake_sort([-2, -5, -45]) [-45, -5, -2] """ cur = len(arr) while cur > 1: # Find the maximum number in arr mi = arr.index(max(arr[0:cur])) # Reverse from 0 to mi arr = arr[mi::-1] + arr[mi + 1 : len(arr)] # Reverse whole list arr = arr[cur - 1 :: -1] + arr[cur : len(arr)] cur -= 1 return arr if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(pancake_sort(unsorted))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/slowsort.py
sorts/slowsort.py
""" Slowsort is a sorting algorithm. It is of humorous nature and not useful. It's based on the principle of multiply and surrender, a tongue-in-cheek joke of divide and conquer. It was published in 1986 by Andrei Broder and Jorge Stolfi in their paper Pessimal Algorithms and Simplexity Analysis (a parody of optimal algorithms and complexity analysis). Source: https://en.wikipedia.org/wiki/Slowsort """ from __future__ import annotations def slowsort(sequence: list, start: int | None = None, end: int | None = None) -> None: """ Sorts sequence[start..end] (both inclusive) in-place. start defaults to 0 if not given. end defaults to len(sequence) - 1 if not given. It returns None. >>> seq = [1, 6, 2, 5, 3, 4, 4, 5]; slowsort(seq); seq [1, 2, 3, 4, 4, 5, 5, 6] >>> seq = []; slowsort(seq); seq [] >>> seq = [2]; slowsort(seq); seq [2] >>> seq = [1, 2, 3, 4]; slowsort(seq); seq [1, 2, 3, 4] >>> seq = [4, 3, 2, 1]; slowsort(seq); seq [1, 2, 3, 4] >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, 2, 7); seq [9, 8, 2, 3, 4, 5, 6, 7, 1, 0] >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, end = 4); seq [5, 6, 7, 8, 9, 4, 3, 2, 1, 0] >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, start = 5); seq [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] """ if start is None: start = 0 if end is None: end = len(sequence) - 1 if start >= end: return mid = (start + end) // 2 slowsort(sequence, start, mid) slowsort(sequence, mid + 1, end) if sequence[end] < sequence[mid]: sequence[end], sequence[mid] = sequence[mid], sequence[end] slowsort(sequence, start, end - 1) 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/sorts/selection_sort.py
sorts/selection_sort.py
def selection_sort(collection: list[int]) -> list[int]: """ Sorts a list in ascending order using the selection sort algorithm. :param collection: A list of integers to be sorted. :return: The sorted list. Examples: >>> selection_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> selection_sort([]) [] >>> selection_sort([-2, -5, -45]) [-45, -5, -2] """ length = len(collection) for i in range(length - 1): min_index = i for k in range(i + 1, length): if collection[k] < collection[min_index]: min_index = k if min_index != i: collection[i], collection[min_index] = collection[min_index], collection[i] return collection if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] sorted_list = selection_sort(unsorted) print("Sorted List:", sorted_list)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/cyclic_sort.py
sorts/cyclic_sort.py
""" This is a pure Python implementation of the Cyclic Sort algorithm. For doctests run following command: python -m doctest -v cyclic_sort.py or python3 -m doctest -v cyclic_sort.py For manual testing run: python cyclic_sort.py or python3 cyclic_sort.py """ def cyclic_sort(nums: list[int]) -> list[int]: """ Sorts the input list of n integers from 1 to n in-place using the Cyclic Sort algorithm. :param nums: List of n integers from 1 to n to be sorted. :return: The same list sorted in ascending order. Time complexity: O(n), where n is the number of integers in the list. Examples: >>> cyclic_sort([]) [] >>> cyclic_sort([3, 5, 2, 1, 4]) [1, 2, 3, 4, 5] """ # Perform cyclic sort index = 0 while index < len(nums): # Calculate the correct index for the current element correct_index = nums[index] - 1 # If the current element is not at its correct position, # swap it with the element at its correct index if index != correct_index: nums[index], nums[correct_index] = nums[correct_index], nums[index] else: # If the current element is already in its correct position, # move to the next element index += 1 return nums if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(*cyclic_sort(unsorted), sep=",")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/__init__.py
sorts/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/merge_sort.py
sorts/merge_sort.py
""" This is a pure Python implementation of the merge sort algorithm. For doctests run following command: python -m doctest -v merge_sort.py or python3 -m doctest -v merge_sort.py For manual testing run: python merge_sort.py """ def merge_sort(collection: list) -> list: """ Sorts a list using the merge sort algorithm. :param collection: A mutable ordered collection with comparable items. :return: The same collection ordered in ascending order. Time Complexity: O(n log n) Space Complexity: O(n) Examples: >>> merge_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> merge_sort([]) [] >>> merge_sort([-2, -5, -45]) [-45, -5, -2] """ def merge(left: list, right: list) -> list: """ Merge two sorted lists into a single sorted list. :param left: Left collection :param right: Right collection :return: Merged result """ result = [] while left and right: result.append(left.pop(0) if left[0] <= right[0] else right.pop(0)) result.extend(left) result.extend(right) return result if len(collection) <= 1: return collection mid_index = len(collection) // 2 return merge(merge_sort(collection[:mid_index]), merge_sort(collection[mid_index:])) if __name__ == "__main__": import doctest doctest.testmod() try: user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] sorted_list = merge_sort(unsorted) print(*sorted_list, sep=",") except ValueError: print("Invalid input. Please enter valid integers separated by commas.")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/cycle_sort.py
sorts/cycle_sort.py
""" Code contributed by Honey Sharma Source: https://en.wikipedia.org/wiki/Cycle_sort """ def cycle_sort(array: list) -> list: """ >>> cycle_sort([4, 3, 2, 1]) [1, 2, 3, 4] >>> cycle_sort([-4, 20, 0, -50, 100, -1]) [-50, -4, -1, 0, 20, 100] >>> cycle_sort([-.1, -.2, 1.3, -.8]) [-0.8, -0.2, -0.1, 1.3] >>> cycle_sort([]) [] """ array_len = len(array) for cycle_start in range(array_len - 1): item = array[cycle_start] pos = cycle_start for i in range(cycle_start + 1, array_len): if array[i] < item: pos += 1 if pos == cycle_start: continue while item == array[pos]: pos += 1 array[pos], item = item, array[pos] while pos != cycle_start: pos = cycle_start for i in range(cycle_start + 1, array_len): if array[i] < item: pos += 1 while item == array[pos]: pos += 1 array[pos], item = item, array[pos] return array if __name__ == "__main__": assert cycle_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert cycle_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/tree_sort.py
sorts/tree_sort.py
""" Tree_sort algorithm. Build a Binary Search Tree and then iterate thru it to get a sorted list. """ from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass @dataclass class Node: val: int left: Node | None = None right: Node | None = None def __iter__(self) -> Iterator[int]: if self.left: yield from self.left yield self.val if self.right: yield from self.right def __len__(self) -> int: return sum(1 for _ in self) def insert(self, val: int) -> None: if val < self.val: if self.left is None: self.left = Node(val) else: self.left.insert(val) elif val > self.val: if self.right is None: self.right = Node(val) else: self.right.insert(val) def tree_sort(arr: list[int]) -> tuple[int, ...]: """ >>> tree_sort([]) () >>> tree_sort((1,)) (1,) >>> tree_sort((1, 2)) (1, 2) >>> tree_sort([5, 2, 7]) (2, 5, 7) >>> tree_sort((5, -4, 9, 2, 7)) (-4, 2, 5, 7, 9) >>> tree_sort([5, 6, 1, -1, 4, 37, 2, 7]) (-1, 1, 2, 4, 5, 6, 7, 37) # >>> tree_sort(range(10, -10, -1)) == tuple(sorted(range(10, -10, -1))) # True """ if len(arr) == 0: return tuple(arr) root = Node(arr[0]) for item in arr[1:]: root.insert(item) return tuple(root) if __name__ == "__main__": import doctest doctest.testmod() print(f"{tree_sort([5, 6, 1, -1, 4, 37, -3, 7]) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false