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/divide_and_conquer/kth_order_statistic.py | divide_and_conquer/kth_order_statistic.py | """
Find the kth smallest element in linear time using divide and conquer.
Recall we can do this trivially in O(nlogn) time. Sort the list and
access kth element in constant time.
This is a divide and conquer algorithm that can find a solution in O(n) time.
For more information of this algorithm:
https://web.stanford.edu/class/archive/cs/cs161/cs161.1138/lectures/08/Small08.pdf
"""
from __future__ import annotations
from random import choice
def random_pivot(lst):
"""
Choose a random pivot for the list.
We can use a more sophisticated algorithm here, such as the median-of-medians
algorithm.
"""
return choice(lst)
def kth_number(lst: list[int], k: int) -> int:
"""
Return the kth smallest number in lst.
>>> kth_number([2, 1, 3, 4, 5], 3)
3
>>> kth_number([2, 1, 3, 4, 5], 1)
1
>>> kth_number([2, 1, 3, 4, 5], 5)
5
>>> kth_number([3, 2, 5, 6, 7, 8], 2)
3
>>> kth_number([25, 21, 98, 100, 76, 22, 43, 60, 89, 87], 4)
43
"""
# pick a pivot and separate into list based on pivot.
pivot = random_pivot(lst)
# partition based on pivot
# linear time
small = [e for e in lst if e < pivot]
big = [e for e in lst if e > pivot]
# if we get lucky, pivot might be the element we want.
# we can easily see this:
# small (elements smaller than k)
# + pivot (kth element)
# + big (elements larger than k)
if len(small) == k - 1:
return pivot
# pivot is in elements bigger than k
elif len(small) < k - 1:
return kth_number(big, k - len(small) - 1)
# pivot is in elements smaller than k
else:
return kth_number(small, k)
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/divide_and_conquer/max_difference_pair.py | divide_and_conquer/max_difference_pair.py | def max_difference(a: list[int]) -> tuple[int, int]:
"""
We are given an array A[1..n] of integers, n >= 1. We want to
find a pair of indices (i, j) such that
1 <= i <= j <= n and A[j] - A[i] is as large as possible.
Explanation:
https://www.geeksforgeeks.org/maximum-difference-between-two-elements/
>>> max_difference([5, 11, 2, 1, 7, 9, 0, 7])
(1, 9)
"""
# base case
if len(a) == 1:
return a[0], a[0]
else:
# split A into half.
first = a[: len(a) // 2]
second = a[len(a) // 2 :]
# 2 sub problems, 1/2 of original size.
small1, big1 = max_difference(first)
small2, big2 = max_difference(second)
# get min of first and max of second
# linear time
min_first = min(first)
max_second = max(second)
# 3 cases, either (small1, big1),
# (min_first, max_second), (small2, big2)
# constant comparisons
if big2 - small2 > max_second - min_first and big2 - small2 > big1 - small1:
return small2, big2
elif big1 - small1 > max_second - min_first:
return small1, big1
else:
return min_first, max_second
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/strings/bitap_string_match.py | strings/bitap_string_match.py | """
Bitap exact string matching
https://en.wikipedia.org/wiki/Bitap_algorithm
Searches for a pattern inside text, and returns the index of the first occurrence
of the pattern. Both text and pattern consist of lowercase alphabetical characters only.
Complexity: O(m*n)
n = length of text
m = length of pattern
Python doctests can be run using this command:
python3 -m doctest -v bitap_string_match.py
"""
def bitap_string_match(text: str, pattern: str) -> int:
"""
Retrieves the index of the first occurrence of pattern in text.
Args:
text: A string consisting only of lowercase alphabetical characters.
pattern: A string consisting only of lowercase alphabetical characters.
Returns:
int: The index where pattern first occurs. Return -1 if not found.
>>> bitap_string_match('abdabababc', 'ababc')
5
>>> bitap_string_match('aaaaaaaaaaaaaaaaaa', 'a')
0
>>> bitap_string_match('zxywsijdfosdfnso', 'zxywsijdfosdfnso')
0
>>> bitap_string_match('abdabababc', '')
0
>>> bitap_string_match('abdabababc', 'c')
9
>>> bitap_string_match('abdabababc', 'fofosdfo')
-1
>>> bitap_string_match('abdab', 'fofosdfo')
-1
"""
if not pattern:
return 0
m = len(pattern)
if m > len(text):
return -1
# Initial state of bit string 1110
state = ~1
# Bit = 0 if character appears at index, and 1 otherwise
pattern_mask: list[int] = [~0] * 27 # 1111
for i, char in enumerate(pattern):
# For the pattern mask for this character, set the bit to 0 for each i
# the character appears.
pattern_index: int = ord(char) - ord("a")
pattern_mask[pattern_index] &= ~(1 << i)
for i, char in enumerate(text):
text_index = ord(char) - ord("a")
# If this character does not appear in pattern, it's pattern mask is 1111.
# Performing a bitwise OR between state and 1111 will reset the state to 1111
# and start searching the start of pattern again.
state |= pattern_mask[text_index]
state <<= 1
# If the mth bit (counting right to left) of the state is 0, then we have
# found pattern in text
if (state & (1 << m)) == 0:
return i - m + 1
return -1
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/strings/upper.py | strings/upper.py | def upper(word: str) -> str:
"""
Convert an entire string to ASCII uppercase letters by looking for lowercase ASCII
letters and subtracting 32 from their integer representation to get the uppercase
letter.
>>> upper("wow")
'WOW'
>>> upper("Hello")
'HELLO'
>>> upper("WHAT")
'WHAT'
>>> upper("wh[]32")
'WH[]32'
"""
return "".join(chr(ord(char) - 32) if "a" <= char <= "z" else char for char in word)
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/strings/levenshtein_distance.py | strings/levenshtein_distance.py | from collections.abc import Callable
def levenshtein_distance(first_word: str, second_word: str) -> int:
"""
Implementation of the Levenshtein distance in Python.
:param first_word: the first word to measure the difference.
:param second_word: the second word to measure the difference.
:return: the levenshtein distance between the two words.
Examples:
>>> levenshtein_distance("planet", "planetary")
3
>>> levenshtein_distance("", "test")
4
>>> levenshtein_distance("book", "back")
2
>>> levenshtein_distance("book", "book")
0
>>> levenshtein_distance("test", "")
4
>>> levenshtein_distance("", "")
0
>>> levenshtein_distance("orchestration", "container")
10
"""
# The longer word should come first
if len(first_word) < len(second_word):
return levenshtein_distance(second_word, first_word)
if len(second_word) == 0:
return len(first_word)
previous_row = list(range(len(second_word) + 1))
for i, c1 in enumerate(first_word):
current_row = [i + 1]
for j, c2 in enumerate(second_word):
# Calculate insertions, deletions, and substitutions
insertions = previous_row[j + 1] + 1
deletions = current_row[j] + 1
substitutions = previous_row[j] + (c1 != c2)
# Get the minimum to append to the current row
current_row.append(min(insertions, deletions, substitutions))
# Store the previous row
previous_row = current_row
# Returns the last element (distance)
return previous_row[-1]
def levenshtein_distance_optimized(first_word: str, second_word: str) -> int:
"""
Compute the Levenshtein distance between two words (strings).
The function is optimized for efficiency by modifying rows in place.
:param first_word: the first word to measure the difference.
:param second_word: the second word to measure the difference.
:return: the Levenshtein distance between the two words.
Examples:
>>> levenshtein_distance_optimized("planet", "planetary")
3
>>> levenshtein_distance_optimized("", "test")
4
>>> levenshtein_distance_optimized("book", "back")
2
>>> levenshtein_distance_optimized("book", "book")
0
>>> levenshtein_distance_optimized("test", "")
4
>>> levenshtein_distance_optimized("", "")
0
>>> levenshtein_distance_optimized("orchestration", "container")
10
"""
if len(first_word) < len(second_word):
return levenshtein_distance_optimized(second_word, first_word)
if len(second_word) == 0:
return len(first_word)
previous_row = list(range(len(second_word) + 1))
for i, c1 in enumerate(first_word):
current_row = [i + 1] + [0] * len(second_word)
for j, c2 in enumerate(second_word):
insertions = previous_row[j + 1] + 1
deletions = current_row[j] + 1
substitutions = previous_row[j] + (c1 != c2)
current_row[j + 1] = min(insertions, deletions, substitutions)
previous_row = current_row
return previous_row[-1]
def benchmark_levenshtein_distance(func: Callable) -> None:
"""
Benchmark the Levenshtein distance function.
:param str: The name of the function being benchmarked.
:param func: The function to be benchmarked.
"""
from timeit import timeit
stmt = f"{func.__name__}('sitting', 'kitten')"
setup = f"from __main__ import {func.__name__}"
number = 25_000
result = timeit(stmt=stmt, setup=setup, number=number)
print(f"{func.__name__:<30} finished {number:,} runs in {result:.5f} seconds")
if __name__ == "__main__":
# Get user input for words
first_word = input("Enter the first word for Levenshtein distance:\n").strip()
second_word = input("Enter the second word for Levenshtein distance:\n").strip()
# Calculate and print Levenshtein distances
print(f"{levenshtein_distance(first_word, second_word) = }")
print(f"{levenshtein_distance_optimized(first_word, second_word) = }")
# Benchmark the Levenshtein distance functions
benchmark_levenshtein_distance(levenshtein_distance)
benchmark_levenshtein_distance(levenshtein_distance_optimized)
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/strip.py | strings/strip.py | def strip(user_string: str, characters: str = " \t\n\r") -> str:
"""
Remove leading and trailing characters (whitespace by default) from a string.
Args:
user_string (str): The input string to be stripped.
characters (str, optional): Optional characters to be removed
(default is whitespace).
Returns:
str: The stripped string.
Examples:
>>> strip(" hello ")
'hello'
>>> strip("...world...", ".")
'world'
>>> strip("123hello123", "123")
'hello'
>>> strip("")
''
"""
start = 0
end = len(user_string)
while start < end and user_string[start] in characters:
start += 1
while end > start and user_string[end - 1] in characters:
end -= 1
return user_string[start:end]
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/is_isogram.py | strings/is_isogram.py | """
wiki: https://en.wikipedia.org/wiki/Heterogram_(literature)#Isograms
"""
def is_isogram(string: str) -> bool:
"""
An isogram is a word in which no letter is repeated.
Examples of isograms are uncopyrightable and ambidextrously.
>>> is_isogram('Uncopyrightable')
True
>>> is_isogram('allowance')
False
>>> is_isogram('copy1')
Traceback (most recent call last):
...
ValueError: String must only contain alphabetic characters.
"""
if not all(x.isalpha() for x in string):
raise ValueError("String must only contain alphabetic characters.")
letters = sorted(string.lower())
return len(letters) == len(set(letters))
if __name__ == "__main__":
input_str = input("Enter a string ").strip()
isogram = is_isogram(input_str)
print(f"{input_str} is {'an' if isogram else 'not an'} isogram.")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/palindrome.py | strings/palindrome.py | # Algorithms to determine if a string is palindrome
from timeit import timeit
test_data = {
"MALAYALAM": True,
"String": False,
"rotor": True,
"level": True,
"A": True,
"BB": True,
"ABC": False,
"amanaplanacanalpanama": True, # "a man a plan a canal panama"
"abcdba": False,
"AB": False,
}
# Ensure our test data is valid
assert all((key == key[::-1]) is value for key, value in test_data.items())
def is_palindrome(s: str) -> bool:
"""
Return True if s is a palindrome otherwise return False.
>>> all(is_palindrome(key) is value for key, value in test_data.items())
True
"""
start_i = 0
end_i = len(s) - 1
while start_i < end_i:
if s[start_i] == s[end_i]:
start_i += 1
end_i -= 1
else:
return False
return True
def is_palindrome_traversal(s: str) -> bool:
"""
Return True if s is a palindrome otherwise return False.
>>> all(is_palindrome_traversal(key) is value for key, value in test_data.items())
True
"""
end = len(s) // 2
n = len(s)
# We need to traverse till half of the length of string
# as we can get access of the i'th last element from
# i'th index.
# eg: [0,1,2,3,4,5] => 4th index can be accessed
# with the help of 1st index (i==n-i-1)
# where n is length of string
return all(s[i] == s[n - i - 1] for i in range(end))
def is_palindrome_recursive(s: str) -> bool:
"""
Return True if s is a palindrome otherwise return False.
>>> all(is_palindrome_recursive(key) is value for key, value in test_data.items())
True
"""
if len(s) <= 1:
return True
if s[0] == s[len(s) - 1]:
return is_palindrome_recursive(s[1:-1])
else:
return False
def is_palindrome_slice(s: str) -> bool:
"""
Return True if s is a palindrome otherwise return False.
>>> all(is_palindrome_slice(key) is value for key, value in test_data.items())
True
"""
return s == s[::-1]
def benchmark_function(name: str) -> None:
stmt = f"all({name}(key) is value for key, value in test_data.items())"
setup = f"from __main__ import test_data, {name}"
number = 500000
result = timeit(stmt=stmt, setup=setup, number=number)
print(f"{name:<35} finished {number:,} runs in {result:.5f} seconds")
if __name__ == "__main__":
for key, value in test_data.items():
assert is_palindrome(key) is is_palindrome_recursive(key)
assert is_palindrome(key) is is_palindrome_slice(key)
print(f"{key:21} {value}")
print("a man a plan a canal panama")
# finished 500,000 runs in 0.46793 seconds
benchmark_function("is_palindrome_slice")
# finished 500,000 runs in 0.85234 seconds
benchmark_function("is_palindrome")
# finished 500,000 runs in 1.32028 seconds
benchmark_function("is_palindrome_recursive")
# finished 500,000 runs in 2.08679 seconds
benchmark_function("is_palindrome_traversal")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/remove_duplicate.py | strings/remove_duplicate.py | def remove_duplicates(sentence: str) -> str:
"""
Remove duplicates from sentence
>>> remove_duplicates("Python is great and Java is also great")
'Java Python also and great is'
>>> remove_duplicates("Python is great and Java is also great")
'Java Python also and great is'
"""
return " ".join(sorted(set(sentence.split())))
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/strings/alternative_string_arrange.py | strings/alternative_string_arrange.py | def alternative_string_arrange(first_str: str, second_str: str) -> str:
"""
Return the alternative arrangements of the two strings.
:param first_str:
:param second_str:
:return: String
>>> alternative_string_arrange("ABCD", "XY")
'AXBYCD'
>>> alternative_string_arrange("XY", "ABCD")
'XAYBCD'
>>> alternative_string_arrange("AB", "XYZ")
'AXBYZ'
>>> alternative_string_arrange("ABC", "")
'ABC'
"""
first_str_length: int = len(first_str)
second_str_length: int = len(second_str)
abs_length: int = (
first_str_length if first_str_length > second_str_length else second_str_length
)
output_list: list = []
for char_count in range(abs_length):
if char_count < first_str_length:
output_list.append(first_str[char_count])
if char_count < second_str_length:
output_list.append(second_str[char_count])
return "".join(output_list)
if __name__ == "__main__":
print(alternative_string_arrange("AB", "XYZ"), end=" ")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/check_anagrams.py | strings/check_anagrams.py | """
wiki: https://en.wikipedia.org/wiki/Anagram
"""
from collections import defaultdict
def check_anagrams(first_str: str, second_str: str) -> bool:
"""
Two strings are anagrams if they are made up of the same letters but are
arranged differently (ignoring the case).
>>> check_anagrams('Silent', 'Listen')
True
>>> check_anagrams('This is a string', 'Is this a string')
True
>>> check_anagrams('This is a string', 'Is this a string')
True
>>> check_anagrams('There', 'Their')
False
"""
first_str = first_str.lower().strip()
second_str = second_str.lower().strip()
# Remove whitespace
first_str = first_str.replace(" ", "")
second_str = second_str.replace(" ", "")
# Strings of different lengths are not anagrams
if len(first_str) != len(second_str):
return False
# Default values for count should be 0
count: defaultdict[str, int] = defaultdict(int)
# For each character in input strings,
# increment count in the corresponding
for i in range(len(first_str)):
count[first_str[i]] += 1
count[second_str[i]] -= 1
return all(_count == 0 for _count in count.values())
if __name__ == "__main__":
from doctest import testmod
testmod()
input_a = input("Enter the first string ").strip()
input_b = input("Enter the second string ").strip()
status = check_anagrams(input_a, input_b)
print(f"{input_a} and {input_b} are {'' if status else 'not '}anagrams.")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/boyer_moore_search.py | strings/boyer_moore_search.py | """
The algorithm finds the pattern in given text using following rule.
The bad-character rule considers the mismatched character in Text.
The next occurrence of that character to the left in Pattern is found,
If the mismatched character occurs to the left in Pattern,
a shift is proposed that aligns text block and pattern.
If the mismatched character does not occur to the left in Pattern,
a shift is proposed that moves the entirety of Pattern past
the point of mismatch in the text.
If there is no mismatch then the pattern matches with text block.
Time Complexity : O(n/m)
n=length of main string
m=length of pattern string
"""
class BoyerMooreSearch:
"""
Example usage:
bms = BoyerMooreSearch(text="ABAABA", pattern="AB")
positions = bms.bad_character_heuristic()
where 'positions' contain the locations where the pattern was matched.
"""
def __init__(self, text: str, pattern: str):
self.text, self.pattern = text, pattern
self.textLen, self.patLen = len(text), len(pattern)
def match_in_pattern(self, char: str) -> int:
"""
Finds the index of char in pattern in reverse order.
Parameters :
char (chr): character to be searched
Returns :
i (int): index of char from last in pattern
-1 (int): if char is not found in pattern
>>> bms = BoyerMooreSearch(text="ABAABA", pattern="AB")
>>> bms.match_in_pattern("B")
1
"""
for i in range(self.patLen - 1, -1, -1):
if char == self.pattern[i]:
return i
return -1
def mismatch_in_text(self, current_pos: int) -> int:
"""
Find the index of mis-matched character in text when compared with pattern
from last.
Parameters :
current_pos (int): current index position of text
Returns :
i (int): index of mismatched char from last in text
-1 (int): if there is no mismatch between pattern and text block
>>> bms = BoyerMooreSearch(text="ABAABA", pattern="AB")
>>> bms.mismatch_in_text(2)
3
"""
for i in range(self.patLen - 1, -1, -1):
if self.pattern[i] != self.text[current_pos + i]:
return current_pos + i
return -1
def bad_character_heuristic(self) -> list[int]:
"""
Finds the positions of the pattern location.
>>> bms = BoyerMooreSearch(text="ABAABA", pattern="AB")
>>> bms.bad_character_heuristic()
[0, 3]
"""
positions = []
for i in range(self.textLen - self.patLen + 1):
mismatch_index = self.mismatch_in_text(i)
if mismatch_index == -1:
positions.append(i)
else:
match_index = self.match_in_pattern(self.text[mismatch_index])
i = (
mismatch_index - match_index
) # shifting index lgtm [py/multiple-definition]
return positions
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/strings/barcode_validator.py | strings/barcode_validator.py | """
https://en.wikipedia.org/wiki/Check_digit#Algorithms
"""
def get_check_digit(barcode: int) -> int:
"""
Returns the last digit of barcode by excluding the last digit first
and then computing to reach the actual last digit from the remaining
12 digits.
>>> get_check_digit(8718452538119)
9
>>> get_check_digit(87184523)
5
>>> get_check_digit(87193425381086)
9
>>> [get_check_digit(x) for x in range(0, 100, 10)]
[0, 7, 4, 1, 8, 5, 2, 9, 6, 3]
"""
barcode //= 10 # exclude the last digit
checker = False
s = 0
# extract and check each digit
while barcode != 0:
mult = 1 if checker else 3
s += mult * (barcode % 10)
barcode //= 10
checker = not checker
return (10 - (s % 10)) % 10
def is_valid(barcode: int) -> bool:
"""
Checks for length of barcode and last-digit
Returns boolean value of validity of barcode
>>> is_valid(8718452538119)
True
>>> is_valid(87184525)
False
>>> is_valid(87193425381089)
False
>>> is_valid(0)
False
>>> is_valid(dwefgiweuf)
Traceback (most recent call last):
...
NameError: name 'dwefgiweuf' is not defined
"""
return len(str(barcode)) == 13 and get_check_digit(barcode) == barcode % 10
def get_barcode(barcode: str) -> int:
"""
Returns the barcode as an integer
>>> get_barcode("8718452538119")
8718452538119
>>> get_barcode("dwefgiweuf")
Traceback (most recent call last):
...
ValueError: Barcode 'dwefgiweuf' has alphabetic characters.
"""
if str(barcode).isalpha():
msg = f"Barcode '{barcode}' has alphabetic characters."
raise ValueError(msg)
elif int(barcode) < 0:
raise ValueError("The entered barcode has a negative value. Try again.")
else:
return int(barcode)
if __name__ == "__main__":
import doctest
doctest.testmod()
"""
Enter a barcode.
"""
barcode = get_barcode(input("Barcode: ").strip())
if is_valid(barcode):
print(f"'{barcode}' is a valid barcode.")
else:
print(f"'{barcode}' is NOT a valid barcode.")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/min_cost_string_conversion.py | strings/min_cost_string_conversion.py | """
Algorithm for calculating the most cost-efficient sequence for converting one string
into another.
The only allowed operations are
--- Cost to copy a character is copy_cost
--- Cost to replace a character is replace_cost
--- Cost to delete a character is delete_cost
--- Cost to insert a character is insert_cost
"""
def compute_transform_tables(
source_string: str,
destination_string: str,
copy_cost: int,
replace_cost: int,
delete_cost: int,
insert_cost: int,
) -> tuple[list[list[int]], list[list[str]]]:
"""
Finds the most cost efficient sequence
for converting one string into another.
>>> costs, operations = compute_transform_tables("cat", "cut", 1, 2, 3, 3)
>>> costs[0][:4]
[0, 3, 6, 9]
>>> costs[2][:4]
[6, 4, 3, 6]
>>> operations[0][:4]
['0', 'Ic', 'Iu', 'It']
>>> operations[3][:4]
['Dt', 'Dt', 'Rtu', 'Ct']
>>> compute_transform_tables("", "", 1, 2, 3, 3)
([[0]], [['0']])
"""
source_seq = list(source_string)
destination_seq = list(destination_string)
len_source_seq = len(source_seq)
len_destination_seq = len(destination_seq)
costs = [
[0 for _ in range(len_destination_seq + 1)] for _ in range(len_source_seq + 1)
]
ops = [
["0" for _ in range(len_destination_seq + 1)] for _ in range(len_source_seq + 1)
]
for i in range(1, len_source_seq + 1):
costs[i][0] = i * delete_cost
ops[i][0] = f"D{source_seq[i - 1]}"
for i in range(1, len_destination_seq + 1):
costs[0][i] = i * insert_cost
ops[0][i] = f"I{destination_seq[i - 1]}"
for i in range(1, len_source_seq + 1):
for j in range(1, len_destination_seq + 1):
if source_seq[i - 1] == destination_seq[j - 1]:
costs[i][j] = costs[i - 1][j - 1] + copy_cost
ops[i][j] = f"C{source_seq[i - 1]}"
else:
costs[i][j] = costs[i - 1][j - 1] + replace_cost
ops[i][j] = f"R{source_seq[i - 1]}" + str(destination_seq[j - 1])
if costs[i - 1][j] + delete_cost < costs[i][j]:
costs[i][j] = costs[i - 1][j] + delete_cost
ops[i][j] = f"D{source_seq[i - 1]}"
if costs[i][j - 1] + insert_cost < costs[i][j]:
costs[i][j] = costs[i][j - 1] + insert_cost
ops[i][j] = f"I{destination_seq[j - 1]}"
return costs, ops
def assemble_transformation(ops: list[list[str]], i: int, j: int) -> list[str]:
"""
Assembles the transformations based on the ops table.
>>> ops = [['0', 'Ic', 'Iu', 'It'],
... ['Dc', 'Cc', 'Iu', 'It'],
... ['Da', 'Da', 'Rau', 'Rat'],
... ['Dt', 'Dt', 'Rtu', 'Ct']]
>>> x = len(ops) - 1
>>> y = len(ops[0]) - 1
>>> assemble_transformation(ops, x, y)
['Cc', 'Rau', 'Ct']
>>> ops1 = [['0']]
>>> x1 = len(ops1) - 1
>>> y1 = len(ops1[0]) - 1
>>> assemble_transformation(ops1, x1, y1)
[]
>>> ops2 = [['0', 'I1', 'I2', 'I3'],
... ['D1', 'C1', 'I2', 'I3'],
... ['D2', 'D2', 'R23', 'R23']]
>>> x2 = len(ops2) - 1
>>> y2 = len(ops2[0]) - 1
>>> assemble_transformation(ops2, x2, y2)
['C1', 'I2', 'R23']
"""
if i == 0 and j == 0:
return []
elif ops[i][j][0] in {"C", "R"}:
seq = assemble_transformation(ops, i - 1, j - 1)
seq.append(ops[i][j])
return seq
elif ops[i][j][0] == "D":
seq = assemble_transformation(ops, i - 1, j)
seq.append(ops[i][j])
return seq
else:
seq = assemble_transformation(ops, i, j - 1)
seq.append(ops[i][j])
return seq
if __name__ == "__main__":
_, operations = compute_transform_tables("Python", "Algorithms", -1, 1, 2, 2)
m = len(operations)
n = len(operations[0])
sequence = assemble_transformation(operations, m - 1, n - 1)
string = list("Python")
i = 0
cost = 0
with open("min_cost.txt", "w") as file:
for op in sequence:
print("".join(string))
if op[0] == "C":
file.write("%-16s" % "Copy %c" % op[1]) # noqa: UP031
file.write("\t\t\t" + "".join(string))
file.write("\r\n")
cost -= 1
elif op[0] == "R":
string[i] = op[2]
file.write("%-16s" % ("Replace %c" % op[1] + " with " + str(op[2]))) # noqa: UP031
file.write("\t\t" + "".join(string))
file.write("\r\n")
cost += 1
elif op[0] == "D":
string.pop(i)
file.write("%-16s" % "Delete %c" % op[1]) # noqa: UP031
file.write("\t\t\t" + "".join(string))
file.write("\r\n")
cost += 2
else:
string.insert(i, op[1])
file.write("%-16s" % "Insert %c" % op[1]) # noqa: UP031
file.write("\t\t\t" + "".join(string))
file.write("\r\n")
cost += 2
i += 1
print("".join(string))
print("Cost: ", cost)
file.write("\r\nMinimum cost: " + str(cost))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/join.py | strings/join.py | """
Program to join a list of strings with a separator
"""
def join(separator: str, separated: list[str]) -> str:
"""
Joins a list of strings using a separator
and returns the result.
:param separator: Separator to be used
for joining the strings.
:param separated: List of strings to be joined.
:return: Joined string with the specified separator.
Examples:
>>> join("", ["a", "b", "c", "d"])
'abcd'
>>> join("#", ["a", "b", "c", "d"])
'a#b#c#d'
>>> join("#", "a")
'a'
>>> join(" ", ["You", "are", "amazing!"])
'You are amazing!'
>>> join(",", ["", "", ""])
',,'
This example should raise an
exception for non-string elements:
>>> join("#", ["a", "b", "c", 1])
Traceback (most recent call last):
...
Exception: join() accepts only strings
Additional test case with a different separator:
>>> join("-", ["apple", "banana", "cherry"])
'apple-banana-cherry'
"""
# Check that all elements are strings
for word_or_phrase in separated:
# If the element is not a string, raise an exception
if not isinstance(word_or_phrase, str):
raise Exception("join() accepts only strings")
joined: str = ""
"""
The last element of the list is not followed by the separator.
So, we need to iterate through the list and join each element
with the separator except the last element.
"""
last_index: int = len(separated) - 1
"""
Iterate through the list and join each element with the separator.
Except the last element, all other elements are followed by the separator.
"""
for word_or_phrase in separated[:last_index]:
# join the element with the separator.
joined += word_or_phrase + separator
# If the list is not empty, join the last element.
if separated != []:
joined += separated[last_index]
# Return the joined string.
return joined
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/strings/manacher.py | strings/manacher.py | def palindromic_string(input_string: str) -> str:
"""
>>> palindromic_string('abbbaba')
'abbba'
>>> palindromic_string('ababa')
'ababa'
Manacher's algorithm which finds Longest palindromic Substring in linear time.
1. first this convert input_string("xyx") into new_string("x|y|x") where odd
positions are actual input characters.
2. for each character in new_string it find corresponding length and
store the length and left,right to store previously calculated info.
(please look the explanation for details)
3. return corresponding output_string by removing all "|"
"""
max_length = 0
# if input_string is "aba" than new_input_string become "a|b|a"
new_input_string = ""
output_string = ""
# append each character + "|" in new_string for range(0, length-1)
for i in input_string[: len(input_string) - 1]:
new_input_string += i + "|"
# append last character
new_input_string += input_string[-1]
# we will store the starting and ending of previous furthest ending palindromic
# substring
left, right = 0, 0
# length[i] shows the length of palindromic substring with center i
length = [1 for i in range(len(new_input_string))]
# for each character in new_string find corresponding palindromic string
start = 0
for j in range(len(new_input_string)):
k = 1 if j > right else min(length[left + right - j] // 2, right - j + 1)
while (
j - k >= 0
and j + k < len(new_input_string)
and new_input_string[k + j] == new_input_string[j - k]
):
k += 1
length[j] = 2 * k - 1
# does this string is ending after the previously explored end (that is right) ?
# if yes the update the new right to the last index of this
if j + k - 1 > right:
left = j - k + 1
right = j + k - 1
# update max_length and start position
if max_length < length[j]:
max_length = length[j]
start = j
# create that string
s = new_input_string[start - max_length // 2 : start + max_length // 2 + 1]
for i in s:
if i != "|":
output_string += i
return output_string
if __name__ == "__main__":
import doctest
doctest.testmod()
"""
...a0...a1...a2.....a3......a4...a5...a6....
consider the string for which we are calculating the longest palindromic substring is
shown above where ... are some characters in between and right now we are calculating
the length of palindromic substring with center at a5 with following conditions :
i) we have stored the length of palindromic substring which has center at a3
(starts at left ends at right) and it is the furthest ending till now,
and it has ending after a6
ii) a2 and a4 are equally distant from a3 so char(a2) == char(a4)
iii) a0 and a6 are equally distant from a3 so char(a0) == char(a6)
iv) a1 is corresponding equal character of a5 in palindrome with center a3 (remember
that in below derivation of a4==a6)
now for a5 we will calculate the length of palindromic substring with center as a5 but
can we use previously calculated information in some way?
Yes, look the above string we know that a5 is inside the palindrome with center a3 and
previously we have calculated that
a0==a2 (palindrome of center a1)
a2==a4 (palindrome of center a3)
a0==a6 (palindrome of center a3)
so a4==a6
so we can say that palindrome at center a5 is at least as long as palindrome at center
a1 but this only holds if a0 and a6 are inside the limits of palindrome centered at a3
so finally ..
len_of_palindrome__at(a5) = min(len_of_palindrome_at(a1), right-a5)
where a3 lies from left to right and we have to keep updating that
and if the a5 lies outside of left,right boundary we calculate length of palindrome with
bruteforce and update left,right.
it gives the linear time complexity just like z-function
"""
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/is_polish_national_id.py | strings/is_polish_national_id.py | def is_polish_national_id(input_str: str) -> bool:
"""
Verification of the correctness of the PESEL number.
www-gov-pl.translate.goog/web/gov/czym-jest-numer-pesel?_x_tr_sl=auto&_x_tr_tl=en
PESEL can start with 0, that's why we take str as input,
but convert it to int for some calculations.
>>> is_polish_national_id(123)
Traceback (most recent call last):
...
ValueError: Expected str as input, found <class 'int'>
>>> is_polish_national_id("abc")
Traceback (most recent call last):
...
ValueError: Expected number as input
>>> is_polish_national_id("02070803628") # correct PESEL
True
>>> is_polish_national_id("02150803629") # wrong month
False
>>> is_polish_national_id("02075503622") # wrong day
False
>>> is_polish_national_id("-99012212349") # wrong range
False
>>> is_polish_national_id("990122123499999") # wrong range
False
>>> is_polish_national_id("02070803621") # wrong checksum
False
"""
# check for invalid input type
if not isinstance(input_str, str):
msg = f"Expected str as input, found {type(input_str)}"
raise ValueError(msg)
# check if input can be converted to int
try:
input_int = int(input_str)
except ValueError:
msg = "Expected number as input"
raise ValueError(msg)
# check number range
if not 10100000 <= input_int <= 99923199999:
return False
# check month correctness
month = int(input_str[2:4])
if (
month not in range(1, 13) # year 1900-1999
and month not in range(21, 33) # 2000-2099
and month not in range(41, 53) # 2100-2199
and month not in range(61, 73) # 2200-2299
and month not in range(81, 93) # 1800-1899
):
return False
# check day correctness
day = int(input_str[4:6])
if day not in range(1, 32):
return False
# check the checksum
multipliers = [1, 3, 7, 9, 1, 3, 7, 9, 1, 3]
subtotal = 0
digits_to_check = str(input_str)[:-1] # cut off the checksum
for index, digit in enumerate(digits_to_check):
# Multiply corresponding digits and multipliers.
# In case of a double-digit result, add only the last digit.
subtotal += (int(digit) * multipliers[index]) % 10
checksum = 10 - subtotal % 10
return checksum == input_int % 10
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/strings/pig_latin.py | strings/pig_latin.py | def pig_latin(word: str) -> str:
"""Compute the piglatin of a given string.
https://en.wikipedia.org/wiki/Pig_Latin
Usage examples:
>>> pig_latin("pig")
'igpay'
>>> pig_latin("latin")
'atinlay'
>>> pig_latin("banana")
'ananabay'
>>> pig_latin("friends")
'iendsfray'
>>> pig_latin("smile")
'ilesmay'
>>> pig_latin("string")
'ingstray'
>>> pig_latin("eat")
'eatway'
>>> pig_latin("omelet")
'omeletway'
>>> pig_latin("are")
'areway'
>>> pig_latin(" ")
''
>>> pig_latin(None)
''
"""
if not (word or "").strip():
return ""
word = word.lower()
if word[0] in "aeiou":
return f"{word}way"
for i, char in enumerate(word): # noqa: B007
if char in "aeiou":
break
return f"{word[i:]}{word[:i]}ay"
if __name__ == "__main__":
print(f"{pig_latin('friends') = }")
word = input("Enter a word: ")
print(f"{pig_latin(word) = }")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/edit_distance.py | strings/edit_distance.py | def edit_distance(source: str, target: str) -> int:
"""
Edit distance algorithm is a string metric, i.e., it is a way of quantifying how
dissimilar two strings are to one another. It is measured by counting the minimum
number of operations required to transform one string into another.
This implementation assumes that the cost of operations (insertion, deletion and
substitution) is always 1
Args:
source: the initial string with respect to which we are calculating the edit
distance for the target
target: the target string, formed after performing n operations on the source string
>>> edit_distance("GATTIC", "GALTIC")
1
>>> edit_distance("NUM3", "HUM2")
2
>>> edit_distance("cap", "CAP")
3
>>> edit_distance("Cat", "")
3
>>> edit_distance("cat", "cat")
0
>>> edit_distance("", "123456789")
9
>>> edit_distance("Be@uty", "Beautyyyy!")
5
>>> edit_distance("lstring", "lsstring")
1
"""
if len(source) == 0:
return len(target)
elif len(target) == 0:
return len(source)
delta = int(source[-1] != target[-1]) # Substitution
return min(
edit_distance(source[:-1], target[:-1]) + delta,
edit_distance(source, target[:-1]) + 1,
edit_distance(source[:-1], target) + 1,
)
if __name__ == "__main__":
print(edit_distance("ATCGCTG", "TAGCTAA")) # Answer is 4
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/reverse_words.py | strings/reverse_words.py | def reverse_words(input_str: str) -> str:
"""
Reverses words in a given string
>>> reverse_words("I love Python")
'Python love I'
>>> reverse_words("I Love Python")
'Python Love I'
"""
return " ".join(input_str.split()[::-1])
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/strings/is_valid_email_address.py | strings/is_valid_email_address.py | """
Implements an is valid email address algorithm
@ https://en.wikipedia.org/wiki/Email_address
"""
import string
email_tests: tuple[tuple[str, bool], ...] = (
("simple@example.com", True),
("very.common@example.com", True),
("disposable.style.email.with+symbol@example.com", True),
("other-email-with-hyphen@and.subdomains.example.com", True),
("fully-qualified-domain@example.com", True),
("user.name+tag+sorting@example.com", True),
("x@example.com", True),
("example-indeed@strange-example.com", True),
("test/test@test.com", True),
(
"123456789012345678901234567890123456789012345678901234567890123@example.com",
True,
),
("admin@mailserver1", True),
("example@s.example", True),
("Abc.example.com", False),
("A@b@c@example.com", False),
("abc@example..com", False),
("a(c)d,e:f;g<h>i[j\\k]l@example.com", False),
(
"12345678901234567890123456789012345678901234567890123456789012345@example.com",
False,
),
("i.like.underscores@but_its_not_allowed_in_this_part", False),
("", False),
)
# The maximum octets (one character as a standard unicode character is one byte)
# that the local part and the domain part can have
MAX_LOCAL_PART_OCTETS = 64
MAX_DOMAIN_OCTETS = 255
def is_valid_email_address(email: str) -> bool:
"""
Returns True if the passed email address is valid.
The local part of the email precedes the singular @ symbol and
is associated with a display-name. For example, "john.smith"
The domain is stricter than the local part and follows the @ symbol.
Global email checks:
1. There can only be one @ symbol in the email address. Technically if the
@ symbol is quoted in the local-part, then it is valid, however this
implementation ignores "" for now.
(See https://en.wikipedia.org/wiki/Email_address#:~:text=If%20quoted,)
2. The local-part and the domain are limited to a certain number of octets. With
unicode storing a single character in one byte, each octet is equivalent to
a character. Hence, we can just check the length of the string.
Checks for the local-part:
3. The local-part may contain: upper and lowercase latin letters, digits 0 to 9,
and printable characters (!#$%&'*+-/=?^_`{|}~)
4. The local-part may also contain a "." in any place that is not the first or
last character, and may not have more than one "." consecutively.
Checks for the domain:
5. The domain may contain: upper and lowercase latin letters and digits 0 to 9
6. Hyphen "-", provided that it is not the first or last character
7. The domain may also contain a "." in any place that is not the first or
last character, and may not have more than one "." consecutively.
>>> for email, valid in email_tests:
... assert is_valid_email_address(email) == valid
"""
# (1.) Make sure that there is only one @ symbol in the email address
if email.count("@") != 1:
return False
local_part, domain = email.split("@")
# (2.) Check octet length of the local part and domain
if len(local_part) > MAX_LOCAL_PART_OCTETS or len(domain) > MAX_DOMAIN_OCTETS:
return False
# (3.) Validate the characters in the local-part
if any(
char not in string.ascii_letters + string.digits + ".(!#$%&'*+-/=?^_`{|}~)"
for char in local_part
):
return False
# (4.) Validate the placement of "." characters in the local-part
if local_part.startswith(".") or local_part.endswith(".") or ".." in local_part:
return False
# (5.) Validate the characters in the domain
if any(char not in string.ascii_letters + string.digits + ".-" for char in domain):
return False
# (6.) Validate the placement of "-" characters
if domain.startswith("-") or domain.endswith("."):
return False
# (7.) Validate the placement of "." characters
return not (domain.startswith(".") or domain.endswith(".") or ".." in domain)
if __name__ == "__main__":
import doctest
doctest.testmod()
for email, valid in email_tests:
is_valid = is_valid_email_address(email)
assert is_valid == valid, f"{email} is {is_valid}"
print(f"Email address {email} is {'not ' if not is_valid else ''}valid")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/word_occurrence.py | strings/word_occurrence.py | # Created by sarathkaul on 17/11/19
# Modified by Arkadip Bhattacharya(@darkmatter18) on 20/04/2020
from collections import defaultdict
def word_occurrence(sentence: str) -> dict:
"""
>>> from collections import Counter
>>> SENTENCE = "a b A b c b d b d e f e g e h e i e j e 0"
>>> occurence_dict = word_occurrence(SENTENCE)
>>> all(occurence_dict[word] == count for word, count
... in Counter(SENTENCE.split()).items())
True
>>> dict(word_occurrence("Two spaces"))
{'Two': 1, 'spaces': 1}
"""
occurrence: defaultdict[str, int] = defaultdict(int)
# Creating a dictionary containing count of each word
for word in sentence.split():
occurrence[word] += 1
return occurrence
if __name__ == "__main__":
for word, count in word_occurrence("INPUT STRING").items():
print(f"{word}: {count}")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/reverse_letters.py | strings/reverse_letters.py | def reverse_letters(sentence: str, length: int = 0) -> str:
"""
Reverse all words that are longer than the given length of characters in a sentence.
If unspecified, length is taken as 0
>>> reverse_letters("Hey wollef sroirraw", 3)
'Hey fellow warriors'
>>> reverse_letters("nohtyP is nohtyP", 2)
'Python is Python'
>>> reverse_letters("1 12 123 1234 54321 654321", 0)
'1 21 321 4321 12345 123456'
>>> reverse_letters("racecar")
'racecar'
"""
return " ".join(
"".join(word[::-1]) if len(word) > length else word for word in sentence.split()
)
if __name__ == "__main__":
import doctest
doctest.testmod()
print(reverse_letters("Hey wollef sroirraw"))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/hamming_distance.py | strings/hamming_distance.py | def hamming_distance(string1: str, string2: str) -> int:
"""Calculate the Hamming distance between two equal length strings
In information theory, the Hamming distance between two strings of equal
length is the number of positions at which the corresponding symbols are
different. https://en.wikipedia.org/wiki/Hamming_distance
Args:
string1 (str): Sequence 1
string2 (str): Sequence 2
Returns:
int: Hamming distance
>>> hamming_distance("python", "python")
0
>>> hamming_distance("karolin", "kathrin")
3
>>> hamming_distance("00000", "11111")
5
>>> hamming_distance("karolin", "kath")
Traceback (most recent call last):
...
ValueError: String lengths must match!
"""
if len(string1) != len(string2):
raise ValueError("String lengths must match!")
count = 0
for char1, char2 in zip(string1, string2):
if char1 != char2:
count += 1
return count
if __name__ == "__main__":
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/word_patterns.py | strings/word_patterns.py | def get_word_pattern(word: str) -> str:
"""
Returns numerical pattern of character appearances in given word
>>> get_word_pattern("")
''
>>> get_word_pattern(" ")
'0'
>>> get_word_pattern("pattern")
'0.1.2.2.3.4.5'
>>> get_word_pattern("word pattern")
'0.1.2.3.4.5.6.7.7.8.2.9'
>>> get_word_pattern("get word pattern")
'0.1.2.3.4.5.6.7.3.8.9.2.2.1.6.10'
>>> get_word_pattern()
Traceback (most recent call last):
...
TypeError: get_word_pattern() missing 1 required positional argument: 'word'
>>> get_word_pattern(1)
Traceback (most recent call last):
...
AttributeError: 'int' object has no attribute 'upper'
>>> get_word_pattern(1.1)
Traceback (most recent call last):
...
AttributeError: 'float' object has no attribute 'upper'
>>> get_word_pattern([])
Traceback (most recent call last):
...
AttributeError: 'list' object has no attribute 'upper'
"""
word = word.upper()
next_num = 0
letter_nums = {}
word_pattern = []
for letter in word:
if letter not in letter_nums:
letter_nums[letter] = str(next_num)
next_num += 1
word_pattern.append(letter_nums[letter])
return ".".join(word_pattern)
if __name__ == "__main__":
import pprint
import time
start_time = time.time()
with open("dictionary.txt") as in_file:
word_list = in_file.read().splitlines()
all_patterns: dict = {}
for word in word_list:
pattern = get_word_pattern(word)
if pattern in all_patterns:
all_patterns[pattern].append(word)
else:
all_patterns[pattern] = [word]
with open("word_patterns.txt", "w") as out_file:
out_file.write(pprint.pformat(all_patterns))
total_time = round(time.time() - start_time, 2)
print(f"Done! {len(all_patterns):,} word patterns found in {total_time} seconds.")
# Done! 9,581 word patterns found in 0.58 seconds.
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/wildcard_pattern_matching.py | strings/wildcard_pattern_matching.py | """
Implementation of regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
"""
def match_pattern(input_string: str, pattern: str) -> bool:
"""
uses bottom-up dynamic programming solution for matching the input
string with a given pattern.
Runtime: O(len(input_string)*len(pattern))
Arguments
--------
input_string: str, any string which should be compared with the pattern
pattern: str, the string that represents a pattern and may contain
'.' for single character matches and '*' for zero or more of preceding character
matches
Note
----
the pattern cannot start with a '*',
because there should be at least one character before *
Returns
-------
A Boolean denoting whether the given string follows the pattern
Examples
-------
>>> match_pattern("aab", "c*a*b")
True
>>> match_pattern("dabc", "*abc")
False
>>> match_pattern("aaa", "aa")
False
>>> match_pattern("aaa", "a.a")
True
>>> match_pattern("aaab", "aa*")
False
>>> match_pattern("aaab", ".*")
True
>>> match_pattern("a", "bbbb")
False
>>> match_pattern("", "bbbb")
False
>>> match_pattern("a", "")
False
>>> match_pattern("", "")
True
"""
len_string = len(input_string) + 1
len_pattern = len(pattern) + 1
# dp is a 2d matrix where dp[i][j] denotes whether prefix string of
# length i of input_string matches with prefix string of length j of
# given pattern.
# "dp" stands for dynamic programming.
dp = [[0 for i in range(len_pattern)] for j in range(len_string)]
# since string of zero length match pattern of zero length
dp[0][0] = 1
# since pattern of zero length will never match with string of non-zero length
for i in range(1, len_string):
dp[i][0] = 0
# since string of zero length will match with pattern where there
# is at least one * alternatively
for j in range(1, len_pattern):
dp[0][j] = dp[0][j - 2] if pattern[j - 1] == "*" else 0
# now using bottom-up approach to find for all remaining lengths
for i in range(1, len_string):
for j in range(1, len_pattern):
if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".":
dp[i][j] = dp[i - 1][j - 1]
elif pattern[j - 1] == "*":
if dp[i][j - 2] == 1:
dp[i][j] = 1
elif pattern[j - 2] in (input_string[i - 1], "."):
dp[i][j] = dp[i - 1][j]
else:
dp[i][j] = 0
else:
dp[i][j] = 0
return bool(dp[-1][-1])
if __name__ == "__main__":
import doctest
doctest.testmod()
# inputing the strings
# input_string = input("input a string :")
# pattern = input("input a pattern :")
input_string = "aab"
pattern = "c*a*b"
# using function to check whether given string matches the given pattern
if match_pattern(input_string, pattern):
print(f"{input_string} matches the given pattern {pattern}")
else:
print(f"{input_string} does not match with the given pattern {pattern}")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/autocomplete_using_trie.py | strings/autocomplete_using_trie.py | from __future__ import annotations
END = "#"
class Trie:
def __init__(self) -> None:
self._trie: dict = {}
def insert_word(self, text: str) -> None:
trie = self._trie
for char in text:
if char not in trie:
trie[char] = {}
trie = trie[char]
trie[END] = True
def find_word(self, prefix: str) -> tuple | list:
trie = self._trie
for char in prefix:
if char in trie:
trie = trie[char]
else:
return []
return self._elements(trie)
def _elements(self, d: dict) -> tuple:
result = []
for c, v in d.items():
sub_result = [" "] if c == END else [(c + s) for s in self._elements(v)]
result.extend(sub_result)
return tuple(result)
trie = Trie()
words = ("depart", "detergent", "daring", "dog", "deer", "deal")
for word in words:
trie.insert_word(word)
def autocomplete_using_trie(string: str) -> tuple:
"""
>>> trie = Trie()
>>> for word in words:
... trie.insert_word(word)
...
>>> matches = autocomplete_using_trie("de")
>>> "detergent " in matches
True
>>> "dog " in matches
False
"""
suffixes = trie.find_word(string)
return tuple(string + word for word in suffixes)
def main() -> None:
print(autocomplete_using_trie("de"))
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/strings/camel_case_to_snake_case.py | strings/camel_case_to_snake_case.py | def camel_to_snake_case(input_str: str) -> str:
"""
Transforms a camelCase (or PascalCase) string to snake_case
>>> camel_to_snake_case("someRandomString")
'some_random_string'
>>> camel_to_snake_case("SomeRandomStr#ng")
'some_random_str_ng'
>>> camel_to_snake_case("123someRandom123String123")
'123_some_random_123_string_123'
>>> camel_to_snake_case("123SomeRandom123String123")
'123_some_random_123_string_123'
>>> camel_to_snake_case(123)
Traceback (most recent call last):
...
ValueError: Expected string as input, found <class 'int'>
"""
# check for invalid input type
if not isinstance(input_str, str):
msg = f"Expected string as input, found {type(input_str)}"
raise ValueError(msg)
snake_str = ""
for index, char in enumerate(input_str):
if char.isupper():
snake_str += "_" + char.lower()
# if char is lowercase but proceeded by a digit:
elif input_str[index - 1].isdigit() and char.islower():
snake_str += "_" + char
# if char is a digit proceeded by a letter:
elif input_str[index - 1].isalpha() and char.isnumeric():
snake_str += "_" + char.lower()
# if char is not alphanumeric:
elif not char.isalnum():
snake_str += "_"
else:
snake_str += char
# remove leading underscore
if snake_str[0] == "_":
snake_str = snake_str[1:]
return snake_str
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/strings/knuth_morris_pratt.py | strings/knuth_morris_pratt.py | from __future__ import annotations
def knuth_morris_pratt(text: str, pattern: str) -> int:
"""
The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of text
with complexity O(n + m)
1) Preprocess pattern to identify any suffixes that are identical to prefixes
This tells us where to continue from if we get a mismatch between a character
in our pattern and the text.
2) Step through the text one character at a time and compare it to a character in
the pattern updating our location within the pattern if necessary
>>> kmp = "knuth_morris_pratt"
>>> all(
... knuth_morris_pratt(kmp, s) == kmp.find(s)
... for s in ("kn", "h_m", "rr", "tt", "not there")
... )
True
"""
# 1) Construct the failure array
failure = get_failure_array(pattern)
# 2) Step through text searching for pattern
i, j = 0, 0 # index into text, pattern
while i < len(text):
if pattern[j] == text[i]:
if j == (len(pattern) - 1):
return i - j
j += 1
# if this is a prefix in our pattern
# just go back far enough to continue
elif j > 0:
j = failure[j - 1]
continue
i += 1
return -1
def get_failure_array(pattern: str) -> list[int]:
"""
Calculates the new index we should go to if we fail a comparison
:param pattern:
:return:
"""
failure = [0]
i = 0
j = 1
while j < len(pattern):
if pattern[i] == pattern[j]:
i += 1
elif i > 0:
i = failure[i - 1]
continue
j += 1
failure.append(i)
return failure
if __name__ == "__main__":
import doctest
doctest.testmod()
# Test 1)
pattern = "abc1abc12"
text1 = "alskfjaldsabc1abc1abc12k23adsfabcabc"
text2 = "alskfjaldsk23adsfabcabc"
assert knuth_morris_pratt(text1, pattern)
assert knuth_morris_pratt(text2, pattern)
# Test 2)
pattern = "ABABX"
text = "ABABZABABYABABX"
assert knuth_morris_pratt(text, pattern)
# Test 3)
pattern = "AAAB"
text = "ABAAAAAB"
assert knuth_morris_pratt(text, pattern)
# Test 4)
pattern = "abcdabcy"
text = "abcxabcdabxabcdabcdabcy"
assert knuth_morris_pratt(text, pattern)
# Test 5) -> Doctests
kmp = "knuth_morris_pratt"
assert all(
knuth_morris_pratt(kmp, s) == kmp.find(s)
for s in ("kn", "h_m", "rr", "tt", "not there")
)
# Test 6)
pattern = "aabaabaaa"
assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/indian_phone_validator.py | strings/indian_phone_validator.py | import re
def indian_phone_validator(phone: str) -> bool:
"""
Determine whether the string is a valid phone number or not
:param phone:
:return: Boolean
>>> indian_phone_validator("+91123456789")
False
>>> indian_phone_validator("+919876543210")
True
>>> indian_phone_validator("01234567896")
False
>>> indian_phone_validator("919876543218")
True
>>> indian_phone_validator("+91-1234567899")
False
>>> indian_phone_validator("+91-9876543218")
True
"""
pat = re.compile(r"^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$")
if match := re.search(pat, phone):
return match.string == phone
return False
if __name__ == "__main__":
print(indian_phone_validator("+918827897895"))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/capitalize.py | strings/capitalize.py | def capitalize(sentence: str) -> str:
"""
Capitalizes the first letter of a sentence or word.
>>> capitalize("hello world")
'Hello world'
>>> capitalize("123 hello world")
'123 hello world'
>>> capitalize(" hello world")
' hello world'
>>> capitalize("a")
'A'
>>> capitalize("")
''
"""
if not sentence:
return ""
# Capitalize the first character if it's a lowercase letter
# Concatenate the capitalized character with the rest of the string
return sentence[0].upper() + sentence[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/strings/naive_string_search.py | strings/naive_string_search.py | """
https://en.wikipedia.org/wiki/String-searching_algorithm#Na%C3%AFve_string_search
this algorithm tries to find the pattern from every position of
the mainString if pattern is found from position i it add it to
the answer and does the same for position i+1
Complexity : O(n*m)
n=length of main string
m=length of pattern string
"""
def naive_pattern_search(s: str, pattern: str) -> list:
"""
>>> naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC")
[4, 10, 18]
>>> naive_pattern_search("ABC", "ABAAABCDBBABCDDEBCABC")
[]
>>> naive_pattern_search("", "ABC")
[]
>>> naive_pattern_search("TEST", "TEST")
[0]
>>> naive_pattern_search("ABCDEGFTEST", "TEST")
[7]
"""
pat_len = len(pattern)
position = []
for i in range(len(s) - pat_len + 1):
match_found = True
for j in range(pat_len):
if s[i + j] != pattern[j]:
match_found = False
break
if match_found:
position.append(i)
return position
if __name__ == "__main__":
assert naive_pattern_search("ABCDEFG", "DE") == [3]
print(naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC"))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/count_vowels.py | strings/count_vowels.py | def count_vowels(s: str) -> int:
"""
Count the number of vowels in a given string.
:param s: Input string to count vowels in.
:return: Number of vowels in the input string.
Examples:
>>> count_vowels("hello world")
3
>>> count_vowels("HELLO WORLD")
3
>>> count_vowels("123 hello world")
3
>>> count_vowels("")
0
>>> count_vowels("a quick brown fox")
5
>>> count_vowels("the quick BROWN fox")
5
>>> count_vowels("PYTHON")
1
"""
if not isinstance(s, str):
raise ValueError("Input must be a string")
vowels = "aeiouAEIOU"
return sum(1 for char in s if char in vowels)
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/strings/is_srilankan_phone_number.py | strings/is_srilankan_phone_number.py | import re
def is_sri_lankan_phone_number(phone: str) -> bool:
"""
Determine whether the string is a valid sri lankan mobile phone number or not
References: https://aye.sh/blog/sri-lankan-phone-number-regex
>>> is_sri_lankan_phone_number("+94773283048")
True
>>> is_sri_lankan_phone_number("+9477-3283048")
True
>>> is_sri_lankan_phone_number("0718382399")
True
>>> is_sri_lankan_phone_number("0094702343221")
True
>>> is_sri_lankan_phone_number("075 3201568")
True
>>> is_sri_lankan_phone_number("07779209245")
False
>>> is_sri_lankan_phone_number("0957651234")
False
"""
pattern = re.compile(r"^(?:0|94|\+94|0{2}94)7(0|1|2|4|5|6|7|8)(-| |)\d{7}$")
return bool(re.search(pattern, phone))
if __name__ == "__main__":
phone = "0094702343221"
print(is_sri_lankan_phone_number(phone))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/z_function.py | strings/z_function.py | """
https://cp-algorithms.com/string/z-function.html
Z-function or Z algorithm
Efficient algorithm for pattern occurrence in a string
Time Complexity: O(n) - where n is the length of the string
"""
def z_function(input_str: str) -> list[int]:
"""
For the given string this function computes value for each index,
which represents the maximal length substring starting from the index
and is the same as the prefix of the same size
e.x. for string 'abab' for second index value would be 2
For the value of the first element the algorithm always returns 0
>>> z_function("abracadabra")
[0, 0, 0, 1, 0, 1, 0, 4, 0, 0, 1]
>>> z_function("aaaa")
[0, 3, 2, 1]
>>> z_function("zxxzxxz")
[0, 0, 0, 4, 0, 0, 1]
"""
z_result = [0 for i in range(len(input_str))]
# initialize interval's left pointer and right pointer
left_pointer, right_pointer = 0, 0
for i in range(1, len(input_str)):
# case when current index is inside the interval
if i <= right_pointer:
min_edge = min(right_pointer - i + 1, z_result[i - left_pointer])
z_result[i] = min_edge
while go_next(i, z_result, input_str):
z_result[i] += 1
# if new index's result gives us more right interval,
# we've to update left_pointer and right_pointer
if i + z_result[i] - 1 > right_pointer:
left_pointer, right_pointer = i, i + z_result[i] - 1
return z_result
def go_next(i: int, z_result: list[int], s: str) -> bool:
"""
Check if we have to move forward to the next characters or not
"""
return i + z_result[i] < len(s) and s[z_result[i]] == s[i + z_result[i]]
def find_pattern(pattern: str, input_str: str) -> int:
"""
Example of using z-function for pattern occurrence
Given function returns the number of times 'pattern'
appears in 'input_str' as a substring
>>> find_pattern("abr", "abracadabra")
2
>>> find_pattern("a", "aaaa")
4
>>> find_pattern("xz", "zxxzxxz")
2
"""
answer = 0
# concatenate 'pattern' and 'input_str' and call z_function
# with concatenated string
z_result = z_function(pattern + input_str)
for val in z_result:
# if value is greater then length of the pattern string
# that means this index is starting position of substring
# which is equal to pattern string
if val >= len(pattern):
answer += 1
return answer
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/strings/credit_card_validator.py | strings/credit_card_validator.py | """
Functions for testing the validity of credit card numbers.
https://en.wikipedia.org/wiki/Luhn_algorithm
"""
def validate_initial_digits(credit_card_number: str) -> bool:
"""
Function to validate initial digits of a given credit card number.
>>> valid = "4111111111111111 41111111111111 34 35 37 412345 523456 634567"
>>> all(validate_initial_digits(cc) for cc in valid.split())
True
>>> invalid = "14 25 76 32323 36111111111111"
>>> all(validate_initial_digits(cc) is False for cc in invalid.split())
True
"""
return credit_card_number.startswith(("34", "35", "37", "4", "5", "6"))
def luhn_validation(credit_card_number: str) -> bool:
"""
Function to luhn algorithm validation for a given credit card number.
>>> luhn_validation('4111111111111111')
True
>>> luhn_validation('36111111111111')
True
>>> luhn_validation('41111111111111')
False
"""
cc_number = credit_card_number
total = 0
half_len = len(cc_number) - 2
for i in range(half_len, -1, -2):
# double the value of every second digit
digit = int(cc_number[i])
digit *= 2
# If doubling of a number results in a two digit number
# i.e greater than 9(e.g., 6 x 2 = 12),
# then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6),
# to get a single digit number.
if digit > 9:
digit %= 10
digit += 1
cc_number = cc_number[:i] + str(digit) + cc_number[i + 1 :]
total += digit
# Sum up the remaining digits
for i in range(len(cc_number) - 1, -1, -2):
total += int(cc_number[i])
return total % 10 == 0
def validate_credit_card_number(credit_card_number: str) -> bool:
"""
Function to validate the given credit card number.
>>> validate_credit_card_number('4111111111111111')
4111111111111111 is a valid credit card number.
True
>>> validate_credit_card_number('helloworld$')
helloworld$ is an invalid credit card number because it has nonnumerical characters.
False
>>> validate_credit_card_number('32323')
32323 is an invalid credit card number because of its length.
False
>>> validate_credit_card_number('32323323233232332323')
32323323233232332323 is an invalid credit card number because of its length.
False
>>> validate_credit_card_number('36111111111111')
36111111111111 is an invalid credit card number because of its first two digits.
False
>>> validate_credit_card_number('41111111111111')
41111111111111 is an invalid credit card number because it fails the Luhn check.
False
"""
error_message = f"{credit_card_number} is an invalid credit card number because"
if not credit_card_number.isdigit():
print(f"{error_message} it has nonnumerical characters.")
return False
if not 13 <= len(credit_card_number) <= 16:
print(f"{error_message} of its length.")
return False
if not validate_initial_digits(credit_card_number):
print(f"{error_message} of its first two digits.")
return False
if not luhn_validation(credit_card_number):
print(f"{error_message} it fails the Luhn check.")
return False
print(f"{credit_card_number} is a valid credit card number.")
return True
if __name__ == "__main__":
import doctest
doctest.testmod()
validate_credit_card_number("4111111111111111")
validate_credit_card_number("32323")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/jaro_winkler.py | strings/jaro_winkler.py | """https://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance"""
def jaro_winkler(str1: str, str2: str) -> float:
"""
Jaro-Winkler distance is a string metric measuring an edit distance between two
sequences.
Output value is between 0.0 and 1.0.
>>> jaro_winkler("martha", "marhta")
0.9611111111111111
>>> jaro_winkler("CRATE", "TRACE")
0.7333333333333334
>>> jaro_winkler("test", "dbdbdbdb")
0.0
>>> jaro_winkler("test", "test")
1.0
>>> jaro_winkler("hello world", "HeLLo W0rlD")
0.6363636363636364
>>> jaro_winkler("test", "")
0.0
>>> jaro_winkler("hello", "world")
0.4666666666666666
>>> jaro_winkler("hell**o", "*world")
0.4365079365079365
"""
def get_matched_characters(_str1: str, _str2: str) -> str:
matched = []
limit = min(len(_str1), len(_str2)) // 2
for i, char in enumerate(_str1):
left = int(max(0, i - limit))
right = int(min(i + limit + 1, len(_str2)))
if char in _str2[left:right]:
matched.append(char)
_str2 = (
f"{_str2[0 : _str2.index(char)]} {_str2[_str2.index(char) + 1 :]}"
)
return "".join(matched)
# matching characters
matching_1 = get_matched_characters(str1, str2)
matching_2 = get_matched_characters(str2, str1)
match_count = len(matching_1)
# transposition
transpositions = (
len([(c1, c2) for c1, c2 in zip(matching_1, matching_2) if c1 != c2]) // 2
)
if not match_count:
jaro = 0.0
else:
jaro = (
1
/ 3
* (
match_count / len(str1)
+ match_count / len(str2)
+ (match_count - transpositions) / match_count
)
)
# common prefix up to 4 characters
prefix_len = 0
for c1, c2 in zip(str1[:4], str2[:4]):
if c1 == c2:
prefix_len += 1
else:
break
return jaro + 0.1 * prefix_len * (1 - jaro)
if __name__ == "__main__":
import doctest
doctest.testmod()
print(jaro_winkler("hello", "world"))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/snake_case_to_camel_pascal_case.py | strings/snake_case_to_camel_pascal_case.py | def snake_to_camel_case(input_str: str, use_pascal: bool = False) -> str:
"""
Transforms a snake_case given string to camelCase (or PascalCase if indicated)
(defaults to not use Pascal)
>>> snake_to_camel_case("some_random_string")
'someRandomString'
>>> snake_to_camel_case("some_random_string", use_pascal=True)
'SomeRandomString'
>>> snake_to_camel_case("some_random_string_with_numbers_123")
'someRandomStringWithNumbers123'
>>> snake_to_camel_case("some_random_string_with_numbers_123", use_pascal=True)
'SomeRandomStringWithNumbers123'
>>> snake_to_camel_case(123)
Traceback (most recent call last):
...
ValueError: Expected string as input, found <class 'int'>
>>> snake_to_camel_case("some_string", use_pascal="True")
Traceback (most recent call last):
...
ValueError: Expected boolean as use_pascal parameter, found <class 'str'>
"""
if not isinstance(input_str, str):
msg = f"Expected string as input, found {type(input_str)}"
raise ValueError(msg)
if not isinstance(use_pascal, bool):
msg = f"Expected boolean as use_pascal parameter, found {type(use_pascal)}"
raise ValueError(msg)
words = input_str.split("_")
start_index = 0 if use_pascal else 1
words_to_capitalize = words[start_index:]
capitalized_words = [word[0].upper() + word[1:] for word in words_to_capitalize]
initial_word = "" if use_pascal else words[0]
return "".join([initial_word, *capitalized_words])
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/strings/anagrams.py | strings/anagrams.py | from __future__ import annotations
import collections
import pprint
from pathlib import Path
def signature(word: str) -> str:
"""
Return a word's frequency-based signature.
>>> signature("test")
'e1s1t2'
>>> signature("this is a test")
' 3a1e1h1i2s3t3'
>>> signature("finaltest")
'a1e1f1i1l1n1s1t2'
"""
frequencies = collections.Counter(word)
return "".join(
f"{char}{frequency}" for char, frequency in sorted(frequencies.items())
)
def anagram(my_word: str) -> list[str]:
"""
Return every anagram of the given word from the dictionary.
>>> anagram('test')
['sett', 'stet', 'test']
>>> anagram('this is a test')
[]
>>> anagram('final')
['final']
"""
return word_by_signature[signature(my_word)]
data: str = Path(__file__).parent.joinpath("words.txt").read_text(encoding="utf-8")
word_list = sorted({word.strip().lower() for word in data.splitlines()})
word_by_signature = collections.defaultdict(list)
for word in word_list:
word_by_signature[signature(word)].append(word)
if __name__ == "__main__":
all_anagrams = {word: anagram(word) for word in word_list if len(anagram(word)) > 1}
with open("anagrams.txt", "w") as file:
file.write("all_anagrams = \n")
file.write(pprint.pformat(all_anagrams))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/dna.py | strings/dna.py | import re
def dna(dna: str) -> str:
"""
https://en.wikipedia.org/wiki/DNA
Returns the second side of a DNA strand
>>> dna("GCTA")
'CGAT'
>>> dna("ATGC")
'TACG'
>>> dna("CTGA")
'GACT'
>>> dna("GFGG")
Traceback (most recent call last):
...
ValueError: Invalid Strand
"""
if len(re.findall("[ATCG]", dna)) != len(dna):
raise ValueError("Invalid Strand")
return dna.translate(dna.maketrans("ATCG", "TAGC"))
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/strings/damerau_levenshtein_distance.py | strings/damerau_levenshtein_distance.py | """
This script is a implementation of the Damerau-Levenshtein distance algorithm.
It's an algorithm that measures the edit distance between two string sequences
More information about this algorithm can be found in this wikipedia article:
https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance
"""
def damerau_levenshtein_distance(first_string: str, second_string: str) -> int:
"""
Implements the Damerau-Levenshtein distance algorithm that measures
the edit distance between two strings.
Parameters:
first_string: The first string to compare
second_string: The second string to compare
Returns:
distance: The edit distance between the first and second strings
>>> damerau_levenshtein_distance("cat", "cut")
1
>>> damerau_levenshtein_distance("kitten", "sitting")
3
>>> damerau_levenshtein_distance("hello", "world")
4
>>> damerau_levenshtein_distance("book", "back")
2
>>> damerau_levenshtein_distance("container", "containment")
3
>>> damerau_levenshtein_distance("container", "containment")
3
"""
# Create a dynamic programming matrix to store the distances
dp_matrix = [[0] * (len(second_string) + 1) for _ in range(len(first_string) + 1)]
# Initialize the matrix
for i in range(len(first_string) + 1):
dp_matrix[i][0] = i
for j in range(len(second_string) + 1):
dp_matrix[0][j] = j
# Fill the matrix
for i, first_char in enumerate(first_string, start=1):
for j, second_char in enumerate(second_string, start=1):
cost = int(first_char != second_char)
dp_matrix[i][j] = min(
dp_matrix[i - 1][j] + 1, # Deletion
dp_matrix[i][j - 1] + 1, # Insertion
dp_matrix[i - 1][j - 1] + cost, # Substitution
)
if (
i > 1
and j > 1
and first_string[i - 1] == second_string[j - 2]
and first_string[i - 2] == second_string[j - 1]
):
# Transposition
dp_matrix[i][j] = min(dp_matrix[i][j], dp_matrix[i - 2][j - 2] + cost)
return dp_matrix[-1][-1]
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/strings/lower.py | strings/lower.py | def lower(word: str) -> str:
"""
Will convert the entire string to lowercase letters
>>> lower("wow")
'wow'
>>> lower("HellZo")
'hellzo'
>>> lower("WHAT")
'what'
>>> lower("wh[]32")
'wh[]32'
>>> lower("whAT")
'what'
"""
# Converting to ASCII value, obtaining the integer representation
# and checking to see if the character is a capital letter.
# If it is a capital letter, it is shifted by 32, making it a lowercase letter.
return "".join(chr(ord(char) + 32) if "A" <= char <= "Z" else char for char in word)
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/strings/rabin_karp.py | strings/rabin_karp.py | # Numbers of alphabet which we call base
alphabet_size = 256
# Modulus to hash a string
modulus = 1000003
def rabin_karp(pattern: str, text: str) -> bool:
"""
The Rabin-Karp Algorithm for finding a pattern within a piece of text
with complexity O(nm), most efficient when it is used with multiple patterns
as it is able to check if any of a set of patterns match a section of text in o(1)
given the precomputed hashes.
This will be the simple version which only assumes one pattern is being searched
for but it's not hard to modify
1) Calculate pattern hash
2) Step through the text one character at a time passing a window with the same
length as the pattern
calculating the hash of the text within the window compare it with the hash
of the pattern. Only testing equality if the hashes match
"""
p_len = len(pattern)
t_len = len(text)
if p_len > t_len:
return False
p_hash = 0
text_hash = 0
modulus_power = 1
# Calculating the hash of pattern and substring of text
for i in range(p_len):
p_hash = (ord(pattern[i]) + p_hash * alphabet_size) % modulus
text_hash = (ord(text[i]) + text_hash * alphabet_size) % modulus
if i == p_len - 1:
continue
modulus_power = (modulus_power * alphabet_size) % modulus
for i in range(t_len - p_len + 1):
if text_hash == p_hash and text[i : i + p_len] == pattern:
return True
if i == t_len - p_len:
continue
# Calculate the https://en.wikipedia.org/wiki/Rolling_hash
text_hash = (
(text_hash - ord(text[i]) * modulus_power) * alphabet_size
+ ord(text[i + p_len])
) % modulus
return False
def test_rabin_karp() -> None:
"""
>>> test_rabin_karp()
Success.
"""
# Test 1)
pattern = "abc1abc12"
text1 = "alskfjaldsabc1abc1abc12k23adsfabcabc"
text2 = "alskfjaldsk23adsfabcabc"
assert rabin_karp(pattern, text1)
assert not rabin_karp(pattern, text2)
# Test 2)
pattern = "ABABX"
text = "ABABZABABYABABX"
assert rabin_karp(pattern, text)
# Test 3)
pattern = "AAAB"
text = "ABAAAAAB"
assert rabin_karp(pattern, text)
# Test 4)
pattern = "abcdabcy"
text = "abcxabcdabxabcdabcdabcy"
assert rabin_karp(pattern, text)
# Test 5)
pattern = "Lü"
text = "Lüsai"
assert rabin_karp(pattern, text)
pattern = "Lue"
assert not rabin_karp(pattern, text)
print("Success.")
if __name__ == "__main__":
test_rabin_karp()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/is_contains_unique_chars.py | strings/is_contains_unique_chars.py | def is_contains_unique_chars(input_str: str) -> bool:
"""
Check if all characters in the string is unique or not.
>>> is_contains_unique_chars("I_love.py")
True
>>> is_contains_unique_chars("I don't love Python")
False
Time complexity: O(n)
Space complexity: O(1) 19320 bytes as we are having 144697 characters in unicode
"""
# Each bit will represent each unicode character
# For example 65th bit representing 'A'
# https://stackoverflow.com/a/12811293
bitmap = 0
for ch in input_str:
ch_unicode = ord(ch)
ch_bit_index_on = pow(2, ch_unicode)
# If we already turned on bit for current character's unicode
if bitmap >> ch_unicode & 1 == 1:
return False
bitmap |= ch_bit_index_on
return True
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/strings/__init__.py | strings/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/ngram.py | strings/ngram.py | """
https://en.wikipedia.org/wiki/N-gram
"""
def create_ngram(sentence: str, ngram_size: int) -> list[str]:
"""
Create ngrams from a sentence
>>> create_ngram("I am a sentence", 2)
['I ', ' a', 'am', 'm ', ' a', 'a ', ' s', 'se', 'en', 'nt', 'te', 'en', 'nc', 'ce']
>>> create_ngram("I am an NLPer", 2)
['I ', ' a', 'am', 'm ', ' a', 'an', 'n ', ' N', 'NL', 'LP', 'Pe', 'er']
>>> create_ngram("This is short", 50)
[]
"""
return [sentence[i : i + ngram_size] for i in range(len(sentence) - ngram_size + 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/strings/prefix_function.py | strings/prefix_function.py | """
https://cp-algorithms.com/string/prefix-function.html
Prefix function Knuth-Morris-Pratt algorithm
Different algorithm than Knuth-Morris-Pratt pattern finding
E.x. Finding longest prefix which is also suffix
Time Complexity: O(n) - where n is the length of the string
"""
def prefix_function(input_string: str) -> list:
"""
For the given string this function computes value for each index(i),
which represents the longest coincidence of prefix and suffix
for given substring (input_str[0...i])
For the value of the first element the algorithm always returns 0
>>> prefix_function("aabcdaabc")
[0, 1, 0, 0, 0, 1, 2, 3, 4]
>>> prefix_function("asdasdad")
[0, 0, 0, 1, 2, 3, 4, 0]
"""
# list for the result values
prefix_result = [0] * len(input_string)
for i in range(1, len(input_string)):
# use last results for better performance - dynamic programming
j = prefix_result[i - 1]
while j > 0 and input_string[i] != input_string[j]:
j = prefix_result[j - 1]
if input_string[i] == input_string[j]:
j += 1
prefix_result[i] = j
return prefix_result
def longest_prefix(input_str: str) -> int:
"""
Prefix-function use case
Finding longest prefix which is suffix as well
>>> longest_prefix("aabcdaabc")
4
>>> longest_prefix("asdasdad")
4
>>> longest_prefix("abcab")
2
"""
# just returning maximum value of the array gives us answer
return max(prefix_function(input_str))
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/strings/aho_corasick.py | strings/aho_corasick.py | from __future__ import annotations
from collections import deque
class Automaton:
def __init__(self, keywords: list[str]):
self.adlist: list[dict] = []
self.adlist.append(
{"value": "", "next_states": [], "fail_state": 0, "output": []}
)
for keyword in keywords:
self.add_keyword(keyword)
self.set_fail_transitions()
def find_next_state(self, current_state: int, char: str) -> int | None:
for state in self.adlist[current_state]["next_states"]:
if char == self.adlist[state]["value"]:
return state
return None
def add_keyword(self, keyword: str) -> None:
current_state = 0
for character in keyword:
next_state = self.find_next_state(current_state, character)
if next_state is None:
self.adlist.append(
{
"value": character,
"next_states": [],
"fail_state": 0,
"output": [],
}
)
self.adlist[current_state]["next_states"].append(len(self.adlist) - 1)
current_state = len(self.adlist) - 1
else:
current_state = next_state
self.adlist[current_state]["output"].append(keyword)
def set_fail_transitions(self) -> None:
q: deque = deque()
for node in self.adlist[0]["next_states"]:
q.append(node)
self.adlist[node]["fail_state"] = 0
while q:
r = q.popleft()
for child in self.adlist[r]["next_states"]:
q.append(child)
state = self.adlist[r]["fail_state"]
while (
self.find_next_state(state, self.adlist[child]["value"]) is None
and state != 0
):
state = self.adlist[state]["fail_state"]
self.adlist[child]["fail_state"] = self.find_next_state(
state, self.adlist[child]["value"]
)
if self.adlist[child]["fail_state"] is None:
self.adlist[child]["fail_state"] = 0
self.adlist[child]["output"] = (
self.adlist[child]["output"]
+ self.adlist[self.adlist[child]["fail_state"]]["output"]
)
def search_in(self, string: str) -> dict[str, list[int]]:
"""
>>> A = Automaton(["what", "hat", "ver", "er"])
>>> A.search_in("whatever, err ... , wherever")
{'what': [0], 'hat': [1], 'ver': [5, 25], 'er': [6, 10, 22, 26]}
"""
result: dict = {} # returns a dict with keywords and list of its occurrences
current_state = 0
for i in range(len(string)):
while (
self.find_next_state(current_state, string[i]) is None
and current_state != 0
):
current_state = self.adlist[current_state]["fail_state"]
next_state = self.find_next_state(current_state, string[i])
if next_state is None:
current_state = 0
else:
current_state = next_state
for key in self.adlist[current_state]["output"]:
if key not in result:
result[key] = []
result[key].append(i - len(key) + 1)
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/strings/top_k_frequent_words.py | strings/top_k_frequent_words.py | """
Finds the top K most frequent words from the provided word list.
This implementation aims to show how to solve the problem using the Heap class
already present in this repository.
Computing order statistics is, in fact, a typical usage of heaps.
This is mostly shown for educational purposes, since the problem can be solved
in a few lines using collections.Counter from the Python standard library:
from collections import Counter
def top_k_frequent_words(words, k_value):
return [x[0] for x in Counter(words).most_common(k_value)]
"""
from collections import Counter
from functools import total_ordering
from data_structures.heap.heap import Heap
@total_ordering
class WordCount:
def __init__(self, word: str, count: int) -> None:
self.word = word
self.count = count
def __eq__(self, other: object) -> bool:
"""
>>> WordCount('a', 1).__eq__(WordCount('b', 1))
True
>>> WordCount('a', 1).__eq__(WordCount('a', 1))
True
>>> WordCount('a', 1).__eq__(WordCount('a', 2))
False
>>> WordCount('a', 1).__eq__(WordCount('b', 2))
False
>>> WordCount('a', 1).__eq__(1)
NotImplemented
"""
if not isinstance(other, WordCount):
return NotImplemented
return self.count == other.count
def __lt__(self, other: object) -> bool:
"""
>>> WordCount('a', 1).__lt__(WordCount('b', 1))
False
>>> WordCount('a', 1).__lt__(WordCount('a', 1))
False
>>> WordCount('a', 1).__lt__(WordCount('a', 2))
True
>>> WordCount('a', 1).__lt__(WordCount('b', 2))
True
>>> WordCount('a', 2).__lt__(WordCount('a', 1))
False
>>> WordCount('a', 2).__lt__(WordCount('b', 1))
False
>>> WordCount('a', 1).__lt__(1)
NotImplemented
"""
if not isinstance(other, WordCount):
return NotImplemented
return self.count < other.count
def top_k_frequent_words(words: list[str], k_value: int) -> list[str]:
"""
Returns the `k_value` most frequently occurring words,
in non-increasing order of occurrence.
In this context, a word is defined as an element in the provided list.
In case `k_value` is greater than the number of distinct words, a value of k equal
to the number of distinct words will be considered, instead.
>>> top_k_frequent_words(['a', 'b', 'c', 'a', 'c', 'c'], 3)
['c', 'a', 'b']
>>> top_k_frequent_words(['a', 'b', 'c', 'a', 'c', 'c'], 2)
['c', 'a']
>>> top_k_frequent_words(['a', 'b', 'c', 'a', 'c', 'c'], 1)
['c']
>>> top_k_frequent_words(['a', 'b', 'c', 'a', 'c', 'c'], 0)
[]
>>> top_k_frequent_words([], 1)
[]
>>> top_k_frequent_words(['a', 'a'], 2)
['a']
"""
heap: Heap[WordCount] = Heap()
count_by_word = Counter(words)
heap.build_max_heap(
[WordCount(word, count) for word, count in count_by_word.items()]
)
return [heap.extract_max().word for _ in range(min(k_value, len(count_by_word)))]
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/strings/is_spain_national_id.py | strings/is_spain_national_id.py | NUMBERS_PLUS_LETTER = "Input must be a string of 8 numbers plus letter"
LOOKUP_LETTERS = "TRWAGMYFPDXBNJZSQVHLCKE"
def is_spain_national_id(spanish_id: str) -> bool:
"""
Spain National Id is a string composed by 8 numbers plus a letter
The letter in fact is not part of the ID, it acts as a validator,
checking you didn't do a mistake when entering it on a system or
are giving a fake one.
https://en.wikipedia.org/wiki/Documento_Nacional_de_Identidad_(Spain)#Number
>>> is_spain_national_id("12345678Z")
True
>>> is_spain_national_id("12345678z") # It is case-insensitive
True
>>> is_spain_national_id("12345678x")
False
>>> is_spain_national_id("12345678I")
False
>>> is_spain_national_id("12345678-Z") # Some systems add a dash
True
>>> is_spain_national_id("12345678")
Traceback (most recent call last):
...
ValueError: Input must be a string of 8 numbers plus letter
>>> is_spain_national_id("123456709")
Traceback (most recent call last):
...
ValueError: Input must be a string of 8 numbers plus letter
>>> is_spain_national_id("1234567--Z")
Traceback (most recent call last):
...
ValueError: Input must be a string of 8 numbers plus letter
>>> is_spain_national_id("1234Z")
Traceback (most recent call last):
...
ValueError: Input must be a string of 8 numbers plus letter
>>> is_spain_national_id("1234ZzZZ")
Traceback (most recent call last):
...
ValueError: Input must be a string of 8 numbers plus letter
>>> is_spain_national_id(12345678)
Traceback (most recent call last):
...
TypeError: Expected string as input, found int
"""
if not isinstance(spanish_id, str):
msg = f"Expected string as input, found {type(spanish_id).__name__}"
raise TypeError(msg)
spanish_id_clean = spanish_id.replace("-", "").upper()
if len(spanish_id_clean) != 9:
raise ValueError(NUMBERS_PLUS_LETTER)
try:
number = int(spanish_id_clean[0:8])
letter = spanish_id_clean[8]
except ValueError as ex:
raise ValueError(NUMBERS_PLUS_LETTER) from ex
if letter.isdigit():
raise ValueError(NUMBERS_PLUS_LETTER)
return letter == LOOKUP_LETTERS[number % 23]
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/strings/frequency_finder.py | strings/frequency_finder.py | # Frequency Finder
import string
# frequency taken from https://en.wikipedia.org/wiki/Letter_frequency
english_letter_freq = {
"E": 12.70,
"T": 9.06,
"A": 8.17,
"O": 7.51,
"I": 6.97,
"N": 6.75,
"S": 6.33,
"H": 6.09,
"R": 5.99,
"D": 4.25,
"L": 4.03,
"C": 2.78,
"U": 2.76,
"M": 2.41,
"W": 2.36,
"F": 2.23,
"G": 2.02,
"Y": 1.97,
"P": 1.93,
"B": 1.29,
"V": 0.98,
"K": 0.77,
"J": 0.15,
"X": 0.15,
"Q": 0.10,
"Z": 0.07,
}
ETAOIN = "ETAOINSHRDLCUMWFGYPBVKJXQZ"
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def get_letter_count(message: str) -> dict[str, int]:
letter_count = dict.fromkeys(string.ascii_uppercase, 0)
for letter in message.upper():
if letter in LETTERS:
letter_count[letter] += 1
return letter_count
def get_item_at_index_zero(x: tuple) -> str:
return x[0]
def get_frequency_order(message: str) -> str:
"""
Get the frequency order of the letters in the given string
>>> get_frequency_order('Hello World')
'LOWDRHEZQXJKVBPYGFMUCSNIAT'
>>> get_frequency_order('Hello@')
'LHOEZQXJKVBPYGFWMUCDRSNIAT'
>>> get_frequency_order('h')
'HZQXJKVBPYGFWMUCLDRSNIOATE'
"""
letter_to_freq = get_letter_count(message)
freq_to_letter: dict[int, list[str]] = {
freq: [] for letter, freq in letter_to_freq.items()
}
for letter in LETTERS:
freq_to_letter[letter_to_freq[letter]].append(letter)
freq_to_letter_str: dict[int, str] = {}
for freq in freq_to_letter: # noqa: PLC0206
freq_to_letter[freq].sort(key=ETAOIN.find, reverse=True)
freq_to_letter_str[freq] = "".join(freq_to_letter[freq])
freq_pairs = list(freq_to_letter_str.items())
freq_pairs.sort(key=get_item_at_index_zero, reverse=True)
freq_order: list[str] = [freq_pair[1] for freq_pair in freq_pairs]
return "".join(freq_order)
def english_freq_match_score(message: str) -> int:
"""
>>> english_freq_match_score('Hello World')
1
"""
freq_order = get_frequency_order(message)
match_score = 0
for common_letter in ETAOIN[:6]:
if common_letter in freq_order[:6]:
match_score += 1
for uncommon_letter in ETAOIN[-6:]:
if uncommon_letter in freq_order[-6:]:
match_score += 1
return match_score
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/strings/text_justification.py | strings/text_justification.py | def text_justification(word: str, max_width: int) -> list:
"""
Will format the string such that each line has exactly
(max_width) characters and is fully (left and right) justified,
and return the list of justified text.
example 1:
string = "This is an example of text justification."
max_width = 16
output = ['This is an',
'example of text',
'justification. ']
>>> text_justification("This is an example of text justification.", 16)
['This is an', 'example of text', 'justification. ']
example 2:
string = "Two roads diverged in a yellow wood"
max_width = 16
output = ['Two roads',
'diverged in a',
'yellow wood ']
>>> text_justification("Two roads diverged in a yellow wood", 16)
['Two roads', 'diverged in a', 'yellow wood ']
Time complexity: O(m*n)
Space complexity: O(m*n)
"""
# Converting string into list of strings split by a space
words = word.split()
def justify(line: list, width: int, max_width: int) -> str:
overall_spaces_count = max_width - width
words_count = len(line)
if len(line) == 1:
# if there is only word in line
# just insert overall_spaces_count for the remainder of line
return line[0] + " " * overall_spaces_count
else:
spaces_to_insert_between_words = words_count - 1
# num_spaces_between_words_list[i] : tells you to insert
# num_spaces_between_words_list[i] spaces
# after word on line[i]
num_spaces_between_words_list = spaces_to_insert_between_words * [
overall_spaces_count // spaces_to_insert_between_words
]
spaces_count_in_locations = (
overall_spaces_count % spaces_to_insert_between_words
)
# distribute spaces via round robin to the left words
for i in range(spaces_count_in_locations):
num_spaces_between_words_list[i] += 1
aligned_words_list = []
for i in range(spaces_to_insert_between_words):
# add the word
aligned_words_list.append(line[i])
# add the spaces to insert
aligned_words_list.append(num_spaces_between_words_list[i] * " ")
# just add the last word to the sentence
aligned_words_list.append(line[-1])
# join the aligned words list to form a justified line
return "".join(aligned_words_list)
answer = []
line: list[str] = []
width = 0
for inner_word in words:
if width + len(inner_word) + len(line) <= max_width:
# keep adding words until we can fill out max_width
# width = sum of length of all words (without overall_spaces_count)
# len(inner_word) = length of current inner_word
# len(line) = number of overall_spaces_count to insert between words
line.append(inner_word)
width += len(inner_word)
else:
# justify the line and add it to result
answer.append(justify(line, width, max_width))
# reset new line and new width
line, width = [inner_word], len(inner_word)
remaining_spaces = max_width - width - len(line)
answer.append(" ".join(line) + (remaining_spaces + 1) * " ")
return answer
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/strings/detecting_english_programmatically.py | strings/detecting_english_programmatically.py | import os
from string import ascii_letters
LETTERS_AND_SPACE = ascii_letters + " \t\n"
def load_dictionary() -> dict[str, None]:
path = os.path.split(os.path.realpath(__file__))
english_words: dict[str, None] = {}
with open(path[0] + "/dictionary.txt") as dictionary_file:
for word in dictionary_file.read().split("\n"):
english_words[word] = None
return english_words
ENGLISH_WORDS = load_dictionary()
def get_english_count(message: str) -> float:
message = message.upper()
message = remove_non_letters(message)
possible_words = message.split()
matches = len([word for word in possible_words if word in ENGLISH_WORDS])
return float(matches) / len(possible_words)
def remove_non_letters(message: str) -> str:
"""
>>> remove_non_letters("Hi! how are you?")
'Hi how are you'
>>> remove_non_letters("P^y%t)h@o*n")
'Python'
>>> remove_non_letters("1+1=2")
''
>>> remove_non_letters("www.google.com/")
'wwwgooglecom'
>>> remove_non_letters("")
''
"""
return "".join(symbol for symbol in message if symbol in LETTERS_AND_SPACE)
def is_english(
message: str, word_percentage: int = 20, letter_percentage: int = 85
) -> bool:
"""
>>> is_english('Hello World')
True
>>> is_english('llold HorWd')
False
"""
words_match = get_english_count(message) * 100 >= word_percentage
num_letters = len(remove_non_letters(message))
message_letters_percentage = (float(num_letters) / len(message)) * 100
letters_match = message_letters_percentage >= letter_percentage
return words_match and letters_match
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/strings/string_switch_case.py | strings/string_switch_case.py | import re
"""
general info:
https://en.wikipedia.org/wiki/Naming_convention_(programming)#Python_and_Ruby
pascal case [ an upper Camel Case ]: https://en.wikipedia.org/wiki/Camel_case
camel case: https://en.wikipedia.org/wiki/Camel_case
kebab case [ can be found in general info ]:
https://en.wikipedia.org/wiki/Naming_convention_(programming)#Python_and_Ruby
snake case: https://en.wikipedia.org/wiki/Snake_case
"""
# assistant functions
def split_input(str_: str) -> list:
"""
>>> split_input("one two 31235three4four")
[['one', 'two', '31235three4four']]
"""
return [char.split() for char in re.split(r"[^ a-z A-Z 0-9 \s]", str_)]
def to_simple_case(str_: str) -> str:
"""
>>> to_simple_case("one two 31235three4four")
'OneTwo31235three4four'
>>> to_simple_case("This should be combined")
'ThisShouldBeCombined'
>>> to_simple_case("The first letters are capitalized, then string is merged")
'TheFirstLettersAreCapitalizedThenStringIsMerged'
>>> to_simple_case("special characters :, ', %, ^, $, are ignored")
'SpecialCharactersAreIgnored'
"""
string_split = split_input(str_)
return "".join(
["".join([char.capitalize() for char in sub_str]) for sub_str in string_split]
)
def to_complex_case(text: str, upper: bool, separator: str) -> str:
"""
Returns the string concatenated with the delimiter we provide.
Parameters:
@text: The string on which we want to perform operation
@upper: Boolean value to determine whether we want capitalized result or not
@separator: The delimiter with which we want to concatenate words
Examples:
>>> to_complex_case("one two 31235three4four", True, "_")
'ONE_TWO_31235THREE4FOUR'
>>> to_complex_case("one two 31235three4four", False, "-")
'one-two-31235three4four'
"""
try:
string_split = split_input(text)
if upper:
res_str = "".join(
[
separator.join([char.upper() for char in sub_str])
for sub_str in string_split
]
)
else:
res_str = "".join(
[
separator.join([char.lower() for char in sub_str])
for sub_str in string_split
]
)
return res_str
except IndexError:
return "not valid string"
# main content
def to_pascal_case(text: str) -> str:
"""
>>> to_pascal_case("one two 31235three4four")
'OneTwo31235three4four'
"""
return to_simple_case(text)
def to_camel_case(text: str) -> str:
"""
>>> to_camel_case("one two 31235three4four")
'oneTwo31235three4four'
"""
try:
res_str = to_simple_case(text)
return res_str[0].lower() + res_str[1:]
except IndexError:
return "not valid string"
def to_snake_case(text: str, upper: bool) -> str:
"""
>>> to_snake_case("one two 31235three4four", True)
'ONE_TWO_31235THREE4FOUR'
>>> to_snake_case("one two 31235three4four", False)
'one_two_31235three4four'
"""
return to_complex_case(text, upper, "_")
def to_kebab_case(text: str, upper: bool) -> str:
"""
>>> to_kebab_case("one two 31235three4four", True)
'ONE-TWO-31235THREE4FOUR'
>>> to_kebab_case("one two 31235three4four", False)
'one-two-31235three4four'
"""
return to_complex_case(text, upper, "-")
if __name__ == "__main__":
__import__("doctest").testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/can_string_be_rearranged_as_palindrome.py | strings/can_string_be_rearranged_as_palindrome.py | # Created by susmith98
from collections import Counter
from timeit import timeit
# Problem Description:
# Check if characters of the given string can be rearranged to form a palindrome.
# Counter is faster for long strings and non-Counter is faster for short strings.
def can_string_be_rearranged_as_palindrome_counter(
input_str: str = "",
) -> bool:
"""
A Palindrome is a String that reads the same forward as it does backwards.
Examples of Palindromes mom, dad, malayalam
>>> can_string_be_rearranged_as_palindrome_counter("Momo")
True
>>> can_string_be_rearranged_as_palindrome_counter("Mother")
False
>>> can_string_be_rearranged_as_palindrome_counter("Father")
False
>>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama")
True
"""
return sum(c % 2 for c in Counter(input_str.replace(" ", "").lower()).values()) < 2
def can_string_be_rearranged_as_palindrome(input_str: str = "") -> bool:
"""
A Palindrome is a String that reads the same forward as it does backwards.
Examples of Palindromes mom, dad, malayalam
>>> can_string_be_rearranged_as_palindrome("Momo")
True
>>> can_string_be_rearranged_as_palindrome("Mother")
False
>>> can_string_be_rearranged_as_palindrome("Father")
False
>>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama")
True
"""
if len(input_str) == 0:
return True
lower_case_input_str = input_str.replace(" ", "").lower()
# character_freq_dict: Stores the frequency of every character in the input string
character_freq_dict: dict[str, int] = {}
for character in lower_case_input_str:
character_freq_dict[character] = character_freq_dict.get(character, 0) + 1
"""
Above line of code is equivalent to:
1) Getting the frequency of current character till previous index
>>> character_freq = character_freq_dict.get(character, 0)
2) Incrementing the frequency of current character by 1
>>> character_freq = character_freq + 1
3) Updating the frequency of current character
>>> character_freq_dict[character] = character_freq
"""
"""
OBSERVATIONS:
Even length palindrome
-> Every character appears even no.of times.
Odd length palindrome
-> Every character appears even no.of times except for one character.
LOGIC:
Step 1: We'll count number of characters that appear odd number of times i.e oddChar
Step 2:If we find more than 1 character that appears odd number of times,
It is not possible to rearrange as a palindrome
"""
odd_char = 0
for character_count in character_freq_dict.values():
if character_count % 2:
odd_char += 1
return not odd_char > 1
def benchmark(input_str: str = "") -> None:
"""
Benchmark code for comparing above 2 functions
"""
print("\nFor string = ", input_str, ":")
print(
"> can_string_be_rearranged_as_palindrome_counter()",
"\tans =",
can_string_be_rearranged_as_palindrome_counter(input_str),
"\ttime =",
timeit(
"z.can_string_be_rearranged_as_palindrome_counter(z.check_str)",
setup="import __main__ as z",
),
"seconds",
)
print(
"> can_string_be_rearranged_as_palindrome()",
"\tans =",
can_string_be_rearranged_as_palindrome(input_str),
"\ttime =",
timeit(
"z.can_string_be_rearranged_as_palindrome(z.check_str)",
setup="import __main__ as z",
),
"seconds",
)
if __name__ == "__main__":
check_str = input(
"Enter string to determine if it can be rearranged as a palindrome or not: "
).strip()
benchmark(check_str)
status = can_string_be_rearranged_as_palindrome_counter(check_str)
print(f"{check_str} can {'' if status else 'not '}be rearranged as a palindrome")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/is_pangram.py | strings/is_pangram.py | """
wiki: https://en.wikipedia.org/wiki/Pangram
"""
def is_pangram(
input_str: str = "The quick brown fox jumps over the lazy dog",
) -> bool:
"""
A Pangram String contains all the alphabets at least once.
>>> is_pangram("The quick brown fox jumps over the lazy dog")
True
>>> is_pangram("Waltz, bad nymph, for quick jigs vex.")
True
>>> is_pangram("Jived fox nymph grabs quick waltz.")
True
>>> is_pangram("My name is Unknown")
False
>>> is_pangram("The quick brown fox jumps over the la_y dog")
False
>>> is_pangram()
True
"""
# Declare frequency as a set to have unique occurrences of letters
frequency = set()
# Replace all the whitespace in our sentence
input_str = input_str.replace(" ", "")
for alpha in input_str:
if "a" <= alpha.lower() <= "z":
frequency.add(alpha.lower())
return len(frequency) == 26
def is_pangram_faster(
input_str: str = "The quick brown fox jumps over the lazy dog",
) -> bool:
"""
>>> is_pangram_faster("The quick brown fox jumps over the lazy dog")
True
>>> is_pangram_faster("Waltz, bad nymph, for quick jigs vex.")
True
>>> is_pangram_faster("Jived fox nymph grabs quick waltz.")
True
>>> is_pangram_faster("The quick brown fox jumps over the la_y dog")
False
>>> is_pangram_faster()
True
"""
flag = [False] * 26
for char in input_str:
if char.islower():
flag[ord(char) - 97] = True
elif char.isupper():
flag[ord(char) - 65] = True
return all(flag)
def is_pangram_fastest(
input_str: str = "The quick brown fox jumps over the lazy dog",
) -> bool:
"""
>>> is_pangram_fastest("The quick brown fox jumps over the lazy dog")
True
>>> is_pangram_fastest("Waltz, bad nymph, for quick jigs vex.")
True
>>> is_pangram_fastest("Jived fox nymph grabs quick waltz.")
True
>>> is_pangram_fastest("The quick brown fox jumps over the la_y dog")
False
>>> is_pangram_fastest()
True
"""
return len({char for char in input_str.lower() if char.isalpha()}) == 26
def benchmark() -> None:
"""
Benchmark code comparing different version.
"""
from timeit import timeit
setup = "from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest"
print(timeit("is_pangram()", setup=setup))
print(timeit("is_pangram_faster()", setup=setup))
print(timeit("is_pangram_fastest()", setup=setup))
# 5.348480500048026, 2.6477354579837993, 1.8470395830227062
# 5.036091582966037, 2.644472333951853, 1.8869528750656173
if __name__ == "__main__":
import doctest
doctest.testmod()
benchmark()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/strings/title.py | strings/title.py | def to_title_case(word: str) -> str:
"""
Converts a string to capitalized case, preserving the input as is
>>> to_title_case("Aakash")
'Aakash'
>>> to_title_case("aakash")
'Aakash'
>>> to_title_case("AAKASH")
'Aakash'
>>> to_title_case("aAkAsH")
'Aakash'
"""
"""
Convert the first character to uppercase if it's lowercase
"""
if "a" <= word[0] <= "z":
word = chr(ord(word[0]) - 32) + word[1:]
"""
Convert the remaining characters to lowercase if they are uppercase
"""
for i in range(1, len(word)):
if "A" <= word[i] <= "Z":
word = word[:i] + chr(ord(word[i]) + 32) + word[i + 1 :]
return word
def sentence_to_title_case(input_str: str) -> str:
"""
Converts a string to title case, preserving the input as is
>>> sentence_to_title_case("Aakash Giri")
'Aakash Giri'
>>> sentence_to_title_case("aakash giri")
'Aakash Giri'
>>> sentence_to_title_case("AAKASH GIRI")
'Aakash Giri'
>>> sentence_to_title_case("aAkAsH gIrI")
'Aakash Giri'
"""
return " ".join(to_title_case(word) for word in input_str.split())
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/strings/split.py | strings/split.py | def split(string: str, separator: str = " ") -> list:
"""
Will split the string up into all the values separated by the separator
(defaults to spaces)
>>> split("apple#banana#cherry#orange",separator='#')
['apple', 'banana', 'cherry', 'orange']
>>> split("Hello there")
['Hello', 'there']
>>> split("11/22/63",separator = '/')
['11', '22', '63']
>>> split("12:43:39",separator = ":")
['12', '43', '39']
>>> split(";abbb;;c;", separator=';')
['', 'abbb', '', 'c', '']
"""
split_words = []
last_index = 0
for index, char in enumerate(string):
if char == separator:
split_words.append(string[last_index:index])
last_index = index + 1
if index + 1 == len(string):
split_words.append(string[last_index : index + 1])
return split_words
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/strings/wave_string.py | strings/wave_string.py | def wave(txt: str) -> list:
"""
Returns a so called 'wave' of a given string
>>> wave('cat')
['Cat', 'cAt', 'caT']
>>> wave('one')
['One', 'oNe', 'onE']
>>> wave('book')
['Book', 'bOok', 'boOk', 'booK']
"""
return [
txt[:a] + txt[a].upper() + txt[a + 1 :]
for a in range(len(txt))
if txt[a].isalpha()
]
if __name__ == "__main__":
__import__("doctest").testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/linear_programming/simplex.py | linear_programming/simplex.py | """
Python implementation of the simplex algorithm for solving linear programs in
tabular form with
- `>=`, `<=`, and `=` constraints and
- each variable `x1, x2, ...>= 0`.
See https://gist.github.com/imengus/f9619a568f7da5bc74eaf20169a24d98 for how to
convert linear programs to simplex tableaus, and the steps taken in the simplex
algorithm.
Resources:
https://en.wikipedia.org/wiki/Simplex_algorithm
https://tinyurl.com/simplex4beginners
"""
from typing import Any
import numpy as np
class Tableau:
"""Operate on simplex tableaus
>>> Tableau(np.array([[-1,-1,0,0,1],[1,3,1,0,4],[3,1,0,1,4]]), 2, 2)
Traceback (most recent call last):
...
TypeError: Tableau must have type float64
>>> Tableau(np.array([[-1,-1,0,0,-1],[1,3,1,0,4],[3,1,0,1,4.]]), 2, 2)
Traceback (most recent call last):
...
ValueError: RHS must be > 0
>>> Tableau(np.array([[-1,-1,0,0,1],[1,3,1,0,4],[3,1,0,1,4.]]), -2, 2)
Traceback (most recent call last):
...
ValueError: number of (artificial) variables must be a natural number
"""
# Max iteration number to prevent cycling
maxiter = 100
def __init__(
self, tableau: np.ndarray, n_vars: int, n_artificial_vars: int
) -> None:
if tableau.dtype != "float64":
raise TypeError("Tableau must have type float64")
# Check if RHS is negative
if not (tableau[:, -1] >= 0).all():
raise ValueError("RHS must be > 0")
if n_vars < 2 or n_artificial_vars < 0:
raise ValueError(
"number of (artificial) variables must be a natural number"
)
self.tableau = tableau
self.n_rows, n_cols = tableau.shape
# Number of decision variables x1, x2, x3...
self.n_vars, self.n_artificial_vars = n_vars, n_artificial_vars
# 2 if there are >= or == constraints (nonstandard), 1 otherwise (std)
self.n_stages = (self.n_artificial_vars > 0) + 1
# Number of slack variables added to make inequalities into equalities
self.n_slack = n_cols - self.n_vars - self.n_artificial_vars - 1
# Objectives for each stage
self.objectives = ["max"]
# In two stage simplex, first minimise then maximise
if self.n_artificial_vars:
self.objectives.append("min")
self.col_titles = self.generate_col_titles()
# Index of current pivot row and column
self.row_idx = None
self.col_idx = None
# Does objective row only contain (non)-negative values?
self.stop_iter = False
def generate_col_titles(self) -> list[str]:
"""Generate column titles for tableau of specific dimensions
>>> Tableau(np.array([[-1,-1,0,0,1],[1,3,1,0,4],[3,1,0,1,4.]]),
... 2, 0).generate_col_titles()
['x1', 'x2', 's1', 's2', 'RHS']
>>> Tableau(np.array([[-1,-1,0,0,1],[1,3,1,0,4],[3,1,0,1,4.]]),
... 2, 2).generate_col_titles()
['x1', 'x2', 'RHS']
"""
args = (self.n_vars, self.n_slack)
# decision | slack
string_starts = ["x", "s"]
titles = []
for i in range(2):
for j in range(args[i]):
titles.append(string_starts[i] + str(j + 1))
titles.append("RHS")
return titles
def find_pivot(self) -> tuple[Any, Any]:
"""Finds the pivot row and column.
>>> tuple(int(x) for x in Tableau(np.array([[-2,1,0,0,0], [3,1,1,0,6],
... [1,2,0,1,7.]]), 2, 0).find_pivot())
(1, 0)
"""
objective = self.objectives[-1]
# Find entries of highest magnitude in objective rows
sign = (objective == "min") - (objective == "max")
col_idx = np.argmax(sign * self.tableau[0, :-1])
# Choice is only valid if below 0 for maximise, and above for minimise
if sign * self.tableau[0, col_idx] <= 0:
self.stop_iter = True
return 0, 0
# Pivot row is chosen as having the lowest quotient when elements of
# the pivot column divide the right-hand side
# Slice excluding the objective rows
s = slice(self.n_stages, self.n_rows)
# RHS
dividend = self.tableau[s, -1]
# Elements of pivot column within slice
divisor = self.tableau[s, col_idx]
# Array filled with nans
nans = np.full(self.n_rows - self.n_stages, np.nan)
# If element in pivot column is greater than zero, return
# quotient or nan otherwise
quotients = np.divide(dividend, divisor, out=nans, where=divisor > 0)
# Arg of minimum quotient excluding the nan values. n_stages is added
# to compensate for earlier exclusion of objective columns
row_idx = np.nanargmin(quotients) + self.n_stages
return row_idx, col_idx
def pivot(self, row_idx: int, col_idx: int) -> np.ndarray:
"""Pivots on value on the intersection of pivot row and column.
>>> Tableau(np.array([[-2,-3,0,0,0],[1,3,1,0,4],[3,1,0,1,4.]]),
... 2, 2).pivot(1, 0).tolist()
... # doctest: +NORMALIZE_WHITESPACE
[[0.0, 3.0, 2.0, 0.0, 8.0],
[1.0, 3.0, 1.0, 0.0, 4.0],
[0.0, -8.0, -3.0, 1.0, -8.0]]
"""
# Avoid changes to original tableau
piv_row = self.tableau[row_idx].copy()
piv_val = piv_row[col_idx]
# Entry becomes 1
piv_row *= 1 / piv_val
# Variable in pivot column becomes basic, ie the only non-zero entry
for idx, coeff in enumerate(self.tableau[:, col_idx]):
self.tableau[idx] += -coeff * piv_row
self.tableau[row_idx] = piv_row
return self.tableau
def change_stage(self) -> np.ndarray:
"""Exits first phase of the two-stage method by deleting artificial
rows and columns, or completes the algorithm if exiting the standard
case.
>>> Tableau(np.array([
... [3, 3, -1, -1, 0, 0, 4],
... [2, 1, 0, 0, 0, 0, 0.],
... [1, 2, -1, 0, 1, 0, 2],
... [2, 1, 0, -1, 0, 1, 2]
... ]), 2, 2).change_stage().tolist()
... # doctest: +NORMALIZE_WHITESPACE
[[2.0, 1.0, 0.0, 0.0, 0.0],
[1.0, 2.0, -1.0, 0.0, 2.0],
[2.0, 1.0, 0.0, -1.0, 2.0]]
"""
# Objective of original objective row remains
self.objectives.pop()
if not self.objectives:
return self.tableau
# Slice containing ids for artificial columns
s = slice(-self.n_artificial_vars - 1, -1)
# Delete the artificial variable columns
self.tableau = np.delete(self.tableau, s, axis=1)
# Delete the objective row of the first stage
self.tableau = np.delete(self.tableau, 0, axis=0)
self.n_stages = 1
self.n_rows -= 1
self.n_artificial_vars = 0
self.stop_iter = False
return self.tableau
def run_simplex(self) -> dict[Any, Any]:
"""Operate on tableau until objective function cannot be
improved further.
# Standard linear program:
Max: x1 + x2
ST: x1 + 3x2 <= 4
3x1 + x2 <= 4
>>> {key: float(value) for key, value in Tableau(np.array([[-1,-1,0,0,0],
... [1,3,1,0,4],[3,1,0,1,4.]]), 2, 0).run_simplex().items()}
{'P': 2.0, 'x1': 1.0, 'x2': 1.0}
# Standard linear program with 3 variables:
Max: 3x1 + x2 + 3x3
ST: 2x1 + x2 + x3 ≤ 2
x1 + 2x2 + 3x3 ≤ 5
2x1 + 2x2 + x3 ≤ 6
>>> {key: float(value) for key, value in Tableau(np.array([
... [-3,-1,-3,0,0,0,0],
... [2,1,1,1,0,0,2],
... [1,2,3,0,1,0,5],
... [2,2,1,0,0,1,6.]
... ]),3,0).run_simplex().items()} # doctest: +ELLIPSIS
{'P': 5.4, 'x1': 0.199..., 'x3': 1.6}
# Optimal tableau input:
>>> {key: float(value) for key, value in Tableau(np.array([
... [0, 0, 0.25, 0.25, 2],
... [0, 1, 0.375, -0.125, 1],
... [1, 0, -0.125, 0.375, 1]
... ]), 2, 0).run_simplex().items()}
{'P': 2.0, 'x1': 1.0, 'x2': 1.0}
# Non-standard: >= constraints
Max: 2x1 + 3x2 + x3
ST: x1 + x2 + x3 <= 40
2x1 + x2 - x3 >= 10
- x2 + x3 >= 10
>>> {key: float(value) for key, value in Tableau(np.array([
... [2, 0, 0, 0, -1, -1, 0, 0, 20],
... [-2, -3, -1, 0, 0, 0, 0, 0, 0],
... [1, 1, 1, 1, 0, 0, 0, 0, 40],
... [2, 1, -1, 0, -1, 0, 1, 0, 10],
... [0, -1, 1, 0, 0, -1, 0, 1, 10.]
... ]), 3, 2).run_simplex().items()}
{'P': 70.0, 'x1': 10.0, 'x2': 10.0, 'x3': 20.0}
# Non standard: minimisation and equalities
Min: x1 + x2
ST: 2x1 + x2 = 12
6x1 + 5x2 = 40
>>> {key: float(value) for key, value in Tableau(np.array([
... [8, 6, 0, 0, 52],
... [1, 1, 0, 0, 0],
... [2, 1, 1, 0, 12],
... [6, 5, 0, 1, 40.],
... ]), 2, 2).run_simplex().items()}
{'P': 7.0, 'x1': 5.0, 'x2': 2.0}
# Pivot on slack variables
Max: 8x1 + 6x2
ST: x1 + 3x2 <= 33
4x1 + 2x2 <= 48
2x1 + 4x2 <= 48
x1 + x2 >= 10
x1 >= 2
>>> {key: float(value) for key, value in Tableau(np.array([
... [2, 1, 0, 0, 0, -1, -1, 0, 0, 12.0],
... [-8, -6, 0, 0, 0, 0, 0, 0, 0, 0.0],
... [1, 3, 1, 0, 0, 0, 0, 0, 0, 33.0],
... [4, 2, 0, 1, 0, 0, 0, 0, 0, 60.0],
... [2, 4, 0, 0, 1, 0, 0, 0, 0, 48.0],
... [1, 1, 0, 0, 0, -1, 0, 1, 0, 10.0],
... [1, 0, 0, 0, 0, 0, -1, 0, 1, 2.0]
... ]), 2, 2).run_simplex().items()} # doctest: +ELLIPSIS
{'P': 132.0, 'x1': 12.000... 'x2': 5.999...}
"""
# Stop simplex algorithm from cycling.
for _ in range(Tableau.maxiter):
# Completion of each stage removes an objective. If both stages
# are complete, then no objectives are left
if not self.objectives:
# Find the values of each variable at optimal solution
return self.interpret_tableau()
row_idx, col_idx = self.find_pivot()
# If there are no more negative values in objective row
if self.stop_iter:
# Delete artificial variable columns and rows. Update attributes
self.tableau = self.change_stage()
else:
self.tableau = self.pivot(row_idx, col_idx)
return {}
def interpret_tableau(self) -> dict[str, float]:
"""Given the final tableau, add the corresponding values of the basic
decision variables to the `output_dict`
>>> {key: float(value) for key, value in Tableau(np.array([
... [0,0,0.875,0.375,5],
... [0,1,0.375,-0.125,1],
... [1,0,-0.125,0.375,1]
... ]),2, 0).interpret_tableau().items()}
{'P': 5.0, 'x1': 1.0, 'x2': 1.0}
"""
# P = RHS of final tableau
output_dict = {"P": abs(self.tableau[0, -1])}
for i in range(self.n_vars):
# Gives indices of nonzero entries in the ith column
nonzero = np.nonzero(self.tableau[:, i])
n_nonzero = len(nonzero[0])
# First entry in the nonzero indices
nonzero_rowidx = nonzero[0][0]
nonzero_val = self.tableau[nonzero_rowidx, i]
# If there is only one nonzero value in column, which is one
if n_nonzero == 1 and nonzero_val == 1:
rhs_val = self.tableau[nonzero_rowidx, -1]
output_dict[self.col_titles[i]] = rhs_val
return output_dict
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/linear_programming/__init__.py | linear_programming/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/knapsack/knapsack.py | knapsack/knapsack.py | """A recursive implementation of 0-N Knapsack Problem
https://en.wikipedia.org/wiki/Knapsack_problem
"""
from __future__ import annotations
from functools import lru_cache
def knapsack(
capacity: int,
weights: list[int],
values: list[int],
counter: int,
allow_repetition=False,
) -> int:
"""
Returns the maximum value that can be put in a knapsack of a capacity cap,
whereby each weight w has a specific value val
with option to allow repetitive selection of items
>>> cap = 50
>>> val = [60, 100, 120]
>>> w = [10, 20, 30]
>>> c = len(val)
>>> knapsack(cap, w, val, c)
220
Given the repetition is NOT allowed,
the result is 220 cause the values of 100 and 120 got the weight of 50
which is the limit of the capacity.
>>> knapsack(cap, w, val, c, True)
300
Given the repetition is allowed,
the result is 300 cause the values of 60*5 (pick 5 times)
got the weight of 10*5 which is the limit of the capacity.
"""
@lru_cache
def knapsack_recur(capacity: int, counter: int) -> int:
# Base Case
if counter == 0 or capacity == 0:
return 0
# If weight of the nth item is more than Knapsack of capacity,
# then this item cannot be included in the optimal solution,
# else return the maximum of two cases:
# (1) nth item included only once (0-1), if allow_repetition is False
# nth item included one or more times (0-N), if allow_repetition is True
# (2) not included
if weights[counter - 1] > capacity:
return knapsack_recur(capacity, counter - 1)
else:
left_capacity = capacity - weights[counter - 1]
new_value_included = values[counter - 1] + knapsack_recur(
left_capacity, counter - 1 if not allow_repetition else counter
)
without_new_value = knapsack_recur(capacity, counter - 1)
return max(new_value_included, without_new_value)
return knapsack_recur(capacity, counter)
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/knapsack/__init__.py | knapsack/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/knapsack/greedy_knapsack.py | knapsack/greedy_knapsack.py | # To get an insight into Greedy Algorithm through the Knapsack problem
"""
A shopkeeper has bags of wheat that each have different weights and different profits.
eg.
profit 5 8 7 1 12 3 4
weight 2 7 1 6 4 2 5
max_weight 100
Constraints:
max_weight > 0
profit[i] >= 0
weight[i] >= 0
Calculate the maximum profit that the shopkeeper can make given maxmum weight that can
be carried.
"""
def calc_profit(profit: list, weight: list, max_weight: int) -> int:
"""
Function description is as follows-
:param profit: Take a list of profits
:param weight: Take a list of weight if bags corresponding to the profits
:param max_weight: Maximum weight that could be carried
:return: Maximum expected gain
>>> calc_profit([1, 2, 3], [3, 4, 5], 15)
6
>>> calc_profit([10, 9 , 8], [3 ,4 , 5], 25)
27
"""
if len(profit) != len(weight):
raise ValueError("The length of profit and weight must be same.")
if max_weight <= 0:
raise ValueError("max_weight must greater than zero.")
if any(p < 0 for p in profit):
raise ValueError("Profit can not be negative.")
if any(w < 0 for w in weight):
raise ValueError("Weight can not be negative.")
# List created to store profit gained for the 1kg in case of each weight
# respectively. Calculate and append profit/weight for each element.
profit_by_weight = [p / w for p, w in zip(profit, weight)]
# Creating a copy of the list and sorting profit/weight in ascending order
sorted_profit_by_weight = sorted(profit_by_weight)
# declaring useful variables
length = len(sorted_profit_by_weight)
limit = 0
gain = 0
i = 0
# loop till the total weight do not reach max limit e.g. 15 kg and till i<length
while limit <= max_weight and i < length:
# flag value for encountered greatest element in sorted_profit_by_weight
biggest_profit_by_weight = sorted_profit_by_weight[length - i - 1]
"""
Calculate the index of the biggest_profit_by_weight in profit_by_weight list.
This will give the index of the first encountered element which is same as of
biggest_profit_by_weight. There may be one or more values same as that of
biggest_profit_by_weight but index always encounter the very first element
only. To curb this alter the values in profit_by_weight once they are used
here it is done to -1 because neither profit nor weight can be in negative.
"""
index = profit_by_weight.index(biggest_profit_by_weight)
profit_by_weight[index] = -1
# check if the weight encountered is less than the total weight
# encountered before.
if max_weight - limit >= weight[index]:
limit += weight[index]
# Adding profit gained for the given weight 1 ===
# weight[index]/weight[index]
gain += 1 * profit[index]
else:
# Since the weight encountered is greater than limit, therefore take the
# required number of remaining kgs and calculate profit for it.
# weight remaining / weight[index]
gain += (max_weight - limit) / weight[index] * profit[index]
break
i += 1
return gain
if __name__ == "__main__":
print(
"Input profits, weights, and then max_weight (all positive ints) separated by "
"spaces."
)
profit = [int(x) for x in input("Input profits separated by spaces: ").split()]
weight = [int(x) for x in input("Input weights separated by spaces: ").split()]
max_weight = int(input("Max weight allowed: "))
# Function Call
calc_profit(profit, weight, max_weight)
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/knapsack/recursive_approach_knapsack.py | knapsack/recursive_approach_knapsack.py | # To get an insight into naive recursive way to solve the Knapsack problem
"""
A shopkeeper has bags of wheat that each have different weights and different profits.
eg.
no_of_items 4
profit 5 4 8 6
weight 1 2 4 5
max_weight 5
Constraints:
max_weight > 0
profit[i] >= 0
weight[i] >= 0
Calculate the maximum profit that the shopkeeper can make given maxmum weight that can
be carried.
"""
def knapsack(
weights: list, values: list, number_of_items: int, max_weight: int, index: int
) -> int:
"""
Function description is as follows-
:param weights: Take a list of weights
:param values: Take a list of profits corresponding to the weights
:param number_of_items: number of items available to pick from
:param max_weight: Maximum weight that could be carried
:param index: the element we are looking at
:return: Maximum expected gain
>>> knapsack([1, 2, 4, 5], [5, 4, 8, 6], 4, 5, 0)
13
>>> knapsack([3 ,4 , 5], [10, 9 , 8], 3, 25, 0)
27
"""
if index == number_of_items:
return 0
ans1 = 0
ans2 = 0
ans1 = knapsack(weights, values, number_of_items, max_weight, index + 1)
if weights[index] <= max_weight:
ans2 = values[index] + knapsack(
weights, values, number_of_items, max_weight - weights[index], index + 1
)
return max(ans1, ans2)
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/knapsack/tests/test_greedy_knapsack.py | knapsack/tests/test_greedy_knapsack.py | import unittest
import pytest
from knapsack import greedy_knapsack as kp
class TestClass(unittest.TestCase):
"""
Test cases for knapsack
"""
def test_sorted(self):
"""
kp.calc_profit takes the required argument (profit, weight, max_weight)
and returns whether the answer matches to the expected ones
"""
profit = [10, 20, 30, 40, 50, 60]
weight = [2, 4, 6, 8, 10, 12]
max_weight = 100
assert kp.calc_profit(profit, weight, max_weight) == 210
def test_negative_max_weight(self):
"""
Returns ValueError for any negative max_weight value
:return: ValueError
"""
# profit = [10, 20, 30, 40, 50, 60]
# weight = [2, 4, 6, 8, 10, 12]
# max_weight = -15
pytest.raises(ValueError, match=r"max_weight must greater than zero.")
def test_negative_profit_value(self):
"""
Returns ValueError for any negative profit value in the list
:return: ValueError
"""
# profit = [10, -20, 30, 40, 50, 60]
# weight = [2, 4, 6, 8, 10, 12]
# max_weight = 15
pytest.raises(ValueError, match=r"Weight can not be negative.")
def test_negative_weight_value(self):
"""
Returns ValueError for any negative weight value in the list
:return: ValueError
"""
# profit = [10, 20, 30, 40, 50, 60]
# weight = [2, -4, 6, -8, 10, 12]
# max_weight = 15
pytest.raises(ValueError, match=r"Profit can not be negative.")
def test_null_max_weight(self):
"""
Returns ValueError for any zero max_weight value
:return: ValueError
"""
# profit = [10, 20, 30, 40, 50, 60]
# weight = [2, 4, 6, 8, 10, 12]
# max_weight = null
pytest.raises(ValueError, match=r"max_weight must greater than zero.")
def test_unequal_list_length(self):
"""
Returns IndexError if length of lists (profit and weight) are unequal.
:return: IndexError
"""
# profit = [10, 20, 30, 40, 50]
# weight = [2, 4, 6, 8, 10, 12]
# max_weight = 100
pytest.raises(
IndexError, match=r"The length of profit and weight must be same."
)
if __name__ == "__main__":
unittest.main()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/knapsack/tests/test_knapsack.py | knapsack/tests/test_knapsack.py | """
Created on Fri Oct 16 09:31:07 2020
@author: Dr. Tobias Schröder
@license: MIT-license
This file contains the test-suite for the knapsack problem.
"""
import unittest
from knapsack import knapsack as k
class Test(unittest.TestCase):
def test_base_case(self):
"""
test for the base case
"""
cap = 0
val = [0]
w = [0]
c = len(val)
assert k.knapsack(cap, w, val, c) == 0
val = [60]
w = [10]
c = len(val)
assert k.knapsack(cap, w, val, c) == 0
def test_easy_case(self):
"""
test for the easy case
"""
cap = 3
val = [1, 2, 3]
w = [3, 2, 1]
c = len(val)
assert k.knapsack(cap, w, val, c) == 5
def test_knapsack(self):
"""
test for the knapsack
"""
cap = 50
val = [60, 100, 120]
w = [10, 20, 30]
c = len(val)
assert k.knapsack(cap, w, val, c) == 220
def test_knapsack_repetition(self):
"""
test for the knapsack repetition
"""
cap = 50
val = [60, 100, 120]
w = [10, 20, 30]
c = len(val)
assert k.knapsack(cap, w, val, c, True) == 300
if __name__ == "__main__":
unittest.main()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/knapsack/tests/__init__.py | knapsack/tests/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/beaufort_cipher.py | ciphers/beaufort_cipher.py | """
Author: Mohit Radadiya
"""
from string import ascii_uppercase
dict1 = {char: i for i, char in enumerate(ascii_uppercase)}
dict2 = dict(enumerate(ascii_uppercase))
# This function generates the key in
# a cyclic manner until it's length isn't
# equal to the length of original text
def generate_key(message: str, key: str) -> str:
"""
>>> generate_key("THE GERMAN ATTACK","SECRET")
'SECRETSECRETSECRE'
"""
x = len(message)
i = 0
while True:
if x == i:
i = 0
if len(key) == len(message):
break
key += key[i]
i += 1
return key
# This function returns the encrypted text
# generated with the help of the key
def cipher_text(message: str, key_new: str) -> str:
"""
>>> cipher_text("THE GERMAN ATTACK","SECRETSECRETSECRE")
'BDC PAYUWL JPAIYI'
"""
cipher_text = ""
i = 0
for letter in message:
if letter == " ":
cipher_text += " "
else:
x = (dict1[letter] - dict1[key_new[i]]) % 26
i += 1
cipher_text += dict2[x]
return cipher_text
# This function decrypts the encrypted text
# and returns the original text
def original_text(cipher_text: str, key_new: str) -> str:
"""
>>> original_text("BDC PAYUWL JPAIYI","SECRETSECRETSECRE")
'THE GERMAN ATTACK'
"""
or_txt = ""
i = 0
for letter in cipher_text:
if letter == " ":
or_txt += " "
else:
x = (dict1[letter] + dict1[key_new[i]] + 26) % 26
i += 1
or_txt += dict2[x]
return or_txt
def main() -> None:
message = "THE GERMAN ATTACK"
key = "SECRET"
key_new = generate_key(message, key)
s = cipher_text(message, key_new)
print(f"Encrypted Text = {s}")
print(f"Original Text = {original_text(s, key_new)}")
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/running_key_cipher.py | ciphers/running_key_cipher.py | """
https://en.wikipedia.org/wiki/Running_key_cipher
"""
def running_key_encrypt(key: str, plaintext: str) -> str:
"""
Encrypts the plaintext using the Running Key Cipher.
:param key: The running key (long piece of text).
:param plaintext: The plaintext to be encrypted.
:return: The ciphertext.
"""
plaintext = plaintext.replace(" ", "").upper()
key = key.replace(" ", "").upper()
key_length = len(key)
ciphertext = []
ord_a = ord("A")
for i, char in enumerate(plaintext):
p = ord(char) - ord_a
k = ord(key[i % key_length]) - ord_a
c = (p + k) % 26
ciphertext.append(chr(c + ord_a))
return "".join(ciphertext)
def running_key_decrypt(key: str, ciphertext: str) -> str:
"""
Decrypts the ciphertext using the Running Key Cipher.
:param key: The running key (long piece of text).
:param ciphertext: The ciphertext to be decrypted.
:return: The plaintext.
"""
ciphertext = ciphertext.replace(" ", "").upper()
key = key.replace(" ", "").upper()
key_length = len(key)
plaintext = []
ord_a = ord("A")
for i, char in enumerate(ciphertext):
c = ord(char) - ord_a
k = ord(key[i % key_length]) - ord_a
p = (c - k) % 26
plaintext.append(chr(p + ord_a))
return "".join(plaintext)
def test_running_key_encrypt() -> None:
"""
>>> key = "How does the duck know that? said Victor"
>>> ciphertext = running_key_encrypt(key, "DEFEND THIS")
>>> running_key_decrypt(key, ciphertext) == "DEFENDTHIS"
True
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
test_running_key_encrypt()
plaintext = input("Enter the plaintext: ").upper()
print(f"\n{plaintext = }")
key = "How does the duck know that? said Victor"
encrypted_text = running_key_encrypt(key, plaintext)
print(f"{encrypted_text = }")
decrypted_text = running_key_decrypt(key, encrypted_text)
print(f"{decrypted_text = }")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/cryptomath_module.py | ciphers/cryptomath_module.py | from maths.greatest_common_divisor import gcd_by_iterative
def find_mod_inverse(a: int, m: int) -> int:
if gcd_by_iterative(a, m) != 1:
msg = f"mod inverse of {a!r} and {m!r} does not exist"
raise ValueError(msg)
u1, u2, u3 = 1, 0, a
v1, v2, v3 = 0, 1, m
while v3 != 0:
q = u3 // v3
v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3
return u1 % m
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/deterministic_miller_rabin.py | ciphers/deterministic_miller_rabin.py | """Created by Nathan Damon, @bizzfitch on github
>>> test_miller_rabin()
"""
def miller_rabin(n: int, allow_probable: bool = False) -> bool:
"""Deterministic Miller-Rabin algorithm for primes ~< 3.32e24.
Uses numerical analysis results to return whether or not the passed number
is prime. If the passed number is above the upper limit, and
allow_probable is True, then a return value of True indicates that n is
probably prime. This test does not allow False negatives- a return value
of False is ALWAYS composite.
Parameters
----------
n : int
The integer to be tested. Since we usually care if a number is prime,
n < 2 returns False instead of raising a ValueError.
allow_probable: bool, default False
Whether or not to test n above the upper bound of the deterministic test.
Raises
------
ValueError
Reference
---------
https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
"""
if n == 2:
return True
if not n % 2 or n < 2:
return False
if n > 5 and n % 10 not in (1, 3, 7, 9): # can quickly check last digit
return False
if n > 3_317_044_064_679_887_385_961_981 and not allow_probable:
raise ValueError(
"Warning: upper bound of deterministic test is exceeded. "
"Pass allow_probable=True to allow probabilistic test. "
"A return value of True indicates a probable prime."
)
# array bounds provided by analysis
bounds = [
2_047,
1_373_653,
25_326_001,
3_215_031_751,
2_152_302_898_747,
3_474_749_660_383,
341_550_071_728_321,
1,
3_825_123_056_546_413_051,
1,
1,
318_665_857_834_031_151_167_461,
3_317_044_064_679_887_385_961_981,
]
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
for idx, _p in enumerate(bounds, 1):
if n < _p:
# then we have our last prime to check
plist = primes[:idx]
break
d, s = n - 1, 0
# break up n -1 into a power of 2 (s) and
# remaining odd component
# essentially, solve for d * 2 ** s == n - 1
while d % 2 == 0:
d //= 2
s += 1
for prime in plist:
pr = False
for r in range(s):
m = pow(prime, d * 2**r, n)
# see article for analysis explanation for m
if (r == 0 and m == 1) or ((m + 1) % n == 0):
pr = True
# this loop will not determine compositeness
break
if pr:
continue
# if pr is False, then the above loop never evaluated to true,
# and the n MUST be composite
return False
return True
def test_miller_rabin() -> None:
"""Testing a nontrivial (ends in 1, 3, 7, 9) composite
and a prime in each range.
"""
assert not miller_rabin(561)
assert miller_rabin(563)
# 2047
assert not miller_rabin(838_201)
assert miller_rabin(838_207)
# 1_373_653
assert not miller_rabin(17_316_001)
assert miller_rabin(17_316_017)
# 25_326_001
assert not miller_rabin(3_078_386_641)
assert miller_rabin(3_078_386_653)
# 3_215_031_751
assert not miller_rabin(1_713_045_574_801)
assert miller_rabin(1_713_045_574_819)
# 2_152_302_898_747
assert not miller_rabin(2_779_799_728_307)
assert miller_rabin(2_779_799_728_327)
# 3_474_749_660_383
assert not miller_rabin(113_850_023_909_441)
assert miller_rabin(113_850_023_909_527)
# 341_550_071_728_321
assert not miller_rabin(1_275_041_018_848_804_351)
assert miller_rabin(1_275_041_018_848_804_391)
# 3_825_123_056_546_413_051
assert not miller_rabin(79_666_464_458_507_787_791_867)
assert miller_rabin(79_666_464_458_507_787_791_951)
# 318_665_857_834_031_151_167_461
assert not miller_rabin(552_840_677_446_647_897_660_333)
assert miller_rabin(552_840_677_446_647_897_660_359)
# 3_317_044_064_679_887_385_961_981
# upper limit for probabilistic test
if __name__ == "__main__":
test_miller_rabin()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/atbash.py | ciphers/atbash.py | """https://en.wikipedia.org/wiki/Atbash"""
import string
def atbash_slow(sequence: str) -> str:
"""
>>> atbash_slow("ABCDEFG")
'ZYXWVUT'
>>> atbash_slow("aW;;123BX")
'zD;;123YC'
"""
output = ""
for i in sequence:
extract = ord(i)
if 65 <= extract <= 90:
output += chr(155 - extract)
elif 97 <= extract <= 122:
output += chr(219 - extract)
else:
output += i
return output
def atbash(sequence: str) -> str:
"""
>>> atbash("ABCDEFG")
'ZYXWVUT'
>>> atbash("aW;;123BX")
'zD;;123YC'
"""
letters = string.ascii_letters
letters_reversed = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1]
return "".join(
letters_reversed[letters.index(c)] if c in letters else c for c in sequence
)
def benchmark() -> None:
"""Let's benchmark our functions side-by-side..."""
from timeit import timeit
print("Running performance benchmarks...")
setup = "from string import printable ; from __main__ import atbash, atbash_slow"
print(f"> atbash_slow(): {timeit('atbash_slow(printable)', setup=setup)} seconds")
print(f"> atbash(): {timeit('atbash(printable)', setup=setup)} seconds")
if __name__ == "__main__":
for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"):
print(f"{example} encrypted in atbash: {atbash(example)}")
benchmark()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/hill_cipher.py | ciphers/hill_cipher.py | """
Hill Cipher:
The 'HillCipher' class below implements the Hill Cipher algorithm which uses
modern linear algebra techniques to encode and decode text using an encryption
key matrix.
Algorithm:
Let the order of the encryption key be N (as it is a square matrix).
Your text is divided into batches of length N and converted to numerical vectors
by a simple mapping starting with A=0 and so on.
The key is then multiplied with the newly created batch vector to obtain the
encoded vector. After each multiplication modular 36 calculations are performed
on the vectors so as to bring the numbers between 0 and 36 and then mapped with
their corresponding alphanumerics.
While decrypting, the decrypting key is found which is the inverse of the
encrypting key modular 36. The same process is repeated for decrypting to get
the original message back.
Constraints:
The determinant of the encryption key matrix must be relatively prime w.r.t 36.
Note:
This implementation only considers alphanumerics in the text. If the length of
the text to be encrypted is not a multiple of the break key(the length of one
batch of letters), the last character of the text is added to the text until the
length of the text reaches a multiple of the break_key. So the text after
decrypting might be a little different than the original text.
References:
https://apprendre-en-ligne.net/crypto/hill/Hillciph.pdf
https://www.youtube.com/watch?v=kfmNeskzs2o
https://www.youtube.com/watch?v=4RhLNDqcjpA
"""
import string
import numpy as np
from maths.greatest_common_divisor import greatest_common_divisor
class HillCipher:
key_string = string.ascii_uppercase + string.digits
# This cipher takes alphanumerics into account
# i.e. a total of 36 characters
# take x and return x % len(key_string)
modulus = np.vectorize(lambda x: x % 36)
to_int = np.vectorize(round)
def __init__(self, encrypt_key: np.ndarray) -> None:
"""
encrypt_key is an NxN numpy array
"""
self.encrypt_key = self.modulus(encrypt_key) # mod36 calc's on the encrypt key
self.check_determinant() # validate the determinant of the encryption key
self.break_key = encrypt_key.shape[0]
def replace_letters(self, letter: str) -> int:
"""
>>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]]))
>>> hill_cipher.replace_letters('T')
19
>>> hill_cipher.replace_letters('0')
26
"""
return self.key_string.index(letter)
def replace_digits(self, num: int) -> str:
"""
>>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]]))
>>> hill_cipher.replace_digits(19)
'T'
>>> hill_cipher.replace_digits(26)
'0'
>>> hill_cipher.replace_digits(26.1)
'0'
"""
return self.key_string[int(num)]
def check_determinant(self) -> None:
"""
>>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]]))
>>> hill_cipher.check_determinant()
"""
det = round(np.linalg.det(self.encrypt_key))
if det < 0:
det = det % len(self.key_string)
req_l = len(self.key_string)
if greatest_common_divisor(det, len(self.key_string)) != 1:
msg = (
f"determinant modular {req_l} of encryption key({det}) "
f"is not co prime w.r.t {req_l}.\nTry another key."
)
raise ValueError(msg)
def process_text(self, text: str) -> str:
"""
>>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]]))
>>> hill_cipher.process_text('Testing Hill Cipher')
'TESTINGHILLCIPHERR'
>>> hill_cipher.process_text('hello')
'HELLOO'
"""
chars = [char for char in text.upper() if char in self.key_string]
last = chars[-1]
while len(chars) % self.break_key != 0:
chars.append(last)
return "".join(chars)
def encrypt(self, text: str) -> str:
"""
>>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]]))
>>> hill_cipher.encrypt('testing hill cipher')
'WHXYJOLM9C6XT085LL'
>>> hill_cipher.encrypt('hello')
'85FF00'
"""
text = self.process_text(text.upper())
encrypted = ""
for i in range(0, len(text) - self.break_key + 1, self.break_key):
batch = text[i : i + self.break_key]
vec = [self.replace_letters(char) for char in batch]
batch_vec = np.array([vec]).T
batch_encrypted = self.modulus(self.encrypt_key.dot(batch_vec)).T.tolist()[
0
]
encrypted_batch = "".join(
self.replace_digits(num) for num in batch_encrypted
)
encrypted += encrypted_batch
return encrypted
def make_decrypt_key(self) -> np.ndarray:
"""
>>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]]))
>>> hill_cipher.make_decrypt_key()
array([[ 6, 25],
[ 5, 26]])
"""
det = round(np.linalg.det(self.encrypt_key))
if det < 0:
det = det % len(self.key_string)
det_inv = None
for i in range(len(self.key_string)):
if (det * i) % len(self.key_string) == 1:
det_inv = i
break
inv_key = (
det_inv * np.linalg.det(self.encrypt_key) * np.linalg.inv(self.encrypt_key)
)
return self.to_int(self.modulus(inv_key))
def decrypt(self, text: str) -> str:
"""
>>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]]))
>>> hill_cipher.decrypt('WHXYJOLM9C6XT085LL')
'TESTINGHILLCIPHERR'
>>> hill_cipher.decrypt('85FF00')
'HELLOO'
"""
decrypt_key = self.make_decrypt_key()
text = self.process_text(text.upper())
decrypted = ""
for i in range(0, len(text) - self.break_key + 1, self.break_key):
batch = text[i : i + self.break_key]
vec = [self.replace_letters(char) for char in batch]
batch_vec = np.array([vec]).T
batch_decrypted = self.modulus(decrypt_key.dot(batch_vec)).T.tolist()[0]
decrypted_batch = "".join(
self.replace_digits(num) for num in batch_decrypted
)
decrypted += decrypted_batch
return decrypted
def main() -> None:
n = int(input("Enter the order of the encryption key: "))
hill_matrix = []
print("Enter each row of the encryption key with space separated integers")
for _ in range(n):
row = [int(x) for x in input().split()]
hill_matrix.append(row)
hc = HillCipher(np.array(hill_matrix))
print("Would you like to encrypt or decrypt some text? (1 or 2)")
option = input("\n1. Encrypt\n2. Decrypt\n")
if option == "1":
text_e = input("What text would you like to encrypt?: ")
print("Your encrypted text is:")
print(hc.encrypt(text_e))
elif option == "2":
text_d = input("What text would you like to decrypt?: ")
print("Your decrypted text is:")
print(hc.decrypt(text_d))
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_key_generator.py | ciphers/rsa_key_generator.py | import os
import random
import sys
from maths.greatest_common_divisor import gcd_by_iterative
from . import cryptomath_module, rabin_miller
def main() -> None:
print("Making key files...")
make_key_files("rsa", 1024)
print("Key files generation successful.")
def generate_key(key_size: int) -> tuple[tuple[int, int], tuple[int, int]]:
"""
>>> random.seed(0) # for repeatability
>>> public_key, private_key = generate_key(8)
>>> public_key
(26569, 239)
>>> private_key
(26569, 2855)
"""
p = rabin_miller.generate_large_prime(key_size)
q = rabin_miller.generate_large_prime(key_size)
n = p * q
# Generate e that is relatively prime to (p - 1) * (q - 1)
while True:
e = random.randrange(2 ** (key_size - 1), 2 ** (key_size))
if gcd_by_iterative(e, (p - 1) * (q - 1)) == 1:
break
# Calculate d that is mod inverse of e
d = cryptomath_module.find_mod_inverse(e, (p - 1) * (q - 1))
public_key = (n, e)
private_key = (n, 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 out_file:
out_file.write(f"{key_size},{public_key[0]},{public_key[1]}")
print(f"Writing private key to file {name}_privkey.txt...")
with open(f"{name}_privkey.txt", "w") as out_file:
out_file.write(f"{key_size},{private_key[0]},{private_key[1]}")
if __name__ == "__main__":
main()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/a1z26.py | ciphers/a1z26.py | """
Convert a string of characters to a sequence of numbers
corresponding to the character's position in the alphabet.
https://www.dcode.fr/letter-number-cipher
http://bestcodes.weebly.com/a1z26.html
"""
from __future__ import annotations
def encode(plain: str) -> list[int]:
"""
>>> encode("myname")
[13, 25, 14, 1, 13, 5]
"""
return [ord(elem) - 96 for elem in plain]
def decode(encoded: list[int]) -> str:
"""
>>> decode([13, 25, 14, 1, 13, 5])
'myname'
"""
return "".join(chr(elem + 96) for elem in encoded)
def main() -> None:
encoded = encode(input("-> ").strip().lower())
print("Encoded: ", encoded)
print("Decoded:", decode(encoded))
if __name__ == "__main__":
main()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/simple_keyword_cypher.py | ciphers/simple_keyword_cypher.py | def remove_duplicates(key: str) -> str:
"""
Removes duplicate alphabetic characters in a keyword (letter is ignored after its
first appearance).
:param key: Keyword to use
:return: String with duplicates removed
>>> remove_duplicates('Hello World!!')
'Helo Wrd'
"""
key_no_dups = ""
for ch in key:
if ch == " " or (ch not in key_no_dups and ch.isalpha()):
key_no_dups += ch
return key_no_dups
def create_cipher_map(key: str) -> dict[str, str]:
"""
Returns a cipher map given a keyword.
:param key: keyword to use
:return: dictionary cipher map
"""
# Create a list of the letters in the alphabet
alphabet = [chr(i + 65) for i in range(26)]
# Remove duplicate characters from key
key = remove_duplicates(key.upper())
offset = len(key)
# First fill cipher with key characters
cipher_alphabet = {alphabet[i]: char for i, char in enumerate(key)}
# Then map remaining characters in alphabet to
# the alphabet from the beginning
for i in range(len(cipher_alphabet), 26):
char = alphabet[i - offset]
# Ensure we are not mapping letters to letters previously mapped
while char in key:
offset -= 1
char = alphabet[i - offset]
cipher_alphabet[alphabet[i]] = char
return cipher_alphabet
def encipher(message: str, cipher_map: dict[str, str]) -> str:
"""
Enciphers a message given a cipher map.
:param message: Message to encipher
:param cipher_map: Cipher map
:return: enciphered string
>>> encipher('Hello World!!', create_cipher_map('Goodbye!!'))
'CYJJM VMQJB!!'
"""
return "".join(cipher_map.get(ch, ch) for ch in message.upper())
def decipher(message: str, cipher_map: dict[str, str]) -> str:
"""
Deciphers a message given a cipher map
:param message: Message to decipher
:param cipher_map: Dictionary mapping to use
:return: Deciphered string
>>> cipher_map = create_cipher_map('Goodbye!!')
>>> decipher(encipher('Hello World!!', cipher_map), cipher_map)
'HELLO WORLD!!'
"""
# Reverse our cipher mappings
rev_cipher_map = {v: k for k, v in cipher_map.items()}
return "".join(rev_cipher_map.get(ch, ch) for ch in message.upper())
def main() -> None:
"""
Handles I/O
:return: void
"""
message = input("Enter message to encode or decode: ").strip()
key = input("Enter keyword: ").strip()
option = input("Encipher or decipher? E/D:").strip()[0].lower()
try:
func = {"e": encipher, "d": decipher}[option]
except KeyError:
raise KeyError("invalid input option")
cipher_map = create_cipher_map(key)
print(func(message, cipher_map))
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/polybius.py | ciphers/polybius.py | #!/usr/bin/env python3
"""
A Polybius Square is a table that allows someone to translate letters into numbers.
https://www.braingle.com/brainteasers/codes/polybius.php
"""
import numpy as np
SQUARE = [
["a", "b", "c", "d", "e"],
["f", "g", "h", "i", "k"],
["l", "m", "n", "o", "p"],
["q", "r", "s", "t", "u"],
["v", "w", "x", "y", "z"],
]
class PolybiusCipher:
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(PolybiusCipher().letter_to_numbers('a'), [1,1])
True
>>> np.array_equal(PolybiusCipher().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
>>> PolybiusCipher().numbers_to_letter(4, 5) == "u"
True
>>> PolybiusCipher().numbers_to_letter(1, 1) == "a"
True
"""
return self.SQUARE[index1 - 1, index2 - 1]
def encode(self, message: str) -> str:
"""
Return the encoded version of message according to the polybius cipher
>>> PolybiusCipher().encode("test message") == "44154344 32154343112215"
True
>>> PolybiusCipher().encode("Test Message") == "44154344 32154343112215"
True
"""
message = message.lower()
message = message.replace("j", "i")
encoded_message = ""
for letter_index in range(len(message)):
if message[letter_index] != " ":
numbers = self.letter_to_numbers(message[letter_index])
encoded_message = encoded_message + str(numbers[0]) + str(numbers[1])
elif message[letter_index] == " ":
encoded_message = encoded_message + " "
return encoded_message
def decode(self, message: str) -> str:
"""
Return the decoded version of message according to the polybius cipher
>>> PolybiusCipher().decode("44154344 32154343112215") == "test message"
True
>>> PolybiusCipher().decode("4415434432154343112215") == "testmessage"
True
"""
message = message.replace(" ", " ")
decoded_message = ""
for numbers_index in range(int(len(message) / 2)):
if message[numbers_index * 2] != " ":
index1 = message[numbers_index * 2]
index2 = message[numbers_index * 2 + 1]
letter = self.numbers_to_letter(int(index1), int(index2))
decoded_message = decoded_message + letter
elif message[numbers_index * 2] == " ":
decoded_message = decoded_message + " "
return decoded_message
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/base85.py | ciphers/base85.py | """
Base85 (Ascii85) encoding and decoding
https://en.wikipedia.org/wiki/Ascii85
"""
def _base10_to_85(d: int) -> str:
return "".join(chr(d % 85 + 33)) + _base10_to_85(d // 85) if d > 0 else ""
def _base85_to_10(digits: list) -> int:
return sum(char * 85**i for i, char in enumerate(reversed(digits)))
def ascii85_encode(data: bytes) -> bytes:
"""
>>> ascii85_encode(b"")
b''
>>> ascii85_encode(b"12345")
b'0etOA2#'
>>> ascii85_encode(b"base 85")
b'@UX=h+?24'
"""
binary_data = "".join(bin(ord(d))[2:].zfill(8) for d in data.decode("utf-8"))
null_values = (32 * ((len(binary_data) // 32) + 1) - len(binary_data)) // 8
binary_data = binary_data.ljust(32 * ((len(binary_data) // 32) + 1), "0")
b85_chunks = [int(_s, 2) for _s in map("".join, zip(*[iter(binary_data)] * 32))]
result = "".join(_base10_to_85(chunk)[::-1] for chunk in b85_chunks)
return bytes(result[:-null_values] if null_values % 4 != 0 else result, "utf-8")
def ascii85_decode(data: bytes) -> bytes:
"""
>>> ascii85_decode(b"")
b''
>>> ascii85_decode(b"0etOA2#")
b'12345'
>>> ascii85_decode(b"@UX=h+?24")
b'base 85'
"""
null_values = 5 * ((len(data) // 5) + 1) - len(data)
binary_data = data.decode("utf-8") + "u" * null_values
b85_chunks = map("".join, zip(*[iter(binary_data)] * 5))
b85_segments = [[ord(_s) - 33 for _s in chunk] for chunk in b85_chunks]
results = [bin(_base85_to_10(chunk))[2::].zfill(32) for chunk in b85_segments]
char_chunks = [
[chr(int(_s, 2)) for _s in map("".join, zip(*[iter(r)] * 8))] for r in results
]
result = "".join("".join(char) for char in char_chunks)
offset = int(null_values % 5 == 0)
return bytes(result[: offset - null_values], "utf-8")
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/transposition_cipher_encrypt_decrypt_file.py | ciphers/transposition_cipher_encrypt_decrypt_file.py | import os
import sys
import time
from . import transposition_cipher as trans_cipher
def main() -> None:
input_file = "./prehistoric_men.txt"
output_file = "./Output.txt"
key = int(input("Enter key: "))
mode = input("Encrypt/Decrypt [e/d]: ")
if not os.path.exists(input_file):
print(f"File {input_file} does not exist. Quitting...")
sys.exit()
if os.path.exists(output_file):
print(f"Overwrite {output_file}? [y/n]")
response = input("> ")
if not response.lower().startswith("y"):
sys.exit()
start_time = time.time()
if mode.lower().startswith("e"):
with open(input_file) as f:
content = f.read()
translated = trans_cipher.encrypt_message(key, content)
elif mode.lower().startswith("d"):
with open(output_file) as f:
content = f.read()
translated = trans_cipher.decrypt_message(key, content)
with open(output_file, "w") as output_obj:
output_obj.write(translated)
total_time = round(time.time() - start_time, 2)
print(("Done (", total_time, "seconds )"))
if __name__ == "__main__":
main()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/base32.py | ciphers/base32.py | """
Base32 encoding and decoding
https://en.wikipedia.org/wiki/Base32
"""
B32_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
def base32_encode(data: bytes) -> bytes:
"""
>>> base32_encode(b"Hello World!")
b'JBSWY3DPEBLW64TMMQQQ===='
>>> base32_encode(b"123456")
b'GEZDGNBVGY======'
>>> base32_encode(b"some long complex string")
b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY='
"""
binary_data = "".join(bin(ord(d))[2:].zfill(8) for d in data.decode("utf-8"))
binary_data = binary_data.ljust(5 * ((len(binary_data) // 5) + 1), "0")
b32_chunks = map("".join, zip(*[iter(binary_data)] * 5))
b32_result = "".join(B32_CHARSET[int(chunk, 2)] for chunk in b32_chunks)
return bytes(b32_result.ljust(8 * ((len(b32_result) // 8) + 1), "="), "utf-8")
def base32_decode(data: bytes) -> bytes:
"""
>>> base32_decode(b'JBSWY3DPEBLW64TMMQQQ====')
b'Hello World!'
>>> base32_decode(b'GEZDGNBVGY======')
b'123456'
>>> base32_decode(b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=')
b'some long complex string'
"""
binary_chunks = "".join(
bin(B32_CHARSET.index(_d))[2:].zfill(5)
for _d in data.decode("utf-8").strip("=")
)
binary_data = list(map("".join, zip(*[iter(binary_chunks)] * 8)))
return bytes("".join([chr(int(_d, 2)) for _d in binary_data]), "utf-8")
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/vernam_cipher.py | ciphers/vernam_cipher.py | def vernam_encrypt(plaintext: str, key: str) -> str:
"""
>>> vernam_encrypt("HELLO","KEY")
'RIJVS'
"""
ciphertext = ""
for i in range(len(plaintext)):
ct = ord(key[i % len(key)]) - 65 + ord(plaintext[i]) - 65
while ct > 25:
ct = ct - 26
ciphertext += chr(65 + ct)
return ciphertext
def vernam_decrypt(ciphertext: str, key: str) -> str:
"""
>>> vernam_decrypt("RIJVS","KEY")
'HELLO'
"""
decrypted_text = ""
for i in range(len(ciphertext)):
ct = ord(ciphertext[i]) - ord(key[i % len(key)])
while ct < 0:
ct = 26 + ct
decrypted_text += chr(65 + ct)
return decrypted_text
if __name__ == "__main__":
from doctest import testmod
testmod()
# Example usage
plaintext = "HELLO"
key = "KEY"
encrypted_text = vernam_encrypt(plaintext, key)
decrypted_text = vernam_decrypt(encrypted_text, key)
print("\n\n")
print("Plaintext:", plaintext)
print("Encrypted:", encrypted_text)
print("Decrypted:", decrypted_text)
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/rail_fence_cipher.py | ciphers/rail_fence_cipher.py | """https://en.wikipedia.org/wiki/Rail_fence_cipher"""
def encrypt(input_string: str, key: int) -> str:
"""
Shuffles the character of a string by placing each of them
in a grid (the height is dependent on the key) in a zigzag
formation and reading it left to right.
>>> encrypt("Hello World", 4)
'HWe olordll'
>>> encrypt("This is a message", 0)
Traceback (most recent call last):
...
ValueError: Height of grid can't be 0 or negative
>>> encrypt(b"This is a byte string", 5)
Traceback (most recent call last):
...
TypeError: sequence item 0: expected str instance, int found
"""
temp_grid: list[list[str]] = [[] for _ in range(key)]
lowest = key - 1
if key <= 0:
raise ValueError("Height of grid can't be 0 or negative")
if key == 1 or len(input_string) <= key:
return input_string
for position, character in enumerate(input_string):
num = position % (lowest * 2) # puts it in bounds
num = min(num, lowest * 2 - num) # creates zigzag pattern
temp_grid[num].append(character)
grid = ["".join(row) for row in temp_grid]
output_string = "".join(grid)
return output_string
def decrypt(input_string: str, key: int) -> str:
"""
Generates a template based on the key and fills it in with
the characters of the input string and then reading it in
a zigzag formation.
>>> decrypt("HWe olordll", 4)
'Hello World'
>>> decrypt("This is a message", -10)
Traceback (most recent call last):
...
ValueError: Height of grid can't be 0 or negative
>>> decrypt("My key is very big", 100)
'My key is very big'
"""
grid = []
lowest = key - 1
if key <= 0:
raise ValueError("Height of grid can't be 0 or negative")
if key == 1:
return input_string
temp_grid: list[list[str]] = [[] for _ in range(key)] # generates template
for position in range(len(input_string)):
num = position % (lowest * 2) # puts it in bounds
num = min(num, lowest * 2 - num) # creates zigzag pattern
temp_grid[num].append("*")
counter = 0
for row in temp_grid: # fills in the characters
splice = input_string[counter : counter + len(row)]
grid.append(list(splice))
counter += len(row)
output_string = "" # reads as zigzag
for position in range(len(input_string)):
num = position % (lowest * 2) # puts it in bounds
num = min(num, lowest * 2 - num) # creates zigzag pattern
output_string += grid[num][0]
grid[num].pop(0)
return output_string
def bruteforce(input_string: str) -> dict[int, str]:
"""Uses decrypt function by guessing every key
>>> bruteforce("HWe olordll")[4]
'Hello World'
"""
results = {}
for key_guess in range(1, len(input_string)): # tries every key
results[key_guess] = decrypt(input_string, key_guess)
return results
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/trifid_cipher.py | ciphers/trifid_cipher.py | """
The trifid cipher uses a table to fractionate each plaintext letter into a trigram,
mixes the constituents of the trigrams, and then applies the table in reverse to turn
these mixed trigrams into ciphertext letters.
https://en.wikipedia.org/wiki/Trifid_cipher
"""
from __future__ import annotations
# fmt: off
TEST_CHARACTER_TO_NUMBER = {
"A": "111", "B": "112", "C": "113", "D": "121", "E": "122", "F": "123", "G": "131",
"H": "132", "I": "133", "J": "211", "K": "212", "L": "213", "M": "221", "N": "222",
"O": "223", "P": "231", "Q": "232", "R": "233", "S": "311", "T": "312", "U": "313",
"V": "321", "W": "322", "X": "323", "Y": "331", "Z": "332", "+": "333",
}
# fmt: off
TEST_NUMBER_TO_CHARACTER = {val: key for key, val in TEST_CHARACTER_TO_NUMBER.items()}
def __encrypt_part(message_part: str, character_to_number: dict[str, str]) -> str:
"""
Arrange the triagram value of each letter of `message_part` vertically and join
them horizontally.
>>> __encrypt_part('ASK', TEST_CHARACTER_TO_NUMBER)
'132111112'
"""
one, two, three = "", "", ""
for each in (character_to_number[character] for character in message_part):
one += each[0]
two += each[1]
three += each[2]
return one + two + three
def __decrypt_part(
message_part: str, character_to_number: dict[str, str]
) -> tuple[str, str, str]:
"""
Convert each letter of the input string into their respective trigram values, join
them and split them into three equal groups of strings which are returned.
>>> __decrypt_part('ABCDE', TEST_CHARACTER_TO_NUMBER)
('11111', '21131', '21122')
"""
this_part = "".join(character_to_number[character] for character in message_part)
result = []
tmp = ""
for digit in this_part:
tmp += digit
if len(tmp) == len(message_part):
result.append(tmp)
tmp = ""
return result[0], result[1], result[2]
def __prepare(
message: str, alphabet: str
) -> tuple[str, str, dict[str, str], dict[str, str]]:
"""
A helper function that generates the triagrams and assigns each letter of the
alphabet to its corresponding triagram and stores this in a dictionary
(`character_to_number` and `number_to_character`) after confirming if the
alphabet's length is ``27``.
>>> test = __prepare('I aM a BOy','abCdeFghijkLmnopqrStuVwxYZ+')
>>> expected = ('IAMABOY','ABCDEFGHIJKLMNOPQRSTUVWXYZ+',
... TEST_CHARACTER_TO_NUMBER, TEST_NUMBER_TO_CHARACTER)
>>> test == expected
True
Testing with incomplete alphabet
>>> __prepare('I aM a BOy','abCdeFghijkLmnopqrStuVw')
Traceback (most recent call last):
...
KeyError: 'Length of alphabet has to be 27.'
Testing with extra long alphabets
>>> __prepare('I aM a BOy','abCdeFghijkLmnopqrStuVwxyzzwwtyyujjgfd')
Traceback (most recent call last):
...
KeyError: 'Length of alphabet has to be 27.'
Testing with punctuation not in the given alphabet
>>> __prepare('am i a boy?','abCdeFghijkLmnopqrStuVwxYZ+')
Traceback (most recent call last):
...
ValueError: Each message character has to be included in alphabet!
Testing with numbers
>>> __prepare(500,'abCdeFghijkLmnopqrStuVwxYZ+')
Traceback (most recent call last):
...
AttributeError: 'int' object has no attribute 'replace'
"""
# Validate message and alphabet, set to upper and remove spaces
alphabet = alphabet.replace(" ", "").upper()
message = message.replace(" ", "").upper()
# Check length and characters
if len(alphabet) != 27:
raise KeyError("Length of alphabet has to be 27.")
if any(char not in alphabet for char in message):
raise ValueError("Each message character has to be included in alphabet!")
# Generate dictionares
character_to_number = dict(zip(alphabet, TEST_CHARACTER_TO_NUMBER.values()))
number_to_character = {
number: letter for letter, number in character_to_number.items()
}
return message, alphabet, character_to_number, number_to_character
def encrypt_message(
message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period: int = 5
) -> str:
"""
encrypt_message
===============
Encrypts a message using the trifid_cipher. Any punctuatuion chars that
would be used should be added to the alphabet.
PARAMETERS
----------
* `message`: The message you want to encrypt.
* `alphabet` (optional): The characters to be used for the cipher .
* `period` (optional): The number of characters you want in a group whilst
encrypting.
>>> encrypt_message('I am a boy')
'BCDGBQY'
>>> encrypt_message(' ')
''
>>> encrypt_message(' aide toi le c iel ta id era ',
... 'FELIXMARDSTBCGHJKNOPQUVWYZ+',5)
'FMJFVOISSUFTFPUFEQQC'
"""
message, alphabet, character_to_number, number_to_character = __prepare(
message, alphabet
)
encrypted_numeric = ""
for i in range(0, len(message) + 1, period):
encrypted_numeric += __encrypt_part(
message[i : i + period], character_to_number
)
encrypted = ""
for i in range(0, len(encrypted_numeric), 3):
encrypted += number_to_character[encrypted_numeric[i : i + 3]]
return encrypted
def decrypt_message(
message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period: int = 5
) -> str:
"""
decrypt_message
===============
Decrypts a trifid_cipher encrypted message.
PARAMETERS
----------
* `message`: The message you want to decrypt.
* `alphabet` (optional): The characters used for the cipher.
* `period` (optional): The number of characters used in grouping when it
was encrypted.
>>> decrypt_message('BCDGBQY')
'IAMABOY'
Decrypting with your own alphabet and period
>>> decrypt_message('FMJFVOISSUFTFPUFEQQC','FELIXMARDSTBCGHJKNOPQUVWYZ+',5)
'AIDETOILECIELTAIDERA'
"""
message, alphabet, character_to_number, number_to_character = __prepare(
message, alphabet
)
decrypted_numeric = []
for i in range(0, len(message), period):
a, b, c = __decrypt_part(message[i : i + period], character_to_number)
for j in range(len(a)):
decrypted_numeric.append(a[j] + b[j] + c[j])
return "".join(number_to_character[each] for each in decrypted_numeric)
if __name__ == "__main__":
import doctest
doctest.testmod()
msg = "DEFEND THE EAST WALL OF THE CASTLE."
encrypted = encrypt_message(msg, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ")
decrypted = decrypt_message(encrypted, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ")
print(f"Encrypted: {encrypted}\nDecrypted: {decrypted}")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/xor_cipher.py | ciphers/xor_cipher.py | """
author: Christian Bender
date: 21.12.2017
class: XORCipher
This class implements the XOR-cipher algorithm and provides
some useful methods for encrypting and decrypting strings and
files.
Overview about methods
- encrypt : list of char
- decrypt : list of char
- encrypt_string : str
- decrypt_string : str
- encrypt_file : boolean
- decrypt_file : boolean
"""
from __future__ import annotations
class XORCipher:
def __init__(self, key: int = 0):
"""
simple constructor that receives a key or uses
default key = 0
"""
# private field
self.__key = key
def encrypt(self, content: str, key: int) -> list[str]:
"""
input: 'content' of type string and 'key' of type int
output: encrypted string 'content' as a list of chars
if key not passed the method uses the key by the constructor.
otherwise key = 1
Empty list
>>> XORCipher().encrypt("", 5)
[]
One key
>>> XORCipher().encrypt("hallo welt", 1)
['i', '`', 'm', 'm', 'n', '!', 'v', 'd', 'm', 'u']
Normal key
>>> XORCipher().encrypt("HALLO WELT", 32)
['h', 'a', 'l', 'l', 'o', '\\x00', 'w', 'e', 'l', 't']
Key greater than 255
>>> XORCipher().encrypt("hallo welt", 256)
['h', 'a', 'l', 'l', 'o', ' ', 'w', 'e', 'l', 't']
"""
# precondition
assert isinstance(key, int)
assert isinstance(content, str)
key = key or self.__key or 1
# make sure key is an appropriate size
key %= 256
return [chr(ord(ch) ^ key) for ch in content]
def decrypt(self, content: str, key: int) -> list[str]:
"""
input: 'content' of type list and 'key' of type int
output: decrypted string 'content' as a list of chars
if key not passed the method uses the key by the constructor.
otherwise key = 1
Empty list
>>> XORCipher().decrypt("", 5)
[]
One key
>>> XORCipher().decrypt("hallo welt", 1)
['i', '`', 'm', 'm', 'n', '!', 'v', 'd', 'm', 'u']
Normal key
>>> XORCipher().decrypt("HALLO WELT", 32)
['h', 'a', 'l', 'l', 'o', '\\x00', 'w', 'e', 'l', 't']
Key greater than 255
>>> XORCipher().decrypt("hallo welt", 256)
['h', 'a', 'l', 'l', 'o', ' ', 'w', 'e', 'l', 't']
"""
# precondition
assert isinstance(key, int)
assert isinstance(content, str)
key = key or self.__key or 1
# make sure key is an appropriate size
key %= 256
return [chr(ord(ch) ^ key) for ch in content]
def encrypt_string(self, content: str, key: int = 0) -> str:
"""
input: 'content' of type string and 'key' of type int
output: encrypted string 'content'
if key not passed the method uses the key by the constructor.
otherwise key = 1
Empty list
>>> XORCipher().encrypt_string("", 5)
''
One key
>>> XORCipher().encrypt_string("hallo welt", 1)
'i`mmn!vdmu'
Normal key
>>> XORCipher().encrypt_string("HALLO WELT", 32)
'hallo\\x00welt'
Key greater than 255
>>> XORCipher().encrypt_string("hallo welt", 256)
'hallo welt'
"""
# precondition
assert isinstance(key, int)
assert isinstance(content, str)
key = key or self.__key or 1
# make sure key is an appropriate size
key %= 256
# This will be returned
ans = ""
for ch in content:
ans += chr(ord(ch) ^ key)
return ans
def decrypt_string(self, content: str, key: int = 0) -> str:
"""
input: 'content' of type string and 'key' of type int
output: decrypted string 'content'
if key not passed the method uses the key by the constructor.
otherwise key = 1
Empty list
>>> XORCipher().decrypt_string("", 5)
''
One key
>>> XORCipher().decrypt_string("hallo welt", 1)
'i`mmn!vdmu'
Normal key
>>> XORCipher().decrypt_string("HALLO WELT", 32)
'hallo\\x00welt'
Key greater than 255
>>> XORCipher().decrypt_string("hallo welt", 256)
'hallo welt'
"""
# precondition
assert isinstance(key, int)
assert isinstance(content, str)
key = key or self.__key or 1
# make sure key is an appropriate size
key %= 256
# This will be returned
ans = ""
for ch in content:
ans += chr(ord(ch) ^ key)
return ans
def encrypt_file(self, file: str, key: int = 0) -> bool:
"""
input: filename (str) and a key (int)
output: returns true if encrypt process was
successful otherwise false
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
# precondition
assert isinstance(file, str)
assert isinstance(key, int)
# make sure key is an appropriate size
key %= 256
try:
with open(file) as fin, open("encrypt.out", "w+") as fout:
# actual encrypt-process
for line in fin:
fout.write(self.encrypt_string(line, key))
except OSError:
return False
return True
def decrypt_file(self, file: str, key: int) -> bool:
"""
input: filename (str) and a key (int)
output: returns true if decrypt process was
successful otherwise false
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
# precondition
assert isinstance(file, str)
assert isinstance(key, int)
# make sure key is an appropriate size
key %= 256
try:
with open(file) as fin, open("decrypt.out", "w+") as fout:
# actual encrypt-process
for line in fin:
fout.write(self.decrypt_string(line, key))
except OSError:
return False
return True
if __name__ == "__main__":
from doctest import testmod
testmod()
# Tests
# crypt = XORCipher()
# key = 67
# # test encrypt
# print(crypt.encrypt("hallo welt",key))
# # test decrypt
# print(crypt.decrypt(crypt.encrypt("hallo welt",key), key))
# # test encrypt_string
# print(crypt.encrypt_string("hallo welt",key))
# # test decrypt_string
# print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key))
# if (crypt.encrypt_file("test.txt",key)):
# print("encrypt successful")
# else:
# print("encrypt unsuccessful")
# if (crypt.decrypt_file("encrypt.out",key)):
# print("decrypt successful")
# else:
# print("decrypt unsuccessful")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/base64_cipher.py | ciphers/base64_cipher.py | B64_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
def base64_encode(data: bytes) -> bytes:
"""Encodes data according to RFC4648.
The data is first transformed to binary and appended with binary digits so that its
length becomes a multiple of 6, then each 6 binary digits will match a character in
the B64_CHARSET string. The number of appended binary digits would later determine
how many "=" signs should be added, the padding.
For every 2 binary digits added, a "=" sign is added in the output.
We can add any binary digits to make it a multiple of 6, for instance, consider the
following example:
"AA" -> 0010100100101001 -> 001010 010010 1001
As can be seen above, 2 more binary digits should be added, so there's 4
possibilities here: 00, 01, 10 or 11.
That being said, Base64 encoding can be used in Steganography to hide data in these
appended digits.
>>> from base64 import b64encode
>>> a = b"This pull request is part of Hacktoberfest20!"
>>> b = b"https://tools.ietf.org/html/rfc4648"
>>> c = b"A"
>>> base64_encode(a) == b64encode(a)
True
>>> base64_encode(b) == b64encode(b)
True
>>> base64_encode(c) == b64encode(c)
True
>>> base64_encode("abc")
Traceback (most recent call last):
...
TypeError: a bytes-like object is required, not 'str'
"""
# Make sure the supplied data is a bytes-like object
if not isinstance(data, bytes):
msg = f"a bytes-like object is required, not '{data.__class__.__name__}'"
raise TypeError(msg)
binary_stream = "".join(bin(byte)[2:].zfill(8) for byte in data)
padding_needed = len(binary_stream) % 6 != 0
if padding_needed:
# The padding that will be added later
padding = b"=" * ((6 - len(binary_stream) % 6) // 2)
# Append binary_stream with arbitrary binary digits (0's by default) to make its
# length a multiple of 6.
binary_stream += "0" * (6 - len(binary_stream) % 6)
else:
padding = b""
# Encode every 6 binary digits to their corresponding Base64 character
return (
"".join(
B64_CHARSET[int(binary_stream[index : index + 6], 2)]
for index in range(0, len(binary_stream), 6)
).encode()
+ padding
)
def base64_decode(encoded_data: str) -> bytes:
"""Decodes data according to RFC4648.
This does the reverse operation of base64_encode.
We first transform the encoded data back to a binary stream, take off the
previously appended binary digits according to the padding, at this point we
would have a binary stream whose length is multiple of 8, the last step is
to convert every 8 bits to a byte.
>>> from base64 import b64decode
>>> a = "VGhpcyBwdWxsIHJlcXVlc3QgaXMgcGFydCBvZiBIYWNrdG9iZXJmZXN0MjAh"
>>> b = "aHR0cHM6Ly90b29scy5pZXRmLm9yZy9odG1sL3JmYzQ2NDg="
>>> c = "QQ=="
>>> base64_decode(a) == b64decode(a)
True
>>> base64_decode(b) == b64decode(b)
True
>>> base64_decode(c) == b64decode(c)
True
>>> base64_decode("abc")
Traceback (most recent call last):
...
AssertionError: Incorrect padding
"""
# Make sure encoded_data is either a string or a bytes-like object
if not isinstance(encoded_data, bytes) and not isinstance(encoded_data, str):
msg = (
"argument should be a bytes-like object or ASCII string, "
f"not '{encoded_data.__class__.__name__}'"
)
raise TypeError(msg)
# In case encoded_data is a bytes-like object, make sure it contains only
# ASCII characters so we convert it to a string object
if isinstance(encoded_data, bytes):
try:
encoded_data = encoded_data.decode("utf-8")
except UnicodeDecodeError:
raise ValueError("base64 encoded data should only contain ASCII characters")
padding = encoded_data.count("=")
# Check if the encoded string contains non base64 characters
if padding:
assert all(char in B64_CHARSET for char in encoded_data[:-padding]), (
"Invalid base64 character(s) found."
)
else:
assert all(char in B64_CHARSET for char in encoded_data), (
"Invalid base64 character(s) found."
)
# Check the padding
assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding"
if padding:
# Remove padding if there is one
encoded_data = encoded_data[:-padding]
binary_stream = "".join(
bin(B64_CHARSET.index(char))[2:].zfill(6) for char in encoded_data
)[: -padding * 2]
else:
binary_stream = "".join(
bin(B64_CHARSET.index(char))[2:].zfill(6) for char in encoded_data
)
data = [
int(binary_stream[index : index + 8], 2)
for index in range(0, len(binary_stream), 8)
]
return bytes(data)
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/fractionated_morse_cipher.py | ciphers/fractionated_morse_cipher.py | """
Python program for the Fractionated Morse Cipher.
The Fractionated Morse cipher first converts the plaintext to Morse code,
then enciphers fixed-size blocks of Morse code back to letters.
This procedure means plaintext letters are mixed into the ciphertext letters,
making it more secure than substitution ciphers.
http://practicalcryptography.com/ciphers/fractionated-morse-cipher/
"""
import string
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": "--..",
" ": "",
}
# Define possible trigrams of Morse code
MORSE_COMBINATIONS = [
"...",
"..-",
"..x",
".-.",
".--",
".-x",
".x.",
".x-",
".xx",
"-..",
"-.-",
"-.x",
"--.",
"---",
"--x",
"-x.",
"-x-",
"-xx",
"x..",
"x.-",
"x.x",
"x-.",
"x--",
"x-x",
"xx.",
"xx-",
"xxx",
]
# Create a reverse dictionary for Morse code
REVERSE_DICT = {value: key for key, value in MORSE_CODE_DICT.items()}
def encode_to_morse(plaintext: str) -> str:
"""Encode a plaintext message into Morse code.
Args:
plaintext: The plaintext message to encode.
Returns:
The Morse code representation of the plaintext message.
Example:
>>> encode_to_morse("defend the east")
'-..x.x..-.x.x-.x-..xx-x....x.xx.x.-x...x-'
"""
return "x".join([MORSE_CODE_DICT.get(letter.upper(), "") for letter in plaintext])
def encrypt_fractionated_morse(plaintext: str, key: str) -> str:
"""Encrypt a plaintext message using Fractionated Morse Cipher.
Args:
plaintext: The plaintext message to encrypt.
key: The encryption key.
Returns:
The encrypted ciphertext.
Example:
>>> encrypt_fractionated_morse("defend the east","Roundtable")
'ESOAVVLJRSSTRX'
"""
morse_code = encode_to_morse(plaintext)
key = key.upper() + string.ascii_uppercase
key = "".join(sorted(set(key), key=key.find))
# Ensure morse_code length is a multiple of 3
padding_length = 3 - (len(morse_code) % 3)
morse_code += "x" * padding_length
fractionated_morse_dict = {v: k for k, v in zip(key, MORSE_COMBINATIONS)}
fractionated_morse_dict["xxx"] = ""
encrypted_text = "".join(
[
fractionated_morse_dict[morse_code[i : i + 3]]
for i in range(0, len(morse_code), 3)
]
)
return encrypted_text
def decrypt_fractionated_morse(ciphertext: str, key: str) -> str:
"""Decrypt a ciphertext message encrypted with Fractionated Morse Cipher.
Args:
ciphertext: The ciphertext message to decrypt.
key: The decryption key.
Returns:
The decrypted plaintext message.
Example:
>>> decrypt_fractionated_morse("ESOAVVLJRSSTRX","Roundtable")
'DEFEND THE EAST'
"""
key = key.upper() + string.ascii_uppercase
key = "".join(sorted(set(key), key=key.find))
inverse_fractionated_morse_dict = dict(zip(key, MORSE_COMBINATIONS))
morse_code = "".join(
[inverse_fractionated_morse_dict.get(letter, "") for letter in ciphertext]
)
decrypted_text = "".join(
[REVERSE_DICT[code] for code in morse_code.split("x")]
).strip()
return decrypted_text
if __name__ == "__main__":
"""
Example usage of Fractionated Morse Cipher.
"""
plaintext = "defend the east"
print("Plain Text:", plaintext)
key = "ROUNDTABLE"
ciphertext = encrypt_fractionated_morse(plaintext, key)
print("Encrypted:", ciphertext)
decrypted_text = decrypt_fractionated_morse(ciphertext, key)
print("Decrypted:", decrypted_text)
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/mono_alphabetic_ciphers.py | ciphers/mono_alphabetic_ciphers.py | from typing import Literal
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def translate_message(
key: str, message: str, mode: Literal["encrypt", "decrypt"]
) -> str:
"""
>>> translate_message("QWERTYUIOPASDFGHJKLZXCVBNM","Hello World","encrypt")
'Pcssi Bidsm'
"""
chars_a = LETTERS if mode == "decrypt" else key
chars_b = key if mode == "decrypt" else LETTERS
translated = ""
# loop through each symbol in the message
for symbol in message:
if symbol.upper() in chars_a:
# encrypt/decrypt the symbol
sym_index = chars_a.find(symbol.upper())
if symbol.isupper():
translated += chars_b[sym_index].upper()
else:
translated += chars_b[sym_index].lower()
else:
# symbol is not in LETTERS, just add it
translated += symbol
return translated
def encrypt_message(key: str, message: str) -> str:
"""
>>> encrypt_message("QWERTYUIOPASDFGHJKLZXCVBNM", "Hello World")
'Pcssi Bidsm'
"""
return translate_message(key, message, "encrypt")
def decrypt_message(key: str, message: str) -> str:
"""
>>> decrypt_message("QWERTYUIOPASDFGHJKLZXCVBNM", "Hello World")
'Itssg Vgksr'
"""
return translate_message(key, message, "decrypt")
def main() -> None:
message = "Hello World"
key = "QWERTYUIOPASDFGHJKLZXCVBNM"
mode = "decrypt" # set to 'encrypt' or 'decrypt'
if mode == "encrypt":
translated = encrypt_message(key, message)
elif mode == "decrypt":
translated = decrypt_message(key, message)
print(f"Using the key {key}, the {mode}ed message is: {translated}")
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/diffie_hellman.py | ciphers/diffie_hellman.py | from binascii import hexlify
from hashlib import sha256
from os import urandom
# RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for
# Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526
primes = {
# 1536-bit
5: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 2048-bit
14: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
"DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
"15728E5A8AACAA68FFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 3072-bit
15: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
"DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
"15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
"ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
"ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
"F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
"43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 4096-bit
16: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
"DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
"15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
"ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
"ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
"F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
"43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7"
"88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA"
"2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6"
"287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED"
"1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9"
"93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199"
"FFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 6144-bit
17: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
"8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
"302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
"A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
"49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8"
"FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C"
"180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718"
"3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D"
"04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D"
"B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226"
"1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC"
"E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26"
"99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB"
"04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2"
"233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127"
"D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492"
"36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406"
"AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918"
"DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151"
"2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03"
"F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F"
"BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA"
"CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B"
"B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632"
"387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E"
"6DCC4024FFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
# 8192-bit
18: {
"prime": int(
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
"29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
"83655D23DCA3AD961C62F356208552BB9ED529077096966D"
"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
"DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
"15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
"ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
"ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
"F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
"43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7"
"88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA"
"2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6"
"287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED"
"1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9"
"93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492"
"36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD"
"F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831"
"179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B"
"DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF"
"5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6"
"D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3"
"23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA"
"CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328"
"06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C"
"DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE"
"12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4"
"38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300"
"741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568"
"3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9"
"22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B"
"4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A"
"062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36"
"4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1"
"B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92"
"4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47"
"9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71"
"60C980DD98EDD3DFFFFFFFFFFFFFFFFF",
base=16,
),
"generator": 2,
},
}
class DiffieHellman:
"""
Class to represent the Diffie-Hellman key exchange protocol
>>> alice = DiffieHellman()
>>> bob = DiffieHellman()
>>> alice_private = alice.get_private_key()
>>> alice_public = alice.generate_public_key()
>>> bob_private = bob.get_private_key()
>>> bob_public = bob.generate_public_key()
>>> # generating shared key using the DH object
>>> alice_shared = alice.generate_shared_key(bob_public)
>>> bob_shared = bob.generate_shared_key(alice_public)
>>> assert alice_shared == bob_shared
>>> # generating shared key using static methods
>>> alice_shared = DiffieHellman.generate_shared_key_static(
... alice_private, bob_public
... )
>>> bob_shared = DiffieHellman.generate_shared_key_static(
... bob_private, alice_public
... )
>>> assert alice_shared == bob_shared
"""
# Current minimum recommendation is 2048 bit (group 14)
def __init__(self, group: int = 14) -> None:
if group not in primes:
raise ValueError("Unsupported Group")
self.prime = primes[group]["prime"]
self.generator = primes[group]["generator"]
self.__private_key = int(hexlify(urandom(32)), base=16)
def get_private_key(self) -> str:
return hex(self.__private_key)[2:]
def generate_public_key(self) -> str:
public_key = pow(self.generator, self.__private_key, self.prime)
return hex(public_key)[2:]
def is_valid_public_key(self, key: int) -> bool:
# check if the other public key is valid based on NIST SP800-56
return (
2 <= key <= self.prime - 2
and pow(key, (self.prime - 1) // 2, self.prime) == 1
)
def generate_shared_key(self, other_key_str: str) -> str:
other_key = int(other_key_str, base=16)
if not self.is_valid_public_key(other_key):
raise ValueError("Invalid public key")
shared_key = pow(other_key, self.__private_key, self.prime)
return sha256(str(shared_key).encode()).hexdigest()
@staticmethod
def is_valid_public_key_static(remote_public_key_str: int, prime: int) -> bool:
# check if the other public key is valid based on NIST SP800-56
return (
2 <= remote_public_key_str <= prime - 2
and pow(remote_public_key_str, (prime - 1) // 2, prime) == 1
)
@staticmethod
def generate_shared_key_static(
local_private_key_str: str, remote_public_key_str: str, group: int = 14
) -> str:
local_private_key = int(local_private_key_str, base=16)
remote_public_key = int(remote_public_key_str, base=16)
prime = primes[group]["prime"]
if not DiffieHellman.is_valid_public_key_static(remote_public_key, prime):
raise ValueError("Invalid public key")
shared_key = pow(remote_public_key, local_private_key, prime)
return sha256(str(shared_key).encode()).hexdigest()
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/diffie.py | ciphers/diffie.py | from __future__ import annotations
def find_primitive(modulus: int) -> int | None:
"""
Find a primitive root modulo modulus, if one exists.
Args:
modulus : The modulus for which to find a primitive root.
Returns:
The primitive root if one exists, or None if there is none.
Examples:
>>> find_primitive(7) # Modulo 7 has primitive root 3
3
>>> find_primitive(11) # Modulo 11 has primitive root 2
2
>>> find_primitive(8) == None # Modulo 8 has no primitive root
True
"""
for r in range(1, modulus):
li = []
for x in range(modulus - 1):
val = pow(r, x, modulus)
if val in li:
break
li.append(val)
else:
return r
return None
if __name__ == "__main__":
import doctest
doctest.testmod()
prime = int(input("Enter a prime number q: "))
primitive_root = find_primitive(prime)
if primitive_root is None:
print(f"Cannot find the primitive for the value: {primitive_root!r}")
else:
a_private = int(input("Enter private key of A: "))
a_public = pow(primitive_root, a_private, prime)
b_private = int(input("Enter private key of B: "))
b_public = pow(primitive_root, b_private, prime)
a_secret = pow(b_public, a_private, prime)
b_secret = pow(a_public, b_private, prime)
print("The key value generated by A is: ", a_secret)
print("The key value generated by B is: ", b_secret)
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/affine_cipher.py | ciphers/affine_cipher.py | import random
import sys
from maths.greatest_common_divisor import gcd_by_iterative
from . import cryptomath_module as cryptomath
SYMBOLS = (
r""" !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`"""
r"""abcdefghijklmnopqrstuvwxyz{|}~"""
)
def check_keys(key_a: int, key_b: int, mode: str) -> None:
if mode == "encrypt":
if key_a == 1:
sys.exit(
"The affine cipher becomes weak when key "
"A is set to 1. Choose different key"
)
if key_b == 0:
sys.exit(
"The affine cipher becomes weak when key "
"B is set to 0. Choose different key"
)
if key_a < 0 or key_b < 0 or key_b > len(SYMBOLS) - 1:
sys.exit(
"Key A must be greater than 0 and key B must "
f"be between 0 and {len(SYMBOLS) - 1}."
)
if gcd_by_iterative(key_a, len(SYMBOLS)) != 1:
sys.exit(
f"Key A {key_a} and the symbol set size {len(SYMBOLS)} "
"are not relatively prime. Choose a different key."
)
def encrypt_message(key: int, message: str) -> str:
"""
>>> encrypt_message(4545, 'The affine cipher is a type of monoalphabetic '
... 'substitution cipher.')
'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF{xIp~{HL}Gi'
"""
key_a, key_b = divmod(key, len(SYMBOLS))
check_keys(key_a, key_b, "encrypt")
cipher_text = ""
for symbol in message:
if symbol in SYMBOLS:
sym_index = SYMBOLS.find(symbol)
cipher_text += SYMBOLS[(sym_index * key_a + key_b) % len(SYMBOLS)]
else:
cipher_text += symbol
return cipher_text
def decrypt_message(key: int, message: str) -> str:
"""
>>> decrypt_message(4545, 'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF'
... '{xIp~{HL}Gi')
'The affine cipher is a type of monoalphabetic substitution cipher.'
"""
key_a, key_b = divmod(key, len(SYMBOLS))
check_keys(key_a, key_b, "decrypt")
plain_text = ""
mod_inverse_of_key_a = cryptomath.find_mod_inverse(key_a, len(SYMBOLS))
for symbol in message:
if symbol in SYMBOLS:
sym_index = SYMBOLS.find(symbol)
plain_text += SYMBOLS[
(sym_index - key_b) * mod_inverse_of_key_a % len(SYMBOLS)
]
else:
plain_text += symbol
return plain_text
def get_random_key() -> int:
while True:
key_b = random.randint(2, len(SYMBOLS))
key_b = random.randint(2, len(SYMBOLS))
if gcd_by_iterative(key_b, len(SYMBOLS)) == 1 and key_b % len(SYMBOLS) != 0:
return key_b * len(SYMBOLS) + key_b
def main() -> None:
"""
>>> key = get_random_key()
>>> msg = "This is a test!"
>>> decrypt_message(key, encrypt_message(key, msg)) == msg
True
"""
message = input("Enter message: ").strip()
key = int(input("Enter key [2000 - 9000]: ").strip())
mode = input("Encrypt/Decrypt [E/D]: ").strip().lower()
if mode.startswith("e"):
mode = "encrypt"
translated = encrypt_message(key, message)
elif mode.startswith("d"):
mode = "decrypt"
translated = decrypt_message(key, message)
print(f"\n{mode.title()}ed text: \n{translated}")
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/vigenere_cipher.py | ciphers/vigenere_cipher.py | LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def main() -> None:
message = input("Enter message: ")
key = input("Enter key [alphanumeric]: ")
mode = input("Encrypt/Decrypt [e/d]: ")
if mode.lower().startswith("e"):
mode = "encrypt"
translated = encrypt_message(key, message)
elif mode.lower().startswith("d"):
mode = "decrypt"
translated = decrypt_message(key, message)
print(f"\n{mode.title()}ed message:")
print(translated)
def encrypt_message(key: str, message: str) -> str:
"""
>>> encrypt_message('HDarji', 'This is Harshil Darji from Dharmaj.')
'Akij ra Odrjqqs Gaisq muod Mphumrs.'
"""
return translate_message(key, message, "encrypt")
def decrypt_message(key: str, message: str) -> str:
"""
>>> decrypt_message('HDarji', 'Akij ra Odrjqqs Gaisq muod Mphumrs.')
'This is Harshil Darji from Dharmaj.'
"""
return translate_message(key, message, "decrypt")
def translate_message(key: str, message: str, mode: str) -> str:
translated = []
key_index = 0
key = key.upper()
for symbol in message:
num = LETTERS.find(symbol.upper())
if num != -1:
if mode == "encrypt":
num += LETTERS.find(key[key_index])
elif mode == "decrypt":
num -= LETTERS.find(key[key_index])
num %= len(LETTERS)
if symbol.isupper():
translated.append(LETTERS[num])
elif symbol.islower():
translated.append(LETTERS[num].lower())
key_index += 1
if key_index == len(key):
key_index = 0
else:
translated.append(symbol)
return "".join(translated)
if __name__ == "__main__":
main()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/permutation_cipher.py | ciphers/permutation_cipher.py | """
The permutation cipher, also called the transposition cipher, is a simple encryption
technique that rearranges the characters in a message based on a secret key. It
divides the message into blocks and applies a permutation to the characters within
each block according to the key. The key is a sequence of unique integers that
determine the order of character rearrangement.
For more info: https://www.nku.edu/~christensen/1402%20permutation%20ciphers.pdf
"""
import random
def generate_valid_block_size(message_length: int) -> int:
"""
Generate a valid block size that is a factor of the message length.
Args:
message_length (int): The length of the message.
Returns:
int: A valid block size.
Example:
>>> random.seed(1)
>>> generate_valid_block_size(12)
3
"""
block_sizes = [
block_size
for block_size in range(2, message_length + 1)
if message_length % block_size == 0
]
return random.choice(block_sizes)
def generate_permutation_key(block_size: int) -> list[int]:
"""
Generate a random permutation key of a specified block size.
Args:
block_size (int): The size of each permutation block.
Returns:
list[int]: A list containing a random permutation of digits.
Example:
>>> random.seed(0)
>>> generate_permutation_key(4)
[2, 0, 1, 3]
"""
digits = list(range(block_size))
random.shuffle(digits)
return digits
def encrypt(
message: str, key: list[int] | None = None, block_size: int | None = None
) -> tuple[str, list[int]]:
"""
Encrypt a message using a permutation cipher with block rearrangement using a key.
Args:
message (str): The plaintext message to be encrypted.
key (list[int]): The permutation key for decryption.
block_size (int): The size of each permutation block.
Returns:
tuple: A tuple containing the encrypted message and the encryption key.
Example:
>>> encrypted_message, key = encrypt("HELLO WORLD")
>>> decrypted_message = decrypt(encrypted_message, key)
>>> decrypted_message
'HELLO WORLD'
"""
message = message.upper()
message_length = len(message)
if key is None or block_size is None:
block_size = generate_valid_block_size(message_length)
key = generate_permutation_key(block_size)
encrypted_message = ""
for i in range(0, message_length, block_size):
block = message[i : i + block_size]
rearranged_block = [block[digit] for digit in key]
encrypted_message += "".join(rearranged_block)
return encrypted_message, key
def decrypt(encrypted_message: str, key: list[int]) -> str:
"""
Decrypt an encrypted message using a permutation cipher with block rearrangement.
Args:
encrypted_message (str): The encrypted message.
key (list[int]): The permutation key for decryption.
Returns:
str: The decrypted plaintext message.
Example:
>>> encrypted_message, key = encrypt("HELLO WORLD")
>>> decrypted_message = decrypt(encrypted_message, key)
>>> decrypted_message
'HELLO WORLD'
"""
key_length = len(key)
decrypted_message = ""
for i in range(0, len(encrypted_message), key_length):
block = encrypted_message[i : i + key_length]
original_block = [""] * key_length
for j, digit in enumerate(key):
original_block[digit] = block[j]
decrypted_message += "".join(original_block)
return decrypted_message
def main() -> None:
"""
Driver function to pass message to get encrypted, then decrypted.
Example:
>>> main()
Decrypted message: HELLO WORLD
"""
message = "HELLO WORLD"
encrypted_message, key = encrypt(message)
decrypted_message = decrypt(encrypted_message, key)
print(f"Decrypted message: {decrypted_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/simple_substitution_cipher.py | ciphers/simple_substitution_cipher.py | import random
import sys
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def main() -> None:
message = input("Enter message: ")
key = "LFWOAYUISVKMNXPBDCRJTQEGHZ"
resp = input("Encrypt/Decrypt [e/d]: ")
check_valid_key(key)
if resp.lower().startswith("e"):
mode = "encrypt"
translated = encrypt_message(key, message)
elif resp.lower().startswith("d"):
mode = "decrypt"
translated = decrypt_message(key, message)
print(f"\n{mode.title()}ion: \n{translated}")
def check_valid_key(key: str) -> None:
key_list = list(key)
letters_list = list(LETTERS)
key_list.sort()
letters_list.sort()
if key_list != letters_list:
sys.exit("Error in the key or symbol set.")
def encrypt_message(key: str, message: str) -> str:
"""
>>> encrypt_message('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji')
'Ilcrism Olcvs'
"""
return translate_message(key, message, "encrypt")
def decrypt_message(key: str, message: str) -> str:
"""
>>> decrypt_message('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs')
'Harshil Darji'
"""
return translate_message(key, message, "decrypt")
def translate_message(key: str, message: str, mode: str) -> str:
translated = ""
chars_a = LETTERS
chars_b = key
if mode == "decrypt":
chars_a, chars_b = chars_b, chars_a
for symbol in message:
if symbol.upper() in chars_a:
sym_index = chars_a.find(symbol.upper())
if symbol.isupper():
translated += chars_b[sym_index].upper()
else:
translated += chars_b[sym_index].lower()
else:
translated += symbol
return translated
def get_random_key() -> str:
key = list(LETTERS)
random.shuffle(key)
return "".join(key)
if __name__ == "__main__":
main()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/rsa_factorization.py | ciphers/rsa_factorization.py | """
An RSA prime factor algorithm.
The program can efficiently factor RSA prime number given the private key d and
public key e.
| Source: on page ``3`` of https://crypto.stanford.edu/~dabo/papers/RSA-survey.pdf
| More readable source: https://www.di-mgt.com.au/rsa_factorize_n.html
large number can take minutes to factor, therefore are not included in doctest.
"""
from __future__ import annotations
import math
import random
def rsafactor(d: int, e: int, n: int) -> list[int]:
"""
This function returns the factors of N, where p*q=N
Return: [p, q]
We call N the RSA modulus, e the encryption exponent, and d the decryption exponent.
The pair (N, e) is the public key. As its name suggests, it is public and is used to
encrypt messages.
The pair (N, d) is the secret key or private key and is known only to the recipient
of encrypted messages.
>>> rsafactor(3, 16971, 25777)
[149, 173]
>>> rsafactor(7331, 11, 27233)
[113, 241]
>>> rsafactor(4021, 13, 17711)
[89, 199]
"""
k = d * e - 1
p = 0
q = 0
while p == 0:
g = random.randint(2, n - 1)
t = k
while True:
if t % 2 == 0:
t = t // 2
x = (g**t) % n
y = math.gcd(x - 1, n)
if x > 1 and y > 1:
p = y
q = n // y
break # find the correct factors
else:
break # t is not divisible by 2, break and choose another g
return sorted([p, q])
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/autokey.py | ciphers/autokey.py | """
https://en.wikipedia.org/wiki/Autokey_cipher
An autokey cipher (also known as the autoclave cipher) is a cipher that
incorporates the message (the plaintext) into the key.
The key is generated from the message in some automated fashion,
sometimes by selecting certain letters from the text or, more commonly,
by adding a short primer key to the front of the message.
"""
def encrypt(plaintext: str, key: str) -> str:
"""
Encrypt a given `plaintext` (string) and `key` (string), returning the
encrypted ciphertext.
>>> encrypt("hello world", "coffee")
'jsqqs avvwo'
>>> encrypt("coffee is good as python", "TheAlgorithms")
'vvjfpk wj ohvp su ddylsv'
>>> encrypt("coffee is good as python", 2)
Traceback (most recent call last):
...
TypeError: key must be a string
>>> encrypt("", "TheAlgorithms")
Traceback (most recent call last):
...
ValueError: plaintext is empty
>>> encrypt("coffee is good as python", "")
Traceback (most recent call last):
...
ValueError: key is empty
>>> encrypt(527.26, "TheAlgorithms")
Traceback (most recent call last):
...
TypeError: plaintext must be a string
"""
if not isinstance(plaintext, str):
raise TypeError("plaintext must be a string")
if not isinstance(key, str):
raise TypeError("key must be a string")
if not plaintext:
raise ValueError("plaintext is empty")
if not key:
raise ValueError("key is empty")
key += plaintext
plaintext = plaintext.lower()
key = key.lower()
plaintext_iterator = 0
key_iterator = 0
ciphertext = ""
while plaintext_iterator < len(plaintext):
if (
ord(plaintext[plaintext_iterator]) < 97
or ord(plaintext[plaintext_iterator]) > 122
):
ciphertext += plaintext[plaintext_iterator]
plaintext_iterator += 1
elif ord(key[key_iterator]) < 97 or ord(key[key_iterator]) > 122:
key_iterator += 1
else:
ciphertext += chr(
(
(ord(plaintext[plaintext_iterator]) - 97 + ord(key[key_iterator]))
- 97
)
% 26
+ 97
)
key_iterator += 1
plaintext_iterator += 1
return ciphertext
def decrypt(ciphertext: str, key: str) -> str:
"""
Decrypt a given `ciphertext` (string) and `key` (string), returning the decrypted
ciphertext.
>>> decrypt("jsqqs avvwo", "coffee")
'hello world'
>>> decrypt("vvjfpk wj ohvp su ddylsv", "TheAlgorithms")
'coffee is good as python'
>>> decrypt("vvjfpk wj ohvp su ddylsv", "")
Traceback (most recent call last):
...
ValueError: key is empty
>>> decrypt(527.26, "TheAlgorithms")
Traceback (most recent call last):
...
TypeError: ciphertext must be a string
>>> decrypt("", "TheAlgorithms")
Traceback (most recent call last):
...
ValueError: ciphertext is empty
>>> decrypt("vvjfpk wj ohvp su ddylsv", 2)
Traceback (most recent call last):
...
TypeError: key must be a string
"""
if not isinstance(ciphertext, str):
raise TypeError("ciphertext must be a string")
if not isinstance(key, str):
raise TypeError("key must be a string")
if not ciphertext:
raise ValueError("ciphertext is empty")
if not key:
raise ValueError("key is empty")
key = key.lower()
ciphertext_iterator = 0
key_iterator = 0
plaintext = ""
while ciphertext_iterator < len(ciphertext):
if (
ord(ciphertext[ciphertext_iterator]) < 97
or ord(ciphertext[ciphertext_iterator]) > 122
):
plaintext += ciphertext[ciphertext_iterator]
else:
plaintext += chr(
(ord(ciphertext[ciphertext_iterator]) - ord(key[key_iterator])) % 26
+ 97
)
key += chr(
(ord(ciphertext[ciphertext_iterator]) - ord(key[key_iterator])) % 26
+ 97
)
key_iterator += 1
ciphertext_iterator += 1
return plaintext
if __name__ == "__main__":
import doctest
doctest.testmod()
operation = int(input("Type 1 to encrypt or 2 to decrypt:"))
if operation == 1:
plaintext = input("Typeplaintext to be encrypted:\n")
key = input("Type the key:\n")
print(encrypt(plaintext, key))
elif operation == 2:
ciphertext = input("Type the ciphertext to be decrypted:\n")
key = input("Type the key:\n")
print(decrypt(ciphertext, key))
decrypt("jsqqs avvwo", "coffee")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/caesar_cipher.py | ciphers/caesar_cipher.py | from __future__ import annotations
from string import ascii_letters
def encrypt(input_string: str, key: int, alphabet: str | None = None) -> str:
"""
encrypt
=======
Encodes a given string with the caesar cipher and returns the encoded
message
Parameters:
-----------
* `input_string`: the plain-text that needs to be encoded
* `key`: the number of letters to shift the message by
Optional:
* `alphabet` (``None``): the alphabet used to encode the cipher, if not
specified, the standard english alphabet with upper and lowercase
letters is used
Returns:
* A string containing the encoded cipher-text
More on the caesar cipher
=========================
The caesar cipher is named after Julius Caesar who used it when sending
secret military messages to his troops. This is a simple substitution cipher
where every character in the plain-text is shifted by a certain number known
as the "key" or "shift".
Example:
Say we have the following message:
``Hello, captain``
And our alphabet is made up of lower and uppercase letters:
``abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ``
And our shift is ``2``
We can then encode the message, one letter at a time. ``H`` would become ``J``,
since ``J`` is two letters away, and so on. If the shift is ever two large, or
our letter is at the end of the alphabet, we just start at the beginning
(``Z`` would shift to ``a`` then ``b`` and so on).
Our final message would be ``Jgnnq, ecrvckp``
Further reading
===============
* https://en.m.wikipedia.org/wiki/Caesar_cipher
Doctests
========
>>> encrypt('The quick brown fox jumps over the lazy dog', 8)
'bpm yCqks jzwEv nwF rCuxA wDmz Bpm tiHG lwo'
>>> encrypt('A very large key', 8000)
's nWjq dSjYW cWq'
>>> encrypt('a lowercase alphabet', 5, 'abcdefghijklmnopqrstuvwxyz')
'f qtbjwhfxj fqumfgjy'
"""
# Set default alphabet to lower and upper case english chars
alpha = alphabet or ascii_letters
# The final result string
result = ""
for character in input_string:
if character not in alpha:
# Append without encryption if character is not in the alphabet
result += character
else:
# Get the index of the new key and make sure it isn't too large
new_key = (alpha.index(character) + key) % len(alpha)
# Append the encoded character to the alphabet
result += alpha[new_key]
return result
def decrypt(input_string: str, key: int, alphabet: str | None = None) -> str:
"""
decrypt
=======
Decodes a given string of cipher-text and returns the decoded plain-text
Parameters:
-----------
* `input_string`: the cipher-text that needs to be decoded
* `key`: the number of letters to shift the message backwards by to decode
Optional:
* `alphabet` (``None``): the alphabet used to decode the cipher, if not
specified, the standard english alphabet with upper and lowercase
letters is used
Returns:
* A string containing the decoded plain-text
More on the caesar cipher
=========================
The caesar cipher is named after Julius Caesar who used it when sending
secret military messages to his troops. This is a simple substitution cipher
where very character in the plain-text is shifted by a certain number known
as the "key" or "shift". Please keep in mind, here we will be focused on
decryption.
Example:
Say we have the following cipher-text:
``Jgnnq, ecrvckp``
And our alphabet is made up of lower and uppercase letters:
``abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ``
And our shift is ``2``
To decode the message, we would do the same thing as encoding, but in
reverse. The first letter, ``J`` would become ``H`` (remember: we are decoding)
because ``H`` is two letters in reverse (to the left) of ``J``. We would
continue doing this. A letter like ``a`` would shift back to the end of
the alphabet, and would become ``Z`` or ``Y`` and so on.
Our final message would be ``Hello, captain``
Further reading
===============
* https://en.m.wikipedia.org/wiki/Caesar_cipher
Doctests
========
>>> decrypt('bpm yCqks jzwEv nwF rCuxA wDmz Bpm tiHG lwo', 8)
'The quick brown fox jumps over the lazy dog'
>>> decrypt('s nWjq dSjYW cWq', 8000)
'A very large key'
>>> decrypt('f qtbjwhfxj fqumfgjy', 5, 'abcdefghijklmnopqrstuvwxyz')
'a lowercase alphabet'
"""
# Turn on decode mode by making the key negative
key *= -1
return encrypt(input_string, key, alphabet)
def brute_force(input_string: str, alphabet: str | None = None) -> dict[int, str]:
"""
brute_force
===========
Returns all the possible combinations of keys and the decoded strings in the
form of a dictionary
Parameters:
-----------
* `input_string`: the cipher-text that needs to be used during brute-force
Optional:
* `alphabet` (``None``): the alphabet used to decode the cipher, if not
specified, the standard english alphabet with upper and lowercase
letters is used
More about brute force
======================
Brute force is when a person intercepts a message or password, not knowing
the key and tries every single combination. This is easy with the caesar
cipher since there are only all the letters in the alphabet. The more
complex the cipher, the larger amount of time it will take to do brute force
Ex:
Say we have a ``5`` letter alphabet (``abcde``), for simplicity and we intercepted
the following message: ``dbc``,
we could then just write out every combination:
``ecd``... and so on, until we reach a combination that makes sense:
``cab``
Further reading
===============
* https://en.wikipedia.org/wiki/Brute_force
Doctests
========
>>> brute_force("jFyuMy xIH'N vLONy zILwy Gy!")[20]
"Please don't brute force me!"
>>> brute_force(1)
Traceback (most recent call last):
TypeError: 'int' object is not iterable
"""
# Set default alphabet to lower and upper case english chars
alpha = alphabet or ascii_letters
# To store data on all the combinations
brute_force_data = {}
# Cycle through each combination
for key in range(1, len(alpha) + 1):
# Decrypt the message and store the result in the data
brute_force_data[key] = decrypt(input_string, key, alpha)
return brute_force_data
if __name__ == "__main__":
while True:
print(f"\n{'-' * 10}\n Menu\n{'-' * 10}")
print(*["1.Encrypt", "2.Decrypt", "3.BruteForce", "4.Quit"], sep="\n")
# get user input
choice = input("\nWhat would you like to do?: ").strip() or "4"
# run functions based on what the user chose
if choice not in ("1", "2", "3", "4"):
print("Invalid choice, please enter a valid choice")
elif choice == "1":
input_string = input("Please enter the string to be encrypted: ")
key = int(input("Please enter off-set: ").strip())
print(encrypt(input_string, key))
elif choice == "2":
input_string = input("Please enter the string to be decrypted: ")
key = int(input("Please enter off-set: ").strip())
print(decrypt(input_string, key))
elif choice == "3":
input_string = input("Please enter the string to be decrypted: ")
brute_force_data = brute_force(input_string)
for key, value in brute_force_data.items():
print(f"Key: {key} | Message: {value}")
elif choice == "4":
print("Goodbye.")
break
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/rabin_miller.py | ciphers/rabin_miller.py | # Primality Testing with the Rabin-Miller Algorithm
import random
def rabin_miller(num: int) -> bool:
s = num - 1
t = 0
while s % 2 == 0:
s = s // 2
t += 1
for _ in range(5):
a = random.randrange(2, num - 1)
v = pow(a, s, num)
if v != 1:
i = 0
while v != (num - 1):
if i == t - 1:
return False
else:
i = i + 1
v = (v**2) % num
return True
def is_prime_low_num(num: int) -> bool:
if num < 2:
return False
low_primes = [
2,
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97,
101,
103,
107,
109,
113,
127,
131,
137,
139,
149,
151,
157,
163,
167,
173,
179,
181,
191,
193,
197,
199,
211,
223,
227,
229,
233,
239,
241,
251,
257,
263,
269,
271,
277,
281,
283,
293,
307,
311,
313,
317,
331,
337,
347,
349,
353,
359,
367,
373,
379,
383,
389,
397,
401,
409,
419,
421,
431,
433,
439,
443,
449,
457,
461,
463,
467,
479,
487,
491,
499,
503,
509,
521,
523,
541,
547,
557,
563,
569,
571,
577,
587,
593,
599,
601,
607,
613,
617,
619,
631,
641,
643,
647,
653,
659,
661,
673,
677,
683,
691,
701,
709,
719,
727,
733,
739,
743,
751,
757,
761,
769,
773,
787,
797,
809,
811,
821,
823,
827,
829,
839,
853,
857,
859,
863,
877,
881,
883,
887,
907,
911,
919,
929,
937,
941,
947,
953,
967,
971,
977,
983,
991,
997,
]
if num in low_primes:
return True
for prime in low_primes:
if (num % prime) == 0:
return False
return rabin_miller(num)
def generate_large_prime(keysize: int = 1024) -> int:
while True:
num = random.randrange(2 ** (keysize - 1), 2 ** (keysize))
if is_prime_low_num(num):
return num
if __name__ == "__main__":
num = generate_large_prime()
print(("Prime number:", num))
print(("is_prime_low_num:", is_prime_low_num(num)))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/porta_cipher.py | ciphers/porta_cipher.py | alphabet = {
"A": ("ABCDEFGHIJKLM", "NOPQRSTUVWXYZ"),
"B": ("ABCDEFGHIJKLM", "NOPQRSTUVWXYZ"),
"C": ("ABCDEFGHIJKLM", "ZNOPQRSTUVWXY"),
"D": ("ABCDEFGHIJKLM", "ZNOPQRSTUVWXY"),
"E": ("ABCDEFGHIJKLM", "YZNOPQRSTUVWX"),
"F": ("ABCDEFGHIJKLM", "YZNOPQRSTUVWX"),
"G": ("ABCDEFGHIJKLM", "XYZNOPQRSTUVW"),
"H": ("ABCDEFGHIJKLM", "XYZNOPQRSTUVW"),
"I": ("ABCDEFGHIJKLM", "WXYZNOPQRSTUV"),
"J": ("ABCDEFGHIJKLM", "WXYZNOPQRSTUV"),
"K": ("ABCDEFGHIJKLM", "VWXYZNOPQRSTU"),
"L": ("ABCDEFGHIJKLM", "VWXYZNOPQRSTU"),
"M": ("ABCDEFGHIJKLM", "UVWXYZNOPQRST"),
"N": ("ABCDEFGHIJKLM", "UVWXYZNOPQRST"),
"O": ("ABCDEFGHIJKLM", "TUVWXYZNOPQRS"),
"P": ("ABCDEFGHIJKLM", "TUVWXYZNOPQRS"),
"Q": ("ABCDEFGHIJKLM", "STUVWXYZNOPQR"),
"R": ("ABCDEFGHIJKLM", "STUVWXYZNOPQR"),
"S": ("ABCDEFGHIJKLM", "RSTUVWXYZNOPQ"),
"T": ("ABCDEFGHIJKLM", "RSTUVWXYZNOPQ"),
"U": ("ABCDEFGHIJKLM", "QRSTUVWXYZNOP"),
"V": ("ABCDEFGHIJKLM", "QRSTUVWXYZNOP"),
"W": ("ABCDEFGHIJKLM", "PQRSTUVWXYZNO"),
"X": ("ABCDEFGHIJKLM", "PQRSTUVWXYZNO"),
"Y": ("ABCDEFGHIJKLM", "OPQRSTUVWXYZN"),
"Z": ("ABCDEFGHIJKLM", "OPQRSTUVWXYZN"),
}
def generate_table(key: str) -> list[tuple[str, str]]:
"""
>>> generate_table('marvin') # doctest: +NORMALIZE_WHITESPACE
[('ABCDEFGHIJKLM', 'UVWXYZNOPQRST'), ('ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ'),
('ABCDEFGHIJKLM', 'STUVWXYZNOPQR'), ('ABCDEFGHIJKLM', 'QRSTUVWXYZNOP'),
('ABCDEFGHIJKLM', 'WXYZNOPQRSTUV'), ('ABCDEFGHIJKLM', 'UVWXYZNOPQRST')]
"""
return [alphabet[char] for char in key.upper()]
def encrypt(key: str, words: str) -> str:
"""
>>> encrypt('marvin', 'jessica')
'QRACRWU'
"""
cipher = ""
count = 0
table = generate_table(key)
for char in words.upper():
cipher += get_opponent(table[count], char)
count = (count + 1) % len(table)
return cipher
def decrypt(key: str, words: str) -> str:
"""
>>> decrypt('marvin', 'QRACRWU')
'JESSICA'
"""
return encrypt(key, words)
def get_position(table: tuple[str, str], char: str) -> tuple[int, int]:
"""
>>> get_position(generate_table('marvin')[0], 'M')
(0, 12)
"""
# `char` is either in the 0th row or the 1st row
row = 0 if char in table[0] else 1
col = table[row].index(char)
return row, col
def get_opponent(table: tuple[str, str], char: str) -> str:
"""
>>> get_opponent(generate_table('marvin')[0], 'M')
'T'
"""
row, col = get_position(table, char.upper())
if row == 1:
return table[0][col]
else:
return table[1][col] if row == 0 else char
if __name__ == "__main__":
import doctest
doctest.testmod() # Fist ensure that all our tests are passing...
"""
Demo:
Enter key: marvin
Enter text to encrypt: jessica
Encrypted: QRACRWU
Decrypted with key: JESSICA
"""
key = input("Enter key: ").strip()
text = input("Enter text to encrypt: ").strip()
cipher_text = encrypt(key, text)
print(f"Encrypted: {cipher_text}")
print(f"Decrypted with key: {decrypt(key, cipher_text)}")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/ciphers/__init__.py | ciphers/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.