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/conversions/decimal_to_binary.py | conversions/decimal_to_binary.py | """Convert a Decimal Number to a Binary Number."""
def decimal_to_binary_iterative(num: int) -> str:
"""
Convert an Integer Decimal Number to a Binary Number as str.
>>> decimal_to_binary_iterative(0)
'0b0'
>>> decimal_to_binary_iterative(2)
'0b10'
>>> decimal_to_binary_iterative(7)
'0b111'
>>> decimal_to_binary_iterative(35)
'0b100011'
>>> # negatives work too
>>> decimal_to_binary_iterative(-2)
'-0b10'
>>> # other floats will error
>>> decimal_to_binary_iterative(16.16) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: 'float' object cannot be interpreted as an integer
>>> # strings will error as well
>>> decimal_to_binary_iterative('0xfffff') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: 'str' object cannot be interpreted as an integer
"""
if isinstance(num, float):
raise TypeError("'float' object cannot be interpreted as an integer")
if isinstance(num, str):
raise TypeError("'str' object cannot be interpreted as an integer")
if num == 0:
return "0b0"
negative = False
if num < 0:
negative = True
num = -num
binary: list[int] = []
while num > 0:
binary.insert(0, num % 2)
num >>= 1
if negative:
return "-0b" + "".join(str(e) for e in binary)
return "0b" + "".join(str(e) for e in binary)
def decimal_to_binary_recursive_helper(decimal: int) -> str:
"""
Take a positive integer value and return its binary equivalent.
>>> decimal_to_binary_recursive_helper(1000)
'1111101000'
>>> decimal_to_binary_recursive_helper("72")
'1001000'
>>> decimal_to_binary_recursive_helper("number")
Traceback (most recent call last):
...
ValueError: invalid literal for int() with base 10: 'number'
"""
decimal = int(decimal)
if decimal in (0, 1): # Exit cases for the recursion
return str(decimal)
div, mod = divmod(decimal, 2)
return decimal_to_binary_recursive_helper(div) + str(mod)
def decimal_to_binary_recursive(number: str) -> str:
"""
Take an integer value and raise ValueError for wrong inputs,
call the function above and return the output with prefix "0b" & "-0b"
for positive and negative integers respectively.
>>> decimal_to_binary_recursive(0)
'0b0'
>>> decimal_to_binary_recursive(40)
'0b101000'
>>> decimal_to_binary_recursive(-40)
'-0b101000'
>>> decimal_to_binary_recursive(40.8)
Traceback (most recent call last):
...
ValueError: Input value is not an integer
>>> decimal_to_binary_recursive("forty")
Traceback (most recent call last):
...
ValueError: Input value is not an integer
"""
number = str(number).strip()
if not number:
raise ValueError("No input value was provided")
negative = "-" if number.startswith("-") else ""
number = number.lstrip("-")
if not number.isnumeric():
raise ValueError("Input value is not an integer")
return f"{negative}0b{decimal_to_binary_recursive_helper(int(number))}"
if __name__ == "__main__":
import doctest
doctest.testmod()
print(decimal_to_binary_recursive(input("Input a decimal number: ")))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/pressure_conversions.py | conversions/pressure_conversions.py | """
Conversion of pressure units.
Available Units:- Pascal,Bar,Kilopascal,Megapascal,psi(pound per square inch),
inHg(in mercury column),torr,atm
USAGE :
-> Import this file into their respective project.
-> Use the function pressure_conversion() for conversion of pressure units.
-> Parameters :
-> value : The number of from units you want to convert
-> from_type : From which type you want to convert
-> to_type : To which type you want to convert
REFERENCES :
-> Wikipedia reference: https://en.wikipedia.org/wiki/Pascal_(unit)
-> Wikipedia reference: https://en.wikipedia.org/wiki/Pound_per_square_inch
-> Wikipedia reference: https://en.wikipedia.org/wiki/Inch_of_mercury
-> Wikipedia reference: https://en.wikipedia.org/wiki/Torr
-> https://en.wikipedia.org/wiki/Standard_atmosphere_(unit)
-> https://msestudent.com/what-are-the-units-of-pressure/
-> https://www.unitconverters.net/pressure-converter.html
"""
from typing import NamedTuple
class FromTo(NamedTuple):
from_factor: float
to_factor: float
PRESSURE_CONVERSION = {
"atm": FromTo(1, 1),
"pascal": FromTo(0.0000098, 101325),
"bar": FromTo(0.986923, 1.01325),
"kilopascal": FromTo(0.00986923, 101.325),
"megapascal": FromTo(9.86923, 0.101325),
"psi": FromTo(0.068046, 14.6959),
"inHg": FromTo(0.0334211, 29.9213),
"torr": FromTo(0.00131579, 760),
}
def pressure_conversion(value: float, from_type: str, to_type: str) -> float:
"""
Conversion between pressure units.
>>> pressure_conversion(4, "atm", "pascal")
405300
>>> pressure_conversion(1, "pascal", "psi")
0.00014401981999999998
>>> pressure_conversion(1, "bar", "atm")
0.986923
>>> pressure_conversion(3, "kilopascal", "bar")
0.029999991892499998
>>> pressure_conversion(2, "megapascal", "psi")
290.074434314
>>> pressure_conversion(4, "psi", "torr")
206.85984
>>> pressure_conversion(1, "inHg", "atm")
0.0334211
>>> pressure_conversion(1, "torr", "psi")
0.019336718261000002
>>> pressure_conversion(4, "wrongUnit", "atm")
Traceback (most recent call last):
...
ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are:
atm, pascal, bar, kilopascal, megapascal, psi, inHg, torr
"""
if from_type not in PRESSURE_CONVERSION:
raise ValueError(
f"Invalid 'from_type' value: {from_type!r} Supported values are:\n"
+ ", ".join(PRESSURE_CONVERSION)
)
if to_type not in PRESSURE_CONVERSION:
raise ValueError(
f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n"
+ ", ".join(PRESSURE_CONVERSION)
)
return (
value
* PRESSURE_CONVERSION[from_type].from_factor
* PRESSURE_CONVERSION[to_type].to_factor
)
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/conversions/octal_to_hexadecimal.py | conversions/octal_to_hexadecimal.py | def octal_to_hex(octal: str) -> str:
"""
Convert an Octal number to Hexadecimal number.
For more information: https://en.wikipedia.org/wiki/Octal
>>> octal_to_hex("100")
'0x40'
>>> octal_to_hex("235")
'0x9D'
>>> octal_to_hex(17)
Traceback (most recent call last):
...
TypeError: Expected a string as input
>>> octal_to_hex("Av")
Traceback (most recent call last):
...
ValueError: Not a Valid Octal Number
>>> octal_to_hex("")
Traceback (most recent call last):
...
ValueError: Empty string was passed to the function
"""
if not isinstance(octal, str):
raise TypeError("Expected a string as input")
if octal.startswith("0o"):
octal = octal[2:]
if octal == "":
raise ValueError("Empty string was passed to the function")
if any(char not in "01234567" for char in octal):
raise ValueError("Not a Valid Octal Number")
decimal = 0
for char in octal:
decimal <<= 3
decimal |= int(char)
hex_char = "0123456789ABCDEF"
revhex = ""
while decimal:
revhex += hex_char[decimal & 15]
decimal >>= 4
return "0x" + revhex[::-1]
if __name__ == "__main__":
import doctest
doctest.testmod()
nums = ["030", "100", "247", "235", "007"]
## Main Tests
for num in nums:
hexadecimal = octal_to_hex(num)
expected = "0x" + hex(int(num, 8))[2:].upper()
assert hexadecimal == expected
print(f"Hex of '0o{num}' is: {hexadecimal}")
print(f"Expected was: {expected}")
print("---")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/decimal_to_octal.py | conversions/decimal_to_octal.py | """Convert a Decimal Number to an Octal Number."""
import math
# Modified from:
# https://github.com/TheAlgorithms/Javascript/blob/master/Conversions/DecimalToOctal.js
def decimal_to_octal(num: int) -> str:
"""Convert a Decimal Number to an Octal Number.
>>> all(decimal_to_octal(i) == oct(i) for i
... in (0, 2, 8, 64, 65, 216, 255, 256, 512))
True
"""
octal = 0
counter = 0
while num > 0:
remainder = num % 8
octal = octal + (remainder * math.floor(math.pow(10, counter)))
counter += 1
num = math.floor(num / 8) # basically /= 8 without remainder if any
# This formatting removes trailing '.0' from `octal`.
return f"0o{int(octal)}"
def main() -> None:
"""Print octal equivalents of decimal numbers."""
print("\n2 in octal is:")
print(decimal_to_octal(2)) # = 2
print("\n8 in octal is:")
print(decimal_to_octal(8)) # = 10
print("\n65 in octal is:")
print(decimal_to_octal(65)) # = 101
print("\n216 in octal is:")
print(decimal_to_octal(216)) # = 330
print("\n512 in octal is:")
print(decimal_to_octal(512)) # = 1000
print("\n")
if __name__ == "__main__":
main()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/rgb_cmyk_conversion.py | conversions/rgb_cmyk_conversion.py | def rgb_to_cmyk(r_input: int, g_input: int, b_input: int) -> tuple[int, int, int, int]:
"""
Simple RGB to CMYK conversion. Returns percentages of CMYK paint.
https://www.programmingalgorithms.com/algorithm/rgb-to-cmyk/
Note: this is a very popular algorithm that converts colors linearly and gives
only approximate results. Actual preparation for printing requires advanced color
conversion considering the color profiles and parameters of the target device.
>>> rgb_to_cmyk(255, 200, "a")
Traceback (most recent call last):
...
ValueError: Expected int, found (<class 'int'>, <class 'int'>, <class 'str'>)
>>> rgb_to_cmyk(255, 255, 999)
Traceback (most recent call last):
...
ValueError: Expected int of the range 0..255
>>> rgb_to_cmyk(255, 255, 255) # white
(0, 0, 0, 0)
>>> rgb_to_cmyk(128, 128, 128) # gray
(0, 0, 0, 50)
>>> rgb_to_cmyk(0, 0, 0) # black
(0, 0, 0, 100)
>>> rgb_to_cmyk(255, 0, 0) # red
(0, 100, 100, 0)
>>> rgb_to_cmyk(0, 255, 0) # green
(100, 0, 100, 0)
>>> rgb_to_cmyk(0, 0, 255) # blue
(100, 100, 0, 0)
"""
if (
not isinstance(r_input, int)
or not isinstance(g_input, int)
or not isinstance(b_input, int)
):
msg = f"Expected int, found {type(r_input), type(g_input), type(b_input)}"
raise ValueError(msg)
if not 0 <= r_input < 256 or not 0 <= g_input < 256 or not 0 <= b_input < 256:
raise ValueError("Expected int of the range 0..255")
# changing range from 0..255 to 0..1
r = r_input / 255
g = g_input / 255
b = b_input / 255
k = 1 - max(r, g, b)
if k == 1: # pure black
return 0, 0, 0, 100
c = round(100 * (1 - r - k) / (1 - k))
m = round(100 * (1 - g - k) / (1 - k))
y = round(100 * (1 - b - k) / (1 - k))
k = round(100 * k)
return c, m, y, k
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/conversions/binary_to_hexadecimal.py | conversions/binary_to_hexadecimal.py | BITS_TO_HEX = {
"0000": "0",
"0001": "1",
"0010": "2",
"0011": "3",
"0100": "4",
"0101": "5",
"0110": "6",
"0111": "7",
"1000": "8",
"1001": "9",
"1010": "a",
"1011": "b",
"1100": "c",
"1101": "d",
"1110": "e",
"1111": "f",
}
def bin_to_hexadecimal(binary_str: str) -> str:
"""
Converting a binary string into hexadecimal using Grouping Method
>>> bin_to_hexadecimal('101011111')
'0x15f'
>>> bin_to_hexadecimal(' 1010 ')
'0x0a'
>>> bin_to_hexadecimal('-11101')
'-0x1d'
>>> bin_to_hexadecimal('a')
Traceback (most recent call last):
...
ValueError: Non-binary value was passed to the function
>>> bin_to_hexadecimal('')
Traceback (most recent call last):
...
ValueError: Empty string was passed to the function
"""
# Sanitising parameter
binary_str = str(binary_str).strip()
# Exceptions
if not binary_str:
raise ValueError("Empty string was passed to the function")
is_negative = binary_str[0] == "-"
binary_str = binary_str[1:] if is_negative else binary_str
if not all(char in "01" for char in binary_str):
raise ValueError("Non-binary value was passed to the function")
binary_str = (
"0" * (4 * (divmod(len(binary_str), 4)[0] + 1) - len(binary_str)) + binary_str
)
hexadecimal = []
for x in range(0, len(binary_str), 4):
hexadecimal.append(BITS_TO_HEX[binary_str[x : x + 4]])
hexadecimal_str = "0x" + "".join(hexadecimal)
return "-" + hexadecimal_str if is_negative else hexadecimal_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/conversions/time_conversions.py | conversions/time_conversions.py | """
A unit of time is any particular time interval, used as a standard way of measuring or
expressing duration. The base unit of time in the International System of Units (SI),
and by extension most of the Western world, is the second, defined as about 9 billion
oscillations of the caesium atom.
https://en.wikipedia.org/wiki/Unit_of_time
"""
time_chart: dict[str, float] = {
"seconds": 1.0,
"minutes": 60.0, # 1 minute = 60 sec
"hours": 3600.0, # 1 hour = 60 minutes = 3600 seconds
"days": 86400.0, # 1 day = 24 hours = 1440 min = 86400 sec
"weeks": 604800.0, # 1 week=7d=168hr=10080min = 604800 sec
"months": 2629800.0, # Approximate value for a month in seconds
"years": 31557600.0, # Approximate value for a year in seconds
}
time_chart_inverse: dict[str, float] = {
key: 1 / value for key, value in time_chart.items()
}
def convert_time(time_value: float, unit_from: str, unit_to: str) -> float:
"""
Convert time from one unit to another using the time_chart above.
>>> convert_time(3600, "seconds", "hours")
1.0
>>> convert_time(3500, "Seconds", "Hours")
0.972
>>> convert_time(1, "DaYs", "hours")
24.0
>>> convert_time(120, "minutes", "SeCoNdS")
7200.0
>>> convert_time(2, "WEEKS", "days")
14.0
>>> convert_time(0.5, "hours", "MINUTES")
30.0
>>> convert_time(-3600, "seconds", "hours")
Traceback (most recent call last):
...
ValueError: 'time_value' must be a non-negative number.
>>> convert_time("Hello", "hours", "minutes")
Traceback (most recent call last):
...
ValueError: 'time_value' must be a non-negative number.
>>> convert_time([0, 1, 2], "weeks", "days")
Traceback (most recent call last):
...
ValueError: 'time_value' must be a non-negative number.
>>> convert_time(1, "cool", "century") # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Invalid unit cool is not in seconds, minutes, hours, days, weeks, ...
>>> convert_time(1, "seconds", "hot") # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Invalid unit hot is not in seconds, minutes, hours, days, weeks, ...
"""
if not isinstance(time_value, (int, float)) or time_value < 0:
msg = "'time_value' must be a non-negative number."
raise ValueError(msg)
unit_from = unit_from.lower()
unit_to = unit_to.lower()
if unit_from not in time_chart or unit_to not in time_chart:
invalid_unit = unit_from if unit_from not in time_chart else unit_to
msg = f"Invalid unit {invalid_unit} is not in {', '.join(time_chart)}."
raise ValueError(msg)
return round(
time_value * time_chart[unit_from] * time_chart_inverse[unit_to],
3,
)
if __name__ == "__main__":
import doctest
doctest.testmod()
print(f"{convert_time(3600,'seconds', 'hours') = :,}")
print(f"{convert_time(360, 'days', 'months') = :,}")
print(f"{convert_time(360, 'months', 'years') = :,}")
print(f"{convert_time(1, 'years', 'seconds') = :,}")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/rectangular_to_polar.py | conversions/rectangular_to_polar.py | import math
def rectangular_to_polar(real: float, img: float) -> tuple[float, float]:
"""
https://en.wikipedia.org/wiki/Polar_coordinate_system
>>> rectangular_to_polar(5,-5)
(7.07, -45.0)
>>> rectangular_to_polar(-1,1)
(1.41, 135.0)
>>> rectangular_to_polar(-1,-1)
(1.41, -135.0)
>>> rectangular_to_polar(1e-10,1e-10)
(0.0, 45.0)
>>> rectangular_to_polar(-1e-10,1e-10)
(0.0, 135.0)
>>> rectangular_to_polar(9.75,5.93)
(11.41, 31.31)
>>> rectangular_to_polar(10000,99999)
(100497.76, 84.29)
"""
mod = round(math.sqrt((real**2) + (img**2)), 2)
ang = round(math.degrees(math.atan2(img, real)), 2)
return (mod, ang)
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/conversions/energy_conversions.py | conversions/energy_conversions.py | """
Conversion of energy units.
Available units: joule, kilojoule, megajoule, gigajoule,\
wattsecond, watthour, kilowatthour, newtonmeter, calorie_nutr,\
kilocalorie_nutr, electronvolt, britishthermalunit_it, footpound
USAGE :
-> Import this file into their respective project.
-> Use the function energy_conversion() for conversion of energy units.
-> Parameters :
-> from_type : From which type you want to convert
-> to_type : To which type you want to convert
-> value : the value which you want to convert
REFERENCES :
-> Wikipedia reference: https://en.wikipedia.org/wiki/Units_of_energy
-> Wikipedia reference: https://en.wikipedia.org/wiki/Joule
-> Wikipedia reference: https://en.wikipedia.org/wiki/Kilowatt-hour
-> Wikipedia reference: https://en.wikipedia.org/wiki/Newton-metre
-> Wikipedia reference: https://en.wikipedia.org/wiki/Calorie
-> Wikipedia reference: https://en.wikipedia.org/wiki/Electronvolt
-> Wikipedia reference: https://en.wikipedia.org/wiki/British_thermal_unit
-> Wikipedia reference: https://en.wikipedia.org/wiki/Foot-pound_(energy)
-> Unit converter reference: https://www.unitconverters.net/energy-converter.html
"""
ENERGY_CONVERSION: dict[str, float] = {
"joule": 1.0,
"kilojoule": 1_000,
"megajoule": 1_000_000,
"gigajoule": 1_000_000_000,
"wattsecond": 1.0,
"watthour": 3_600,
"kilowatthour": 3_600_000,
"newtonmeter": 1.0,
"calorie_nutr": 4_186.8,
"kilocalorie_nutr": 4_186_800.00,
"electronvolt": 1.602_176_634e-19,
"britishthermalunit_it": 1_055.055_85,
"footpound": 1.355_818,
}
def energy_conversion(from_type: str, to_type: str, value: float) -> float:
"""
Conversion of energy units.
>>> energy_conversion("joule", "joule", 1)
1.0
>>> energy_conversion("joule", "kilojoule", 1)
0.001
>>> energy_conversion("joule", "megajoule", 1)
1e-06
>>> energy_conversion("joule", "gigajoule", 1)
1e-09
>>> energy_conversion("joule", "wattsecond", 1)
1.0
>>> energy_conversion("joule", "watthour", 1)
0.0002777777777777778
>>> energy_conversion("joule", "kilowatthour", 1)
2.7777777777777776e-07
>>> energy_conversion("joule", "newtonmeter", 1)
1.0
>>> energy_conversion("joule", "calorie_nutr", 1)
0.00023884589662749592
>>> energy_conversion("joule", "kilocalorie_nutr", 1)
2.388458966274959e-07
>>> energy_conversion("joule", "electronvolt", 1)
6.241509074460763e+18
>>> energy_conversion("joule", "britishthermalunit_it", 1)
0.0009478171226670134
>>> energy_conversion("joule", "footpound", 1)
0.7375621211696556
>>> energy_conversion("joule", "megajoule", 1000)
0.001
>>> energy_conversion("calorie_nutr", "kilocalorie_nutr", 1000)
1.0
>>> energy_conversion("kilowatthour", "joule", 10)
36000000.0
>>> energy_conversion("britishthermalunit_it", "footpound", 1)
778.1692306784539
>>> energy_conversion("watthour", "joule", "a") # doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for /: 'str' and 'float'
>>> energy_conversion("wrongunit", "joule", 1) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Incorrect 'from_type' or 'to_type' value: 'wrongunit', 'joule'
Valid values are: joule, ... footpound
>>> energy_conversion("joule", "wrongunit", 1) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Incorrect 'from_type' or 'to_type' value: 'joule', 'wrongunit'
Valid values are: joule, ... footpound
>>> energy_conversion("123", "abc", 1) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Incorrect 'from_type' or 'to_type' value: '123', 'abc'
Valid values are: joule, ... footpound
"""
if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION:
msg = (
f"Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n"
f"Valid values are: {', '.join(ENERGY_CONVERSION)}"
)
raise ValueError(msg)
return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type]
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/conversions/weight_conversion.py | conversions/weight_conversion.py | """
Conversion of weight units.
__author__ = "Anubhav Solanki"
__license__ = "MIT"
__version__ = "1.1.0"
__maintainer__ = "Anubhav Solanki"
__email__ = "anubhavsolanki0@gmail.com"
USAGE :
-> Import this file into their respective project.
-> Use the function weight_conversion() for conversion of weight units.
-> Parameters :
-> from_type : From which type you want to convert
-> to_type : To which type you want to convert
-> value : the value which you want to convert
REFERENCES :
-> Wikipedia reference: https://en.wikipedia.org/wiki/Kilogram
-> Wikipedia reference: https://en.wikipedia.org/wiki/Gram
-> Wikipedia reference: https://en.wikipedia.org/wiki/Millimetre
-> Wikipedia reference: https://en.wikipedia.org/wiki/Tonne
-> Wikipedia reference: https://en.wikipedia.org/wiki/Long_ton
-> Wikipedia reference: https://en.wikipedia.org/wiki/Short_ton
-> Wikipedia reference: https://en.wikipedia.org/wiki/Pound
-> Wikipedia reference: https://en.wikipedia.org/wiki/Ounce
-> Wikipedia reference: https://en.wikipedia.org/wiki/Fineness#Karat
-> Wikipedia reference: https://en.wikipedia.org/wiki/Dalton_(unit)
-> Wikipedia reference: https://en.wikipedia.org/wiki/Stone_(unit)
"""
KILOGRAM_CHART: dict[str, float] = {
"kilogram": 1,
"gram": pow(10, 3),
"milligram": pow(10, 6),
"metric-ton": pow(10, -3),
"long-ton": 0.0009842073,
"short-ton": 0.0011023122,
"pound": 2.2046244202,
"stone": 0.1574731728,
"ounce": 35.273990723,
"carrat": 5000,
"atomic-mass-unit": 6.022136652e26,
}
WEIGHT_TYPE_CHART: dict[str, float] = {
"kilogram": 1,
"gram": pow(10, -3),
"milligram": pow(10, -6),
"metric-ton": pow(10, 3),
"long-ton": 1016.04608,
"short-ton": 907.184,
"pound": 0.453592,
"stone": 6.35029,
"ounce": 0.0283495,
"carrat": 0.0002,
"atomic-mass-unit": 1.660540199e-27,
}
def weight_conversion(from_type: str, to_type: str, value: float) -> float:
"""
Conversion of weight unit with the help of KILOGRAM_CHART
"kilogram" : 1,
"gram" : pow(10, 3),
"milligram" : pow(10, 6),
"metric-ton" : pow(10, -3),
"long-ton" : 0.0009842073,
"short-ton" : 0.0011023122,
"pound" : 2.2046244202,
"stone": 0.1574731728,
"ounce" : 35.273990723,
"carrat" : 5000,
"atomic-mass-unit" : 6.022136652E+26
>>> weight_conversion("kilogram","kilogram",4)
4
>>> weight_conversion("kilogram","gram",1)
1000
>>> weight_conversion("kilogram","milligram",4)
4000000
>>> weight_conversion("kilogram","metric-ton",4)
0.004
>>> weight_conversion("kilogram","long-ton",3)
0.0029526219
>>> weight_conversion("kilogram","short-ton",1)
0.0011023122
>>> weight_conversion("kilogram","pound",4)
8.8184976808
>>> weight_conversion("kilogram","stone",5)
0.7873658640000001
>>> weight_conversion("kilogram","ounce",4)
141.095962892
>>> weight_conversion("kilogram","carrat",3)
15000
>>> weight_conversion("kilogram","atomic-mass-unit",1)
6.022136652e+26
>>> weight_conversion("gram","kilogram",1)
0.001
>>> weight_conversion("gram","gram",3)
3.0
>>> weight_conversion("gram","milligram",2)
2000.0
>>> weight_conversion("gram","metric-ton",4)
4e-06
>>> weight_conversion("gram","long-ton",3)
2.9526219e-06
>>> weight_conversion("gram","short-ton",3)
3.3069366000000003e-06
>>> weight_conversion("gram","pound",3)
0.0066138732606
>>> weight_conversion("gram","stone",4)
0.0006298926912000001
>>> weight_conversion("gram","ounce",1)
0.035273990723
>>> weight_conversion("gram","carrat",2)
10.0
>>> weight_conversion("gram","atomic-mass-unit",1)
6.022136652e+23
>>> weight_conversion("milligram","kilogram",1)
1e-06
>>> weight_conversion("milligram","gram",2)
0.002
>>> weight_conversion("milligram","milligram",3)
3.0
>>> weight_conversion("milligram","metric-ton",3)
3e-09
>>> weight_conversion("milligram","long-ton",3)
2.9526219e-09
>>> weight_conversion("milligram","short-ton",1)
1.1023122e-09
>>> weight_conversion("milligram","pound",3)
6.6138732605999995e-06
>>> weight_conversion("milligram","ounce",2)
7.054798144599999e-05
>>> weight_conversion("milligram","carrat",1)
0.005
>>> weight_conversion("milligram","atomic-mass-unit",1)
6.022136652e+20
>>> weight_conversion("metric-ton","kilogram",2)
2000
>>> weight_conversion("metric-ton","gram",2)
2000000
>>> weight_conversion("metric-ton","milligram",3)
3000000000
>>> weight_conversion("metric-ton","metric-ton",2)
2.0
>>> weight_conversion("metric-ton","long-ton",3)
2.9526219
>>> weight_conversion("metric-ton","short-ton",2)
2.2046244
>>> weight_conversion("metric-ton","pound",3)
6613.8732606
>>> weight_conversion("metric-ton","ounce",4)
141095.96289199998
>>> weight_conversion("metric-ton","carrat",4)
20000000
>>> weight_conversion("metric-ton","atomic-mass-unit",1)
6.022136652e+29
>>> weight_conversion("long-ton","kilogram",4)
4064.18432
>>> weight_conversion("long-ton","gram",4)
4064184.32
>>> weight_conversion("long-ton","milligram",3)
3048138240.0
>>> weight_conversion("long-ton","metric-ton",4)
4.06418432
>>> weight_conversion("long-ton","long-ton",3)
2.999999907217152
>>> weight_conversion("long-ton","short-ton",1)
1.119999989746176
>>> weight_conversion("long-ton","pound",3)
6720.000000049448
>>> weight_conversion("long-ton","ounce",1)
35840.000000060514
>>> weight_conversion("long-ton","carrat",4)
20320921.599999998
>>> weight_conversion("long-ton","atomic-mass-unit",4)
2.4475073353955697e+30
>>> weight_conversion("short-ton","kilogram",3)
2721.5519999999997
>>> weight_conversion("short-ton","gram",3)
2721552.0
>>> weight_conversion("short-ton","milligram",1)
907184000.0
>>> weight_conversion("short-ton","metric-ton",4)
3.628736
>>> weight_conversion("short-ton","long-ton",3)
2.6785713457296
>>> weight_conversion("short-ton","short-ton",3)
2.9999999725344
>>> weight_conversion("short-ton","pound",2)
4000.0000000294335
>>> weight_conversion("short-ton","ounce",4)
128000.00000021611
>>> weight_conversion("short-ton","carrat",4)
18143680.0
>>> weight_conversion("short-ton","atomic-mass-unit",1)
5.463186016507968e+29
>>> weight_conversion("pound","kilogram",4)
1.814368
>>> weight_conversion("pound","gram",2)
907.184
>>> weight_conversion("pound","milligram",3)
1360776.0
>>> weight_conversion("pound","metric-ton",3)
0.001360776
>>> weight_conversion("pound","long-ton",2)
0.0008928571152432
>>> weight_conversion("pound","short-ton",1)
0.0004999999954224
>>> weight_conversion("pound","pound",3)
3.0000000000220752
>>> weight_conversion("pound","ounce",1)
16.000000000027015
>>> weight_conversion("pound","carrat",1)
2267.96
>>> weight_conversion("pound","atomic-mass-unit",4)
1.0926372033015936e+27
>>> weight_conversion("stone","kilogram",5)
31.751450000000002
>>> weight_conversion("stone","gram",2)
12700.58
>>> weight_conversion("stone","milligram",3)
19050870.0
>>> weight_conversion("stone","metric-ton",3)
0.01905087
>>> weight_conversion("stone","long-ton",3)
0.018750005325351003
>>> weight_conversion("stone","short-ton",3)
0.021000006421614002
>>> weight_conversion("stone","pound",2)
28.00000881870372
>>> weight_conversion("stone","ounce",1)
224.00007054835967
>>> weight_conversion("stone","carrat",2)
63502.9
>>> weight_conversion("ounce","kilogram",3)
0.0850485
>>> weight_conversion("ounce","gram",3)
85.0485
>>> weight_conversion("ounce","milligram",4)
113398.0
>>> weight_conversion("ounce","metric-ton",4)
0.000113398
>>> weight_conversion("ounce","long-ton",4)
0.0001116071394054
>>> weight_conversion("ounce","short-ton",4)
0.0001249999988556
>>> weight_conversion("ounce","pound",1)
0.0625000000004599
>>> weight_conversion("ounce","ounce",2)
2.000000000003377
>>> weight_conversion("ounce","carrat",1)
141.7475
>>> weight_conversion("ounce","atomic-mass-unit",1)
1.70724563015874e+25
>>> weight_conversion("carrat","kilogram",1)
0.0002
>>> weight_conversion("carrat","gram",4)
0.8
>>> weight_conversion("carrat","milligram",2)
400.0
>>> weight_conversion("carrat","metric-ton",2)
4.0000000000000003e-07
>>> weight_conversion("carrat","long-ton",3)
5.9052438e-07
>>> weight_conversion("carrat","short-ton",4)
8.818497600000002e-07
>>> weight_conversion("carrat","pound",1)
0.00044092488404000004
>>> weight_conversion("carrat","ounce",2)
0.0141095962892
>>> weight_conversion("carrat","carrat",4)
4.0
>>> weight_conversion("carrat","atomic-mass-unit",4)
4.8177093216e+23
>>> weight_conversion("atomic-mass-unit","kilogram",4)
6.642160796e-27
>>> weight_conversion("atomic-mass-unit","gram",2)
3.321080398e-24
>>> weight_conversion("atomic-mass-unit","milligram",2)
3.3210803980000002e-21
>>> weight_conversion("atomic-mass-unit","metric-ton",3)
4.9816205970000004e-30
>>> weight_conversion("atomic-mass-unit","long-ton",3)
4.9029473573977584e-30
>>> weight_conversion("atomic-mass-unit","short-ton",1)
1.830433719948128e-30
>>> weight_conversion("atomic-mass-unit","pound",3)
1.0982602420317504e-26
>>> weight_conversion("atomic-mass-unit","ounce",2)
1.1714775914938915e-25
>>> weight_conversion("atomic-mass-unit","carrat",2)
1.660540199e-23
>>> weight_conversion("atomic-mass-unit","atomic-mass-unit",2)
1.999999998903455
>>> weight_conversion("slug", "kilogram", 1)
Traceback (most recent call last):
...
ValueError: Invalid 'from_type' or 'to_type' value: 'slug', 'kilogram'
Supported values are: kilogram, gram, milligram, metric-ton, long-ton, short-ton, \
pound, stone, ounce, carrat, atomic-mass-unit
"""
if to_type not in KILOGRAM_CHART or from_type not in WEIGHT_TYPE_CHART:
msg = (
f"Invalid 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n"
f"Supported values are: {', '.join(WEIGHT_TYPE_CHART)}"
)
raise ValueError(msg)
return value * KILOGRAM_CHART[to_type] * WEIGHT_TYPE_CHART[from_type]
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/conversions/volume_conversions.py | conversions/volume_conversions.py | """
Conversion of volume units.
Available Units:- Cubic metre,Litre,KiloLitre,Gallon,Cubic yard,Cubic foot,cup
USAGE :
-> Import this file into their respective project.
-> Use the function length_conversion() for conversion of volume units.
-> Parameters :
-> value : The number of from units you want to convert
-> from_type : From which type you want to convert
-> to_type : To which type you want to convert
REFERENCES :
-> Wikipedia reference: https://en.wikipedia.org/wiki/Cubic_metre
-> Wikipedia reference: https://en.wikipedia.org/wiki/Litre
-> Wikipedia reference: https://en.wiktionary.org/wiki/kilolitre
-> Wikipedia reference: https://en.wikipedia.org/wiki/Gallon
-> Wikipedia reference: https://en.wikipedia.org/wiki/Cubic_yard
-> Wikipedia reference: https://en.wikipedia.org/wiki/Cubic_foot
-> Wikipedia reference: https://en.wikipedia.org/wiki/Cup_(unit)
"""
from typing import NamedTuple
class FromTo(NamedTuple):
from_factor: float
to_factor: float
METRIC_CONVERSION = {
"cubic meter": FromTo(1, 1),
"litre": FromTo(0.001, 1000),
"kilolitre": FromTo(1, 1),
"gallon": FromTo(0.00454, 264.172),
"cubic yard": FromTo(0.76455, 1.30795),
"cubic foot": FromTo(0.028, 35.3147),
"cup": FromTo(0.000236588, 4226.75),
}
def volume_conversion(value: float, from_type: str, to_type: str) -> float:
"""
Conversion between volume units.
>>> volume_conversion(4, "cubic meter", "litre")
4000
>>> volume_conversion(1, "litre", "gallon")
0.264172
>>> volume_conversion(1, "kilolitre", "cubic meter")
1
>>> volume_conversion(3, "gallon", "cubic yard")
0.017814279
>>> volume_conversion(2, "cubic yard", "litre")
1529.1
>>> volume_conversion(4, "cubic foot", "cup")
473.396
>>> volume_conversion(1, "cup", "kilolitre")
0.000236588
>>> volume_conversion(4, "wrongUnit", "litre")
Traceback (most recent call last):
...
ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are:
cubic meter, litre, kilolitre, gallon, cubic yard, cubic foot, cup
"""
if from_type not in METRIC_CONVERSION:
raise ValueError(
f"Invalid 'from_type' value: {from_type!r} Supported values are:\n"
+ ", ".join(METRIC_CONVERSION)
)
if to_type not in METRIC_CONVERSION:
raise ValueError(
f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n"
+ ", ".join(METRIC_CONVERSION)
)
return (
value
* METRIC_CONVERSION[from_type].from_factor
* METRIC_CONVERSION[to_type].to_factor
)
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/bit_manipulation/binary_count_setbits.py | bit_manipulation/binary_count_setbits.py | def binary_count_setbits(a: int) -> int:
"""
Take in 1 integer, return a number that is
the number of 1's in binary representation of that number.
>>> binary_count_setbits(25)
3
>>> binary_count_setbits(36)
2
>>> binary_count_setbits(16)
1
>>> binary_count_setbits(58)
4
>>> binary_count_setbits(4294967295)
32
>>> binary_count_setbits(0)
0
>>> binary_count_setbits(-10)
Traceback (most recent call last):
...
ValueError: Input value must be a positive integer
>>> binary_count_setbits(0.8)
Traceback (most recent call last):
...
TypeError: Input value must be a 'int' type
>>> binary_count_setbits("0")
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
"""
if a < 0:
raise ValueError("Input value must be a positive integer")
elif isinstance(a, float):
raise TypeError("Input value must be a 'int' type")
return bin(a).count("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/bit_manipulation/binary_xor_operator.py | bit_manipulation/binary_xor_operator.py | # https://www.tutorialspoint.com/python3/bitwise_operators_example.htm
def binary_xor(a: int, b: int) -> str:
"""
Take in 2 integers, convert them to binary,
return a binary number that is the
result of a binary xor operation on the integers provided.
>>> binary_xor(25, 32)
'0b111001'
>>> binary_xor(37, 50)
'0b010111'
>>> binary_xor(21, 30)
'0b01011'
>>> binary_xor(58, 73)
'0b1110011'
>>> binary_xor(0, 255)
'0b11111111'
>>> binary_xor(256, 256)
'0b000000000'
>>> binary_xor(0, -1)
Traceback (most recent call last):
...
ValueError: the value of both inputs must be positive
>>> binary_xor(0, 1.1)
Traceback (most recent call last):
...
TypeError: 'float' object cannot be interpreted as an integer
>>> binary_xor("0", "1")
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
"""
if a < 0 or b < 0:
raise ValueError("the value of both inputs must be positive")
a_binary = str(bin(a))[2:] # remove the leading "0b"
b_binary = str(bin(b))[2:] # remove the leading "0b"
max_len = max(len(a_binary), len(b_binary))
return "0b" + "".join(
str(int(char_a != char_b))
for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len))
)
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/bit_manipulation/bitwise_addition_recursive.py | bit_manipulation/bitwise_addition_recursive.py | """
Calculates the sum of two non-negative integers using bitwise operators
Wikipedia explanation: https://en.wikipedia.org/wiki/Binary_number
"""
def bitwise_addition_recursive(number: int, other_number: int) -> int:
"""
>>> bitwise_addition_recursive(4, 5)
9
>>> bitwise_addition_recursive(8, 9)
17
>>> bitwise_addition_recursive(0, 4)
4
>>> bitwise_addition_recursive(4.5, 9)
Traceback (most recent call last):
...
TypeError: Both arguments MUST be integers!
>>> bitwise_addition_recursive('4', 9)
Traceback (most recent call last):
...
TypeError: Both arguments MUST be integers!
>>> bitwise_addition_recursive('4.5', 9)
Traceback (most recent call last):
...
TypeError: Both arguments MUST be integers!
>>> bitwise_addition_recursive(-1, 9)
Traceback (most recent call last):
...
ValueError: Both arguments MUST be non-negative!
>>> bitwise_addition_recursive(1, -9)
Traceback (most recent call last):
...
ValueError: Both arguments MUST be non-negative!
"""
if not isinstance(number, int) or not isinstance(other_number, int):
raise TypeError("Both arguments MUST be integers!")
if number < 0 or other_number < 0:
raise ValueError("Both arguments MUST be non-negative!")
bitwise_sum = number ^ other_number
carry = number & other_number
if carry == 0:
return bitwise_sum
return bitwise_addition_recursive(bitwise_sum, carry << 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/bit_manipulation/highest_set_bit.py | bit_manipulation/highest_set_bit.py | def get_highest_set_bit_position(number: int) -> int:
"""
Returns position of the highest set bit of a number.
Ref - https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious
>>> get_highest_set_bit_position(25)
5
>>> get_highest_set_bit_position(37)
6
>>> get_highest_set_bit_position(1)
1
>>> get_highest_set_bit_position(4)
3
>>> get_highest_set_bit_position(0)
0
>>> get_highest_set_bit_position(0.8)
Traceback (most recent call last):
...
TypeError: Input value must be an 'int' type
"""
if not isinstance(number, int):
raise TypeError("Input value must be an 'int' type")
position = 0
while number:
position += 1
number >>= 1
return position
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/bit_manipulation/count_number_of_one_bits.py | bit_manipulation/count_number_of_one_bits.py | from timeit import timeit
def get_set_bits_count_using_brian_kernighans_algorithm(number: int) -> int:
"""
Count the number of set bits in a 32 bit integer
>>> get_set_bits_count_using_brian_kernighans_algorithm(25)
3
>>> get_set_bits_count_using_brian_kernighans_algorithm(37)
3
>>> get_set_bits_count_using_brian_kernighans_algorithm(21)
3
>>> get_set_bits_count_using_brian_kernighans_algorithm(58)
4
>>> get_set_bits_count_using_brian_kernighans_algorithm(0)
0
>>> get_set_bits_count_using_brian_kernighans_algorithm(256)
1
>>> get_set_bits_count_using_brian_kernighans_algorithm(-1)
Traceback (most recent call last):
...
ValueError: the value of input must not be negative
"""
if number < 0:
raise ValueError("the value of input must not be negative")
result = 0
while number:
number &= number - 1
result += 1
return result
def get_set_bits_count_using_modulo_operator(number: int) -> int:
"""
Count the number of set bits in a 32 bit integer
>>> get_set_bits_count_using_modulo_operator(25)
3
>>> get_set_bits_count_using_modulo_operator(37)
3
>>> get_set_bits_count_using_modulo_operator(21)
3
>>> get_set_bits_count_using_modulo_operator(58)
4
>>> get_set_bits_count_using_modulo_operator(0)
0
>>> get_set_bits_count_using_modulo_operator(256)
1
>>> get_set_bits_count_using_modulo_operator(-1)
Traceback (most recent call last):
...
ValueError: the value of input must not be negative
"""
if number < 0:
raise ValueError("the value of input must not be negative")
result = 0
while number:
if number % 2 == 1:
result += 1
number >>= 1
return result
def benchmark() -> None:
"""
Benchmark code for comparing 2 functions, with different length int values.
Brian Kernighan's algorithm is consistently faster than using modulo_operator.
"""
def do_benchmark(number: int) -> None:
setup = "import __main__ as z"
print(f"Benchmark when {number = }:")
print(f"{get_set_bits_count_using_modulo_operator(number) = }")
timing = timeit(
f"z.get_set_bits_count_using_modulo_operator({number})", setup=setup
)
print(f"timeit() runs in {timing} seconds")
print(f"{get_set_bits_count_using_brian_kernighans_algorithm(number) = }")
timing = timeit(
f"z.get_set_bits_count_using_brian_kernighans_algorithm({number})",
setup=setup,
)
print(f"timeit() runs in {timing} seconds")
for number in (25, 37, 58, 0):
do_benchmark(number)
print()
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/bit_manipulation/power_of_4.py | bit_manipulation/power_of_4.py | """
Task:
Given a positive int number. Return True if this number is power of 4
or False otherwise.
Implementation notes: Use bit manipulation.
For example if the number is the power of 2 it's bits representation:
n = 0..100..00
n - 1 = 0..011..11
n & (n - 1) - no intersections = 0
If the number is a power of 4 then it should be a power of 2
and the set bit should be at an odd position.
"""
def power_of_4(number: int) -> bool:
"""
Return True if this number is power of 4 or False otherwise.
>>> power_of_4(0)
Traceback (most recent call last):
...
ValueError: number must be positive
>>> power_of_4(1)
True
>>> power_of_4(2)
False
>>> power_of_4(4)
True
>>> power_of_4(6)
False
>>> power_of_4(8)
False
>>> power_of_4(17)
False
>>> power_of_4(64)
True
>>> power_of_4(-1)
Traceback (most recent call last):
...
ValueError: number must be positive
>>> power_of_4(1.2)
Traceback (most recent call last):
...
TypeError: number must be an integer
"""
if not isinstance(number, int):
raise TypeError("number must be an integer")
if number <= 0:
raise ValueError("number must be positive")
if number & (number - 1) == 0:
c = 0
while number:
c += 1
number >>= 1
return c % 2 == 1
else:
return False
if __name__ == "__main__":
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/bit_manipulation/largest_pow_of_two_le_num.py | bit_manipulation/largest_pow_of_two_le_num.py | """
Author : Naman Sharma
Date : October 2, 2023
Task:
To Find the largest power of 2 less than or equal to a given number.
Implementation notes: Use bit manipulation.
We start from 1 & left shift the set bit to check if (res<<1)<=number.
Each left bit shift represents a pow of 2.
For example:
number: 15
res: 1 0b1
2 0b10
4 0b100
8 0b1000
16 0b10000 (Exit)
"""
def largest_pow_of_two_le_num(number: int) -> int:
"""
Return the largest power of two less than or equal to a number.
>>> largest_pow_of_two_le_num(0)
0
>>> largest_pow_of_two_le_num(1)
1
>>> largest_pow_of_two_le_num(-1)
0
>>> largest_pow_of_two_le_num(3)
2
>>> largest_pow_of_two_le_num(15)
8
>>> largest_pow_of_two_le_num(99)
64
>>> largest_pow_of_two_le_num(178)
128
>>> largest_pow_of_two_le_num(999999)
524288
>>> largest_pow_of_two_le_num(99.9)
Traceback (most recent call last):
...
TypeError: Input value must be a 'int' type
"""
if isinstance(number, float):
raise TypeError("Input value must be a 'int' type")
if number <= 0:
return 0
res = 1
while (res << 1) <= number:
res <<= 1
return res
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/bit_manipulation/gray_code_sequence.py | bit_manipulation/gray_code_sequence.py | def gray_code(bit_count: int) -> list:
"""
Takes in an integer n and returns a n-bit
gray code sequence
An n-bit gray code sequence is a sequence of 2^n
integers where:
a) Every integer is between [0,2^n -1] inclusive
b) The sequence begins with 0
c) An integer appears at most one times in the sequence
d)The binary representation of every pair of integers differ
by exactly one bit
e) The binary representation of first and last bit also
differ by exactly one bit
>>> gray_code(2)
[0, 1, 3, 2]
>>> gray_code(1)
[0, 1]
>>> gray_code(3)
[0, 1, 3, 2, 6, 7, 5, 4]
>>> gray_code(-1)
Traceback (most recent call last):
...
ValueError: The given input must be positive
>>> gray_code(10.6)
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for <<: 'int' and 'float'
"""
# bit count represents no. of bits in the gray code
if bit_count < 0:
raise ValueError("The given input must be positive")
# get the generated string sequence
sequence = gray_code_sequence_string(bit_count)
#
# convert them to integers
for i in range(len(sequence)):
sequence[i] = int(sequence[i], 2)
return sequence
def gray_code_sequence_string(bit_count: int) -> list:
"""
Will output the n-bit grey sequence as a
string of bits
>>> gray_code_sequence_string(2)
['00', '01', '11', '10']
>>> gray_code_sequence_string(1)
['0', '1']
"""
# The approach is a recursive one
# Base case achieved when either n = 0 or n=1
if bit_count == 0:
return ["0"]
if bit_count == 1:
return ["0", "1"]
seq_len = 1 << bit_count # defines the length of the sequence
# 1<< n is equivalent to 2^n
# recursive answer will generate answer for n-1 bits
smaller_sequence = gray_code_sequence_string(bit_count - 1)
sequence = []
# append 0 to first half of the smaller sequence generated
for i in range(seq_len // 2):
generated_no = "0" + smaller_sequence[i]
sequence.append(generated_no)
# append 1 to second half ... start from the end of the list
for i in reversed(range(seq_len // 2)):
generated_no = "1" + smaller_sequence[i]
sequence.append(generated_no)
return sequence
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/bit_manipulation/is_power_of_two.py | bit_manipulation/is_power_of_two.py | """
Author : Alexander Pantyukhin
Date : November 1, 2022
Task:
Given a positive int number. Return True if this number is power of 2
or False otherwise.
Implementation notes: Use bit manipulation.
For example if the number is the power of two it's bits representation:
n = 0..100..00
n - 1 = 0..011..11
n & (n - 1) - no intersections = 0
"""
def is_power_of_two(number: int) -> bool:
"""
Return True if this number is power of 2 or False otherwise.
>>> is_power_of_two(0)
True
>>> is_power_of_two(1)
True
>>> is_power_of_two(2)
True
>>> is_power_of_two(4)
True
>>> is_power_of_two(6)
False
>>> is_power_of_two(8)
True
>>> is_power_of_two(17)
False
>>> is_power_of_two(-1)
Traceback (most recent call last):
...
ValueError: number must not be negative
>>> is_power_of_two(1.2)
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for &: 'float' and 'float'
# Test all powers of 2 from 0 to 10,000
>>> all(is_power_of_two(int(2 ** i)) for i in range(10000))
True
"""
if number < 0:
raise ValueError("number must not be negative")
return number & (number - 1) == 0
if __name__ == "__main__":
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/bit_manipulation/find_unique_number.py | bit_manipulation/find_unique_number.py | def find_unique_number(arr: list[int]) -> int:
"""
Given a list of integers where every element appears twice except for one,
this function returns the element that appears only once using bitwise XOR.
>>> find_unique_number([1, 1, 2, 2, 3])
3
>>> find_unique_number([4, 5, 4, 6, 6])
5
>>> find_unique_number([7])
7
>>> find_unique_number([10, 20, 10])
20
>>> find_unique_number([])
Traceback (most recent call last):
...
ValueError: input list must not be empty
>>> find_unique_number([1, 'a', 1])
Traceback (most recent call last):
...
TypeError: all elements must be integers
"""
if not arr:
raise ValueError("input list must not be empty")
if not all(isinstance(x, int) for x in arr):
raise TypeError("all elements must be integers")
result = 0
for num in arr:
result ^= num
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/bit_manipulation/is_even.py | bit_manipulation/is_even.py | def is_even(number: int) -> bool:
"""
return true if the input integer is even
Explanation: Lets take a look at the following decimal to binary conversions
2 => 10
14 => 1110
100 => 1100100
3 => 11
13 => 1101
101 => 1100101
from the above examples we can observe that
for all the odd integers there is always 1 set bit at the end
also, 1 in binary can be represented as 001, 00001, or 0000001
so for any odd integer n => n&1 is always equals 1 else the integer is even
>>> is_even(1)
False
>>> is_even(4)
True
>>> is_even(9)
False
>>> is_even(15)
False
>>> is_even(40)
True
>>> is_even(100)
True
>>> is_even(101)
False
"""
return number & 1 == 0
if __name__ == "__main__":
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/bit_manipulation/single_bit_manipulation_operations.py | bit_manipulation/single_bit_manipulation_operations.py | #!/usr/bin/env python3
"""Provide the functionality to manipulate a single bit."""
def set_bit(number: int, position: int) -> int:
"""
Set the bit at position to 1.
Details: perform bitwise or for given number and X.
Where X is a number with all the bits - zeroes and bit on given
position - one.
>>> set_bit(0b1101, 1) # 0b1111
15
>>> set_bit(0b0, 5) # 0b100000
32
>>> set_bit(0b1111, 1) # 0b1111
15
"""
return number | (1 << position)
def clear_bit(number: int, position: int) -> int:
"""
Set the bit at position to 0.
Details: perform bitwise and for given number and X.
Where X is a number with all the bits - ones and bit on given
position - zero.
>>> clear_bit(0b10010, 1) # 0b10000
16
>>> clear_bit(0b0, 5) # 0b0
0
"""
return number & ~(1 << position)
def flip_bit(number: int, position: int) -> int:
"""
Flip the bit at position.
Details: perform bitwise xor for given number and X.
Where X is a number with all the bits - zeroes and bit on given
position - one.
>>> flip_bit(0b101, 1) # 0b111
7
>>> flip_bit(0b101, 0) # 0b100
4
"""
return number ^ (1 << position)
def is_bit_set(number: int, position: int) -> bool:
"""
Is the bit at position set?
Details: Shift the bit at position to be the first (smallest) bit.
Then check if the first bit is set by anding the shifted number with 1.
>>> is_bit_set(0b1010, 0)
False
>>> is_bit_set(0b1010, 1)
True
>>> is_bit_set(0b1010, 2)
False
>>> is_bit_set(0b1010, 3)
True
>>> is_bit_set(0b0, 17)
False
"""
return ((number >> position) & 1) == 1
def get_bit(number: int, position: int) -> int:
"""
Get the bit at the given position
Details: perform bitwise and for the given number and X,
Where X is a number with all the bits - zeroes and bit on given position - one.
If the result is not equal to 0, then the bit on the given position is 1, else 0.
>>> get_bit(0b1010, 0)
0
>>> get_bit(0b1010, 1)
1
>>> get_bit(0b1010, 2)
0
>>> get_bit(0b1010, 3)
1
"""
return int((number & (1 << position)) != 0)
if __name__ == "__main__":
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/bit_manipulation/excess_3_code.py | bit_manipulation/excess_3_code.py | def excess_3_code(number: int) -> str:
"""
Find excess-3 code of integer base 10.
Add 3 to all digits in a decimal number then convert to a binary-coded decimal.
https://en.wikipedia.org/wiki/Excess-3
>>> excess_3_code(0)
'0b0011'
>>> excess_3_code(3)
'0b0110'
>>> excess_3_code(2)
'0b0101'
>>> excess_3_code(20)
'0b01010011'
>>> excess_3_code(120)
'0b010001010011'
"""
num = ""
for digit in str(max(0, number)):
num += str(bin(int(digit) + 3))[2:].zfill(4)
return "0b" + num
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/bit_manipulation/numbers_different_signs.py | bit_manipulation/numbers_different_signs.py | """
Author : Alexander Pantyukhin
Date : November 30, 2022
Task:
Given two int numbers. Return True these numbers have opposite signs
or False otherwise.
Implementation notes: Use bit manipulation.
Use XOR for two numbers.
"""
def different_signs(num1: int, num2: int) -> bool:
"""
Return True if numbers have opposite signs False otherwise.
>>> different_signs(1, -1)
True
>>> different_signs(1, 1)
False
>>> different_signs(1000000000000000000000000000, -1000000000000000000000000000)
True
>>> different_signs(-1000000000000000000000000000, 1000000000000000000000000000)
True
>>> different_signs(50, 278)
False
>>> different_signs(0, 2)
False
>>> different_signs(2, 0)
False
"""
return num1 ^ num2 < 0
if __name__ == "__main__":
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/bit_manipulation/missing_number.py | bit_manipulation/missing_number.py | def find_missing_number(nums: list[int]) -> int:
"""
Finds the missing number in a list of consecutive integers.
Args:
nums: A list of integers.
Returns:
The missing number.
Example:
>>> find_missing_number([0, 1, 3, 4])
2
>>> find_missing_number([4, 3, 1, 0])
2
>>> find_missing_number([-4, -3, -1, 0])
-2
>>> find_missing_number([-2, 2, 1, 3, 0])
-1
>>> find_missing_number([1, 3, 4, 5, 6])
2
>>> find_missing_number([6, 5, 4, 2, 1])
3
>>> find_missing_number([6, 1, 5, 3, 4])
2
"""
low = min(nums)
high = max(nums)
missing_number = high
for i in range(low, high):
missing_number ^= i ^ nums[i - low]
return missing_number
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/bit_manipulation/find_previous_power_of_two.py | bit_manipulation/find_previous_power_of_two.py | def find_previous_power_of_two(number: int) -> int:
"""
Find the largest power of two that is less than or equal to a given integer.
https://stackoverflow.com/questions/1322510
>>> [find_previous_power_of_two(i) for i in range(18)]
[0, 1, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 16, 16]
>>> find_previous_power_of_two(-5)
Traceback (most recent call last):
...
ValueError: Input must be a non-negative integer
>>> find_previous_power_of_two(10.5)
Traceback (most recent call last):
...
ValueError: Input must be a non-negative integer
"""
if not isinstance(number, int) or number < 0:
raise ValueError("Input must be a non-negative integer")
if number == 0:
return 0
power = 1
while power <= number:
power <<= 1 # Equivalent to multiplying by 2
return power >> 1 if number > 1 else 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/bit_manipulation/swap_all_odd_and_even_bits.py | bit_manipulation/swap_all_odd_and_even_bits.py | def show_bits(before: int, after: int) -> str:
"""
>>> print(show_bits(0, 0xFFFF))
0: 00000000
65535: 1111111111111111
"""
return f"{before:>5}: {before:08b}\n{after:>5}: {after:08b}"
def swap_odd_even_bits(num: int) -> int:
"""
1. We use bitwise AND operations to separate the even bits (0, 2, 4, 6, etc.) and
odd bits (1, 3, 5, 7, etc.) in the input number.
2. We then right-shift the even bits by 1 position and left-shift the odd bits by
1 position to swap them.
3. Finally, we combine the swapped even and odd bits using a bitwise OR operation
to obtain the final result.
>>> print(show_bits(0, swap_odd_even_bits(0)))
0: 00000000
0: 00000000
>>> print(show_bits(1, swap_odd_even_bits(1)))
1: 00000001
2: 00000010
>>> print(show_bits(2, swap_odd_even_bits(2)))
2: 00000010
1: 00000001
>>> print(show_bits(3, swap_odd_even_bits(3)))
3: 00000011
3: 00000011
>>> print(show_bits(4, swap_odd_even_bits(4)))
4: 00000100
8: 00001000
>>> print(show_bits(5, swap_odd_even_bits(5)))
5: 00000101
10: 00001010
>>> print(show_bits(6, swap_odd_even_bits(6)))
6: 00000110
9: 00001001
>>> print(show_bits(23, swap_odd_even_bits(23)))
23: 00010111
43: 00101011
"""
# Get all even bits - 0xAAAAAAAA is a 32-bit number with all even bits set to 1
even_bits = num & 0xAAAAAAAA
# Get all odd bits - 0x55555555 is a 32-bit number with all odd bits set to 1
odd_bits = num & 0x55555555
# Right shift even bits and left shift odd bits and swap them
return even_bits >> 1 | odd_bits << 1
if __name__ == "__main__":
import doctest
doctest.testmod()
for i in (-1, 0, 1, 2, 3, 4, 23, 24):
print(show_bits(i, swap_odd_even_bits(i)), "\n")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/bit_manipulation/binary_shifts.py | bit_manipulation/binary_shifts.py | # Information on binary shifts:
# https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types
# https://www.interviewcake.com/concept/java/bit-shift
def logical_left_shift(number: int, shift_amount: int) -> str:
"""
Take in 2 positive integers.
'number' is the integer to be logically left shifted 'shift_amount' times.
i.e. (number << shift_amount)
Return the shifted binary representation.
>>> logical_left_shift(0, 1)
'0b00'
>>> logical_left_shift(1, 1)
'0b10'
>>> logical_left_shift(1, 5)
'0b100000'
>>> logical_left_shift(17, 2)
'0b1000100'
>>> logical_left_shift(1983, 4)
'0b111101111110000'
>>> logical_left_shift(1, -1)
Traceback (most recent call last):
...
ValueError: both inputs must be positive integers
"""
if number < 0 or shift_amount < 0:
raise ValueError("both inputs must be positive integers")
binary_number = str(bin(number))
binary_number += "0" * shift_amount
return binary_number
def logical_right_shift(number: int, shift_amount: int) -> str:
"""
Take in positive 2 integers.
'number' is the integer to be logically right shifted 'shift_amount' times.
i.e. (number >>> shift_amount)
Return the shifted binary representation.
>>> logical_right_shift(0, 1)
'0b0'
>>> logical_right_shift(1, 1)
'0b0'
>>> logical_right_shift(1, 5)
'0b0'
>>> logical_right_shift(17, 2)
'0b100'
>>> logical_right_shift(1983, 4)
'0b1111011'
>>> logical_right_shift(1, -1)
Traceback (most recent call last):
...
ValueError: both inputs must be positive integers
"""
if number < 0 or shift_amount < 0:
raise ValueError("both inputs must be positive integers")
binary_number = str(bin(number))[2:]
if shift_amount >= len(binary_number):
return "0b0"
shifted_binary_number = binary_number[: len(binary_number) - shift_amount]
return "0b" + shifted_binary_number
def arithmetic_right_shift(number: int, shift_amount: int) -> str:
"""
Take in 2 integers.
'number' is the integer to be arithmetically right shifted 'shift_amount' times.
i.e. (number >> shift_amount)
Return the shifted binary representation.
>>> arithmetic_right_shift(0, 1)
'0b00'
>>> arithmetic_right_shift(1, 1)
'0b00'
>>> arithmetic_right_shift(-1, 1)
'0b11'
>>> arithmetic_right_shift(17, 2)
'0b000100'
>>> arithmetic_right_shift(-17, 2)
'0b111011'
>>> arithmetic_right_shift(-1983, 4)
'0b111110000100'
"""
if number >= 0: # Get binary representation of positive number
binary_number = "0" + str(bin(number)).strip("-")[2:]
else: # Get binary (2's complement) representation of negative number
binary_number_length = len(bin(number)[3:]) # Find 2's complement of number
binary_number = bin(abs(number) - (1 << binary_number_length))[3:]
binary_number = (
"1" + "0" * (binary_number_length - len(binary_number)) + binary_number
)
if shift_amount >= len(binary_number):
return "0b" + binary_number[0] * len(binary_number)
return (
"0b"
+ binary_number[0] * shift_amount
+ binary_number[: len(binary_number) - shift_amount]
)
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/bit_manipulation/__init__.py | bit_manipulation/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/bit_manipulation/count_1s_brian_kernighan_method.py | bit_manipulation/count_1s_brian_kernighan_method.py | def get_1s_count(number: int) -> int:
"""
Count the number of set bits in a 32 bit integer using Brian Kernighan's way.
Ref - https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
>>> get_1s_count(25)
3
>>> get_1s_count(37)
3
>>> get_1s_count(21)
3
>>> get_1s_count(58)
4
>>> get_1s_count(0)
0
>>> get_1s_count(256)
1
>>> get_1s_count(-1)
Traceback (most recent call last):
...
ValueError: Input must be a non-negative integer
>>> get_1s_count(0.8)
Traceback (most recent call last):
...
ValueError: Input must be a non-negative integer
>>> get_1s_count("25")
Traceback (most recent call last):
...
ValueError: Input must be a non-negative integer
"""
if not isinstance(number, int) or number < 0:
raise ValueError("Input must be a non-negative integer")
count = 0
while number:
# This way we arrive at next set bit (next 1) instead of looping
# through each bit and checking for 1s hence the
# loop won't run 32 times it will only run the number of `1` times
number &= number - 1
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/bit_manipulation/binary_and_operator.py | bit_manipulation/binary_and_operator.py | # https://www.tutorialspoint.com/python3/bitwise_operators_example.htm
def binary_and(a: int, b: int) -> str:
"""
Take in 2 integers, convert them to binary,
return a binary number that is the
result of a binary and operation on the integers provided.
>>> binary_and(25, 32)
'0b000000'
>>> binary_and(37, 50)
'0b100000'
>>> binary_and(21, 30)
'0b10100'
>>> binary_and(58, 73)
'0b0001000'
>>> binary_and(0, 255)
'0b00000000'
>>> binary_and(256, 256)
'0b100000000'
>>> binary_and(0, -1)
Traceback (most recent call last):
...
ValueError: the value of both inputs must be positive
>>> binary_and(0, 1.1)
Traceback (most recent call last):
...
ValueError: Unknown format code 'b' for object of type 'float'
>>> binary_and("0", "1")
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
"""
if a < 0 or b < 0:
raise ValueError("the value of both inputs must be positive")
a_binary = format(a, "b")
b_binary = format(b, "b")
max_len = max(len(a_binary), len(b_binary))
return "0b" + "".join(
str(int(char_a == "1" and char_b == "1"))
for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len))
)
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/bit_manipulation/binary_count_trailing_zeros.py | bit_manipulation/binary_count_trailing_zeros.py | from math import log2
def binary_count_trailing_zeros(a: int) -> int:
"""
Take in 1 integer, return a number that is
the number of trailing zeros in binary representation of that number.
>>> binary_count_trailing_zeros(25)
0
>>> binary_count_trailing_zeros(36)
2
>>> binary_count_trailing_zeros(16)
4
>>> binary_count_trailing_zeros(58)
1
>>> binary_count_trailing_zeros(4294967296)
32
>>> binary_count_trailing_zeros(0)
0
>>> binary_count_trailing_zeros(-10)
Traceback (most recent call last):
...
ValueError: Input value must be a positive integer
>>> binary_count_trailing_zeros(0.8)
Traceback (most recent call last):
...
TypeError: Input value must be a 'int' type
>>> binary_count_trailing_zeros("0")
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
"""
if a < 0:
raise ValueError("Input value must be a positive integer")
elif isinstance(a, float):
raise TypeError("Input value must be a 'int' type")
return 0 if (a == 0) else int(log2(a & -a))
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/bit_manipulation/index_of_rightmost_set_bit.py | bit_manipulation/index_of_rightmost_set_bit.py | # Reference: https://www.geeksforgeeks.org/position-of-rightmost-set-bit/
def get_index_of_rightmost_set_bit(number: int) -> int:
"""
Take in a positive integer 'number'.
Returns the zero-based index of first set bit in that 'number' from right.
Returns -1, If no set bit found.
>>> get_index_of_rightmost_set_bit(0)
-1
>>> get_index_of_rightmost_set_bit(5)
0
>>> get_index_of_rightmost_set_bit(36)
2
>>> get_index_of_rightmost_set_bit(8)
3
>>> get_index_of_rightmost_set_bit(-18)
Traceback (most recent call last):
...
ValueError: Input must be a non-negative integer
>>> get_index_of_rightmost_set_bit('test')
Traceback (most recent call last):
...
ValueError: Input must be a non-negative integer
>>> get_index_of_rightmost_set_bit(1.25)
Traceback (most recent call last):
...
ValueError: Input must be a non-negative integer
"""
if not isinstance(number, int) or number < 0:
raise ValueError("Input must be a non-negative integer")
intermediate = number & ~(number - 1)
index = 0
while intermediate:
intermediate >>= 1
index += 1
return index - 1
if __name__ == "__main__":
"""
Finding the index of rightmost set bit has some very peculiar use-cases,
especially in finding missing or/and repeating numbers in a list of
positive integers.
"""
import doctest
doctest.testmod(verbose=True)
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/bit_manipulation/reverse_bits.py | bit_manipulation/reverse_bits.py | def get_reverse_bit_string(number: int) -> str:
"""
Return the reverse bit string of a 32 bit integer
>>> get_reverse_bit_string(9)
'10010000000000000000000000000000'
>>> get_reverse_bit_string(43)
'11010100000000000000000000000000'
>>> get_reverse_bit_string(2873)
'10011100110100000000000000000000'
>>> get_reverse_bit_string(2550136832)
'00000000000000000000000000011001'
>>> get_reverse_bit_string("this is not a number")
Traceback (most recent call last):
...
TypeError: operation can not be conducted on an object of type str
"""
if not isinstance(number, int):
msg = (
"operation can not be conducted on an object of type "
f"{type(number).__name__}"
)
raise TypeError(msg)
bit_string = ""
for _ in range(32):
bit_string += str(number % 2)
number >>= 1
return bit_string
def reverse_bit(number: int) -> int:
"""
Take in a 32 bit integer, reverse its bits, return a 32 bit integer result
>>> reverse_bit(25)
2550136832
>>> reverse_bit(37)
2751463424
>>> reverse_bit(21)
2818572288
>>> reverse_bit(58)
1543503872
>>> reverse_bit(0)
0
>>> reverse_bit(256)
8388608
>>> reverse_bit(2550136832)
25
>>> reverse_bit(-1)
Traceback (most recent call last):
...
ValueError: The value of input must be non-negative
>>> reverse_bit(1.1)
Traceback (most recent call last):
...
TypeError: Input value must be an 'int' type
>>> reverse_bit("0")
Traceback (most recent call last):
...
TypeError: Input value must be an 'int' type
"""
if not isinstance(number, int):
raise TypeError("Input value must be an 'int' type")
if number < 0:
raise ValueError("The value of input must be non-negative")
result = 0
# iterator over [0 to 31], since we are dealing with a 32 bit integer
for _ in range(32):
# left shift the bits by unity
result <<= 1
# get the end bit
end_bit = number & 1
# right shift the bits by unity
number >>= 1
# add that bit to our answer
result |= end_bit
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/bit_manipulation/binary_or_operator.py | bit_manipulation/binary_or_operator.py | # https://www.tutorialspoint.com/python3/bitwise_operators_example.htm
def binary_or(a: int, b: int) -> str:
"""
Take in 2 integers, convert them to binary, and return a binary number that is the
result of a binary or operation on the integers provided.
>>> binary_or(25, 32)
'0b111001'
>>> binary_or(37, 50)
'0b110111'
>>> binary_or(21, 30)
'0b11111'
>>> binary_or(58, 73)
'0b1111011'
>>> binary_or(0, 255)
'0b11111111'
>>> binary_or(0, 256)
'0b100000000'
>>> binary_or(0, -1)
Traceback (most recent call last):
...
ValueError: the value of both inputs must be positive
>>> binary_or(0, 1.1)
Traceback (most recent call last):
...
TypeError: 'float' object cannot be interpreted as an integer
>>> binary_or("0", "1")
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
"""
if a < 0 or b < 0:
raise ValueError("the value of both inputs must be positive")
a_binary = str(bin(a))[2:] # remove the leading "0b"
b_binary = str(bin(b))[2:]
max_len = max(len(a_binary), len(b_binary))
return "0b" + "".join(
str(int("1" in (char_a, char_b)))
for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len))
)
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/bit_manipulation/binary_coded_decimal.py | bit_manipulation/binary_coded_decimal.py | def binary_coded_decimal(number: int) -> str:
"""
Find binary coded decimal (bcd) of integer base 10.
Each digit of the number is represented by a 4-bit binary.
Example:
>>> binary_coded_decimal(-2)
'0b0000'
>>> binary_coded_decimal(-1)
'0b0000'
>>> binary_coded_decimal(0)
'0b0000'
>>> binary_coded_decimal(3)
'0b0011'
>>> binary_coded_decimal(2)
'0b0010'
>>> binary_coded_decimal(12)
'0b00010010'
>>> binary_coded_decimal(987)
'0b100110000111'
"""
return "0b" + "".join(
str(bin(int(digit)))[2:].zfill(4) for digit in str(max(0, number))
)
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/bit_manipulation/binary_twos_complement.py | bit_manipulation/binary_twos_complement.py | # Information on 2's complement: https://en.wikipedia.org/wiki/Two%27s_complement
def twos_complement(number: int) -> str:
"""
Take in a negative integer 'number'.
Return the two's complement representation of 'number'.
>>> twos_complement(0)
'0b0'
>>> twos_complement(-1)
'0b11'
>>> twos_complement(-5)
'0b1011'
>>> twos_complement(-17)
'0b101111'
>>> twos_complement(-207)
'0b100110001'
>>> twos_complement(1)
Traceback (most recent call last):
...
ValueError: input must be a negative integer
"""
if number > 0:
raise ValueError("input must be a negative integer")
binary_number_length = len(bin(number)[3:])
twos_complement_number = bin(abs(number) - (1 << binary_number_length))[3:]
twos_complement_number = (
(
"1"
+ "0" * (binary_number_length - len(twos_complement_number))
+ twos_complement_number
)
if number < 0
else "0"
)
return "0b" + twos_complement_number
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/hashes/sha1.py | hashes/sha1.py | """
Implementation of the SHA1 hash function and gives utilities to find hash of string or
hash of text from a file. Also contains a Test class to verify that the generated hash
matches what is returned by the hashlib library
Usage: python sha1.py --string "Hello World!!"
python sha1.py --file "hello_world.txt"
When run without any arguments, it prints the hash of the string "Hello World!!
Welcome to Cryptography"
SHA1 hash or SHA1 sum of a string is a cryptographic function, which means it is easy
to calculate forwards but extremely difficult to calculate backwards. What this means
is you can easily calculate the hash of a string, but it is extremely difficult to know
the original string if you have its hash. This property is useful for communicating
securely, send encrypted messages and is very useful in payment systems, blockchain and
cryptocurrency etc.
The algorithm as described in the reference:
First we start with a message. The message is padded and the length of the message
is added to the end. It is then split into blocks of 512 bits or 64 bytes. The blocks
are then processed one at a time. Each block must be expanded and compressed.
The value after each compression is added to a 160-bit buffer called the current hash
state. After the last block is processed, the current hash state is returned as
the final hash.
Reference: https://deadhacker.com/2006/02/21/sha-1-illustrated/
"""
import argparse
import hashlib # hashlib is only used inside the Test class
import struct
class SHA1Hash:
"""
Class to contain the entire pipeline for SHA1 hashing algorithm
>>> SHA1Hash(bytes('Allan', 'utf-8')).final_hash()
'872af2d8ac3d8695387e7c804bf0e02c18df9e6e'
"""
def __init__(self, data):
"""
Initiates the variables data and h. h is a list of 5 8-digit hexadecimal
numbers corresponding to
(1732584193, 4023233417, 2562383102, 271733878, 3285377520)
respectively. We will start with this as a message digest. 0x is how you write
hexadecimal numbers in Python
"""
self.data = data
self.h = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
@staticmethod
def rotate(n, b):
"""
Static method to be used inside other methods. Left rotates n by b.
>>> SHA1Hash('').rotate(12,2)
48
"""
return ((n << b) | (n >> (32 - b))) & 0xFFFFFFFF
def padding(self):
"""
Pads the input message with zeros so that padded_data has 64 bytes or 512 bits
"""
padding = b"\x80" + b"\x00" * (63 - (len(self.data) + 8) % 64)
padded_data = self.data + padding + struct.pack(">Q", 8 * len(self.data))
return padded_data
def split_blocks(self):
"""
Returns a list of bytestrings each of length 64
"""
return [
self.padded_data[i : i + 64] for i in range(0, len(self.padded_data), 64)
]
# @staticmethod
def expand_block(self, block):
"""
Takes a bytestring-block of length 64, unpacks it to a list of integers and
returns a list of 80 integers after some bit operations
"""
w = list(struct.unpack(">16L", block)) + [0] * 64
for i in range(16, 80):
w[i] = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1)
return w
def final_hash(self):
"""
Calls all the other methods to process the input. Pads the data, then splits
into blocks and then does a series of operations for each block (including
expansion).
For each block, the variable h that was initialized is copied to a,b,c,d,e
and these 5 variables a,b,c,d,e undergo several changes. After all the blocks
are processed, these 5 variables are pairwise added to h ie a to h[0], b to h[1]
and so on. This h becomes our final hash which is returned.
"""
self.padded_data = self.padding()
self.blocks = self.split_blocks()
for block in self.blocks:
expanded_block = self.expand_block(block)
a, b, c, d, e = self.h
for i in range(80):
if 0 <= i < 20:
f = (b & c) | ((~b) & d)
k = 0x5A827999
elif 20 <= i < 40:
f = b ^ c ^ d
k = 0x6ED9EBA1
elif 40 <= i < 60:
f = (b & c) | (b & d) | (c & d)
k = 0x8F1BBCDC
elif 60 <= i < 80:
f = b ^ c ^ d
k = 0xCA62C1D6
a, b, c, d, e = (
self.rotate(a, 5) + f + e + k + expanded_block[i] & 0xFFFFFFFF,
a,
self.rotate(b, 30),
c,
d,
)
self.h = (
self.h[0] + a & 0xFFFFFFFF,
self.h[1] + b & 0xFFFFFFFF,
self.h[2] + c & 0xFFFFFFFF,
self.h[3] + d & 0xFFFFFFFF,
self.h[4] + e & 0xFFFFFFFF,
)
return ("{:08x}" * 5).format(*self.h)
def test_sha1_hash():
msg = b"Test String"
assert SHA1Hash(msg).final_hash() == hashlib.sha1(msg).hexdigest() # noqa: S324
def main():
"""
Provides option 'string' or 'file' to take input and prints the calculated SHA1
hash. unittest.main() has been commented out because we probably don't want to run
the test each time.
"""
# unittest.main()
parser = argparse.ArgumentParser(description="Process some strings or files")
parser.add_argument(
"--string",
dest="input_string",
default="Hello World!! Welcome to Cryptography",
help="Hash the string",
)
parser.add_argument("--file", dest="input_file", help="Hash contents of a file")
args = parser.parse_args()
input_string = args.input_string
# In any case hash input should be a bytestring
if args.input_file:
with open(args.input_file, "rb") as f:
hash_input = f.read()
else:
hash_input = bytes(input_string, "utf-8")
print(SHA1Hash(hash_input).final_hash())
if __name__ == "__main__":
main()
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/hashes/luhn.py | hashes/luhn.py | """Luhn Algorithm"""
from __future__ import annotations
def is_luhn(string: str) -> bool:
"""
Perform Luhn validation on an input string
Algorithm:
* Double every other digit starting from 2nd last digit.
* Subtract 9 if number is greater than 9.
* Sum the numbers
*
>>> test_cases = (79927398710, 79927398711, 79927398712, 79927398713,
... 79927398714, 79927398715, 79927398716, 79927398717, 79927398718,
... 79927398719)
>>> [is_luhn(str(test_case)) for test_case in test_cases]
[False, False, False, True, False, False, False, False, False, False]
"""
check_digit: int
_vector: list[str] = list(string)
__vector, check_digit = _vector[:-1], int(_vector[-1])
vector: list[int] = [int(digit) for digit in __vector]
vector.reverse()
for i, digit in enumerate(vector):
if i & 1 == 0:
doubled: int = digit * 2
if doubled > 9:
doubled -= 9
check_digit += doubled
else:
check_digit += digit
return check_digit % 10 == 0
if __name__ == "__main__":
import doctest
doctest.testmod()
assert is_luhn("79927398713")
assert not is_luhn("79927398714")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/hashes/adler32.py | hashes/adler32.py | """
Adler-32 is a checksum algorithm which was invented by Mark Adler in 1995.
Compared to a cyclic redundancy check of the same length, it trades reliability for
speed (preferring the latter).
Adler-32 is more reliable than Fletcher-16, and slightly less reliable than
Fletcher-32.[2]
source: https://en.wikipedia.org/wiki/Adler-32
"""
MOD_ADLER = 65521
def adler32(plain_text: str) -> int:
"""
Function implements adler-32 hash.
Iterates and evaluates a new value for each character
>>> adler32('Algorithms')
363791387
>>> adler32('go adler em all')
708642122
"""
a = 1
b = 0
for plain_chr in plain_text:
a = (a + ord(plain_chr)) % MOD_ADLER
b = (b + a) % MOD_ADLER
return (b << 16) | a
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/hashes/elf.py | hashes/elf.py | def elf_hash(data: str) -> int:
"""
Implementation of ElfHash Algorithm, a variant of PJW hash function.
>>> elf_hash('lorem ipsum')
253956621
"""
hash_ = x = 0
for letter in data:
hash_ = (hash_ << 4) + ord(letter)
x = hash_ & 0xF0000000
if x != 0:
hash_ ^= x >> 24
hash_ &= ~x
return hash_
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/hashes/djb2.py | hashes/djb2.py | """
This algorithm (k=33) was first reported by Dan Bernstein many years ago in comp.lang.c
Another version of this algorithm (now favored by Bernstein) uses xor:
hash(i) = hash(i - 1) * 33 ^ str[i];
First Magic constant 33:
It has never been adequately explained.
It's magic because it works better than many other constants, prime or not.
Second Magic Constant 5381:
1. odd number
2. prime number
3. deficient number
4. 001/010/100/000/101 b
source: http://www.cse.yorku.ca/~oz/hash.html
"""
def djb2(s: str) -> int:
"""
Implementation of djb2 hash algorithm that
is popular because of it's magic constants.
>>> djb2('Algorithms')
3782405311
>>> djb2('scramble bits')
1609059040
"""
hash_value = 5381
for x in s:
hash_value = ((hash_value << 5) + hash_value) + ord(x)
return hash_value & 0xFFFFFFFF
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/hashes/__init__.py | hashes/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/hashes/sdbm.py | hashes/sdbm.py | """
This algorithm was created for sdbm (a public-domain reimplementation of ndbm)
database library.
It was found to do well in scrambling bits, causing better distribution of the keys
and fewer splits.
It also happens to be a good general hashing function with good distribution.
The actual function (pseudo code) is:
for i in i..len(str):
hash(i) = hash(i - 1) * 65599 + str[i];
What is included below is the faster version used in gawk. [there is even a faster,
duff-device version]
The magic constant 65599 was picked out of thin air while experimenting with
different constants.
It turns out to be a prime.
This is one of the algorithms used in berkeley db (see sleepycat) and elsewhere.
source: http://www.cse.yorku.ca/~oz/hash.html
"""
def sdbm(plain_text: str) -> int:
"""
Function implements sdbm hash, easy to use, great for bits scrambling.
iterates over each character in the given string and applies function to each of
them.
>>> sdbm('Algorithms')
1462174910723540325254304520539387479031000036
>>> sdbm('scramble bits')
730247649148944819640658295400555317318720608290373040936089
"""
hash_value = 0
for plain_chr in plain_text:
hash_value = (
ord(plain_chr) + (hash_value << 6) + (hash_value << 16) - hash_value
)
return hash_value
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/hashes/fletcher16.py | hashes/fletcher16.py | """
The Fletcher checksum is an algorithm for computing a position-dependent
checksum devised by John G. Fletcher (1934-2012) at Lawrence Livermore Labs
in the late 1970s.[1] The objective of the Fletcher checksum was to
provide error-detection properties approaching those of a cyclic
redundancy check but with the lower computational effort associated
with summation techniques.
Source: https://en.wikipedia.org/wiki/Fletcher%27s_checksum
"""
def fletcher16(text: str) -> int:
"""
Loop through every character in the data and add to two sums.
>>> fletcher16('hello world')
6752
>>> fletcher16('onethousandfourhundredthirtyfour')
28347
>>> fletcher16('The quick brown fox jumps over the lazy dog.')
5655
"""
data = bytes(text, "ascii")
sum1 = 0
sum2 = 0
for character in data:
sum1 = (sum1 + character) % 255
sum2 = (sum1 + sum2) % 255
return (sum2 << 8) | sum1
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/hashes/md5.py | hashes/md5.py | """
The MD5 algorithm is a hash function that's commonly used as a checksum to
detect data corruption. The algorithm works by processing a given message in
blocks of 512 bits, padding the message as needed. It uses the blocks to operate
a 128-bit state and performs a total of 64 such operations. Note that all values
are little-endian, so inputs are converted as needed.
Although MD5 was used as a cryptographic hash function in the past, it's since
been cracked, so it shouldn't be used for security purposes.
For more info, see https://en.wikipedia.org/wiki/MD5
"""
from collections.abc import Generator
from math import sin
def to_little_endian(string_32: bytes) -> bytes:
"""
Converts the given string to little-endian in groups of 8 chars.
Arguments:
string_32 {[string]} -- [32-char string]
Raises:
ValueError -- [input is not 32 char]
Returns:
32-char little-endian string
>>> to_little_endian(b'1234567890abcdfghijklmnopqrstuvw')
b'pqrstuvwhijklmno90abcdfg12345678'
>>> to_little_endian(b'1234567890')
Traceback (most recent call last):
...
ValueError: Input must be of length 32
"""
if len(string_32) != 32:
raise ValueError("Input must be of length 32")
little_endian = b""
for i in [3, 2, 1, 0]:
little_endian += string_32[8 * i : 8 * i + 8]
return little_endian
def reformat_hex(i: int) -> bytes:
"""
Converts the given non-negative integer to hex string.
Example: Suppose the input is the following:
i = 1234
The input is 0x000004d2 in hex, so the little-endian hex string is
"d2040000".
Arguments:
i {[int]} -- [integer]
Raises:
ValueError -- [input is negative]
Returns:
8-char little-endian hex string
>>> reformat_hex(1234)
b'd2040000'
>>> reformat_hex(666)
b'9a020000'
>>> reformat_hex(0)
b'00000000'
>>> reformat_hex(1234567890)
b'd2029649'
>>> reformat_hex(1234567890987654321)
b'b11c6cb1'
>>> reformat_hex(-1)
Traceback (most recent call last):
...
ValueError: Input must be non-negative
"""
if i < 0:
raise ValueError("Input must be non-negative")
hex_rep = format(i, "08x")[-8:]
little_endian_hex = b""
for j in [3, 2, 1, 0]:
little_endian_hex += hex_rep[2 * j : 2 * j + 2].encode("utf-8")
return little_endian_hex
def preprocess(message: bytes) -> bytes:
"""
Preprocesses the message string:
- Convert message to bit string
- Pad bit string to a multiple of 512 chars:
- Append a 1
- Append 0's until length = 448 (mod 512)
- Append length of original message (64 chars)
Example: Suppose the input is the following:
message = "a"
The message bit string is "01100001", which is 8 bits long. Thus, the
bit string needs 439 bits of padding so that
(bit_string + "1" + padding) = 448 (mod 512).
The message length is "000010000...0" in 64-bit little-endian binary.
The combined bit string is then 512 bits long.
Arguments:
message {[string]} -- [message string]
Returns:
processed bit string padded to a multiple of 512 chars
>>> preprocess(b"a") == (b"01100001" + b"1" +
... (b"0" * 439) + b"00001000" + (b"0" * 56))
True
>>> preprocess(b"") == b"1" + (b"0" * 447) + (b"0" * 64)
True
"""
bit_string = b""
for char in message:
bit_string += format(char, "08b").encode("utf-8")
start_len = format(len(bit_string), "064b").encode("utf-8")
# Pad bit_string to a multiple of 512 chars
bit_string += b"1"
while len(bit_string) % 512 != 448:
bit_string += b"0"
bit_string += to_little_endian(start_len[32:]) + to_little_endian(start_len[:32])
return bit_string
def get_block_words(bit_string: bytes) -> Generator[list[int]]:
"""
Splits bit string into blocks of 512 chars and yields each block as a list
of 32-bit words
Example: Suppose the input is the following:
bit_string =
"000000000...0" + # 0x00 (32 bits, padded to the right)
"000000010...0" + # 0x01 (32 bits, padded to the right)
"000000100...0" + # 0x02 (32 bits, padded to the right)
"000000110...0" + # 0x03 (32 bits, padded to the right)
...
"000011110...0" # 0x0a (32 bits, padded to the right)
Then len(bit_string) == 512, so there'll be 1 block. The block is split
into 32-bit words, and each word is converted to little endian. The
first word is interpreted as 0 in decimal, the second word is
interpreted as 1 in decimal, etc.
Thus, block_words == [[0, 1, 2, 3, ..., 15]].
Arguments:
bit_string {[string]} -- [bit string with multiple of 512 as length]
Raises:
ValueError -- [length of bit string isn't multiple of 512]
Yields:
a list of 16 32-bit words
>>> test_string = ("".join(format(n << 24, "032b") for n in range(16))
... .encode("utf-8"))
>>> list(get_block_words(test_string))
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]]
>>> list(get_block_words(test_string * 4)) == [list(range(16))] * 4
True
>>> list(get_block_words(b"1" * 512)) == [[4294967295] * 16]
True
>>> list(get_block_words(b""))
[]
>>> list(get_block_words(b"1111"))
Traceback (most recent call last):
...
ValueError: Input must have length that's a multiple of 512
"""
if len(bit_string) % 512 != 0:
raise ValueError("Input must have length that's a multiple of 512")
for pos in range(0, len(bit_string), 512):
block = bit_string[pos : pos + 512]
block_words = []
for i in range(0, 512, 32):
block_words.append(int(to_little_endian(block[i : i + 32]), 2))
yield block_words
def not_32(i: int) -> int:
"""
Perform bitwise NOT on given int.
Arguments:
i {[int]} -- [given int]
Raises:
ValueError -- [input is negative]
Returns:
Result of bitwise NOT on i
>>> not_32(34)
4294967261
>>> not_32(1234)
4294966061
>>> not_32(4294966061)
1234
>>> not_32(0)
4294967295
>>> not_32(1)
4294967294
>>> not_32(-1)
Traceback (most recent call last):
...
ValueError: Input must be non-negative
"""
if i < 0:
raise ValueError("Input must be non-negative")
i_str = format(i, "032b")
new_str = ""
for c in i_str:
new_str += "1" if c == "0" else "0"
return int(new_str, 2)
def sum_32(a: int, b: int) -> int:
"""
Add two numbers as 32-bit ints.
Arguments:
a {[int]} -- [first given int]
b {[int]} -- [second given int]
Returns:
(a + b) as an unsigned 32-bit int
>>> sum_32(1, 1)
2
>>> sum_32(2, 3)
5
>>> sum_32(0, 0)
0
>>> sum_32(-1, -1)
4294967294
>>> sum_32(4294967295, 1)
0
"""
return (a + b) % 2**32
def left_rotate_32(i: int, shift: int) -> int:
"""
Rotate the bits of a given int left by a given amount.
Arguments:
i {[int]} -- [given int]
shift {[int]} -- [shift amount]
Raises:
ValueError -- [either given int or shift is negative]
Returns:
`i` rotated to the left by `shift` bits
>>> left_rotate_32(1234, 1)
2468
>>> left_rotate_32(1111, 4)
17776
>>> left_rotate_32(2147483648, 1)
1
>>> left_rotate_32(2147483648, 3)
4
>>> left_rotate_32(4294967295, 4)
4294967295
>>> left_rotate_32(1234, 0)
1234
>>> left_rotate_32(0, 0)
0
>>> left_rotate_32(-1, 0)
Traceback (most recent call last):
...
ValueError: Input must be non-negative
>>> left_rotate_32(0, -1)
Traceback (most recent call last):
...
ValueError: Shift must be non-negative
"""
if i < 0:
raise ValueError("Input must be non-negative")
if shift < 0:
raise ValueError("Shift must be non-negative")
return ((i << shift) ^ (i >> (32 - shift))) % 2**32
def md5_me(message: bytes) -> bytes:
"""
Returns the 32-char MD5 hash of a given message.
Reference: https://en.wikipedia.org/wiki/MD5#Algorithm
Arguments:
message {[string]} -- [message]
Returns:
32-char MD5 hash string
>>> md5_me(b"")
b'd41d8cd98f00b204e9800998ecf8427e'
>>> md5_me(b"The quick brown fox jumps over the lazy dog")
b'9e107d9d372bb6826bd81d3542a419d6'
>>> md5_me(b"The quick brown fox jumps over the lazy dog.")
b'e4d909c290d0fb1ca068ffaddf22cbd0'
>>> import hashlib
>>> from string import ascii_letters
>>> msgs = [b"", ascii_letters.encode("utf-8"), "Üñîçø∂é".encode("utf-8"),
... b"The quick brown fox jumps over the lazy dog."]
>>> all(md5_me(msg) == hashlib.md5(msg).hexdigest().encode("utf-8") for msg in msgs)
True
"""
# Convert to bit string, add padding and append message length
bit_string = preprocess(message)
added_consts = [int(2**32 * abs(sin(i + 1))) for i in range(64)]
# Starting states
a0 = 0x67452301
b0 = 0xEFCDAB89
c0 = 0x98BADCFE
d0 = 0x10325476
shift_amounts = [
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
]
# Process bit string in chunks, each with 16 32-char words
for block_words in get_block_words(bit_string):
a = a0
b = b0
c = c0
d = d0
# Hash current chunk
for i in range(64):
if i <= 15:
# f = (b & c) | (not_32(b) & d) # Alternate definition for f
f = d ^ (b & (c ^ d))
g = i
elif i <= 31:
# f = (d & b) | (not_32(d) & c) # Alternate definition for f
f = c ^ (d & (b ^ c))
g = (5 * i + 1) % 16
elif i <= 47:
f = b ^ c ^ d
g = (3 * i + 5) % 16
else:
f = c ^ (b | not_32(d))
g = (7 * i) % 16
f = (f + a + added_consts[i] + block_words[g]) % 2**32
a = d
d = c
c = b
b = sum_32(b, left_rotate_32(f, shift_amounts[i]))
# Add hashed chunk to running total
a0 = sum_32(a0, a)
b0 = sum_32(b0, b)
c0 = sum_32(c0, c)
d0 = sum_32(d0, d)
digest = reformat_hex(a0) + reformat_hex(b0) + reformat_hex(c0) + reformat_hex(d0)
return digest
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/hashes/enigma_machine.py | hashes/enigma_machine.py | alphabets = [chr(i) for i in range(32, 126)]
gear_one = list(range(len(alphabets)))
gear_two = list(range(len(alphabets)))
gear_three = list(range(len(alphabets)))
reflector = list(reversed(range(len(alphabets))))
code = []
gear_one_pos = gear_two_pos = gear_three_pos = 0
def rotator():
global gear_one_pos
global gear_two_pos
global gear_three_pos
i = gear_one[0]
gear_one.append(i)
del gear_one[0]
gear_one_pos += 1
if gear_one_pos % len(alphabets) == 0:
i = gear_two[0]
gear_two.append(i)
del gear_two[0]
gear_two_pos += 1
if gear_two_pos % len(alphabets) == 0:
i = gear_three[0]
gear_three.append(i)
del gear_three[0]
gear_three_pos += 1
def engine(input_character):
target = alphabets.index(input_character)
target = gear_one[target]
target = gear_two[target]
target = gear_three[target]
target = reflector[target]
target = gear_three.index(target)
target = gear_two.index(target)
target = gear_one.index(target)
code.append(alphabets[target])
rotator()
if __name__ == "__main__":
decode = list(input("Type your message:\n"))
while True:
try:
token = int(input("Please set token:(must be only digits)\n"))
break
except Exception as error:
print(error)
for _ in range(token):
rotator()
for j in decode:
engine(j)
print("\n" + "".join(code))
print(
f"\nYour Token is {token} please write it down.\nIf you want to decode "
"this message again you should input same digits as token!"
)
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/hashes/sha256.py | hashes/sha256.py | # Author: M. Yathurshan
# Black Formatter: True
"""
Implementation of SHA256 Hash function in a Python class and provides utilities
to find hash of string or hash of text from a file.
Usage: python sha256.py --string "Hello World!!"
python sha256.py --file "hello_world.txt"
When run without any arguments,
it prints the hash of the string "Hello World!! Welcome to Cryptography"
References:
https://qvault.io/cryptography/how-sha-2-works-step-by-step-sha-256/
https://en.wikipedia.org/wiki/SHA-2
"""
import argparse
import struct
import unittest
class SHA256:
"""
Class to contain the entire pipeline for SHA1 Hashing Algorithm
>>> SHA256(b'Python').hash
'18885f27b5af9012df19e496460f9294d5ab76128824c6f993787004f6d9a7db'
>>> SHA256(b'hello world').hash
'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9'
"""
def __init__(self, data: bytes) -> None:
self.data = data
# Initialize hash values
self.hashes = [
0x6A09E667,
0xBB67AE85,
0x3C6EF372,
0xA54FF53A,
0x510E527F,
0x9B05688C,
0x1F83D9AB,
0x5BE0CD19,
]
# Initialize round constants
self.round_constants = [
0x428A2F98,
0x71374491,
0xB5C0FBCF,
0xE9B5DBA5,
0x3956C25B,
0x59F111F1,
0x923F82A4,
0xAB1C5ED5,
0xD807AA98,
0x12835B01,
0x243185BE,
0x550C7DC3,
0x72BE5D74,
0x80DEB1FE,
0x9BDC06A7,
0xC19BF174,
0xE49B69C1,
0xEFBE4786,
0x0FC19DC6,
0x240CA1CC,
0x2DE92C6F,
0x4A7484AA,
0x5CB0A9DC,
0x76F988DA,
0x983E5152,
0xA831C66D,
0xB00327C8,
0xBF597FC7,
0xC6E00BF3,
0xD5A79147,
0x06CA6351,
0x14292967,
0x27B70A85,
0x2E1B2138,
0x4D2C6DFC,
0x53380D13,
0x650A7354,
0x766A0ABB,
0x81C2C92E,
0x92722C85,
0xA2BFE8A1,
0xA81A664B,
0xC24B8B70,
0xC76C51A3,
0xD192E819,
0xD6990624,
0xF40E3585,
0x106AA070,
0x19A4C116,
0x1E376C08,
0x2748774C,
0x34B0BCB5,
0x391C0CB3,
0x4ED8AA4A,
0x5B9CCA4F,
0x682E6FF3,
0x748F82EE,
0x78A5636F,
0x84C87814,
0x8CC70208,
0x90BEFFFA,
0xA4506CEB,
0xBEF9A3F7,
0xC67178F2,
]
self.preprocessed_data = self.preprocessing(self.data)
self.final_hash()
@staticmethod
def preprocessing(data: bytes) -> bytes:
padding = b"\x80" + (b"\x00" * (63 - (len(data) + 8) % 64))
big_endian_integer = struct.pack(">Q", (len(data) * 8))
return data + padding + big_endian_integer
def final_hash(self) -> None:
# Convert into blocks of 64 bytes
self.blocks = [
self.preprocessed_data[x : x + 64]
for x in range(0, len(self.preprocessed_data), 64)
]
for block in self.blocks:
# Convert the given block into a list of 4 byte integers
words = list(struct.unpack(">16L", block))
# add 48 0-ed integers
words += [0] * 48
a, b, c, d, e, f, g, h = self.hashes
for index in range(64):
if index > 15:
# modify the zero-ed indexes at the end of the array
s0 = (
self.ror(words[index - 15], 7)
^ self.ror(words[index - 15], 18)
^ (words[index - 15] >> 3)
)
s1 = (
self.ror(words[index - 2], 17)
^ self.ror(words[index - 2], 19)
^ (words[index - 2] >> 10)
)
words[index] = (
words[index - 16] + s0 + words[index - 7] + s1
) % 0x100000000
# Compression
s1 = self.ror(e, 6) ^ self.ror(e, 11) ^ self.ror(e, 25)
ch = (e & f) ^ ((~e & (0xFFFFFFFF)) & g)
temp1 = (
h + s1 + ch + self.round_constants[index] + words[index]
) % 0x100000000
s0 = self.ror(a, 2) ^ self.ror(a, 13) ^ self.ror(a, 22)
maj = (a & b) ^ (a & c) ^ (b & c)
temp2 = (s0 + maj) % 0x100000000
h, g, f, e, d, c, b, a = (
g,
f,
e,
((d + temp1) % 0x100000000),
c,
b,
a,
((temp1 + temp2) % 0x100000000),
)
mutated_hash_values = [a, b, c, d, e, f, g, h]
# Modify final values
self.hashes = [
((element + mutated_hash_values[index]) % 0x100000000)
for index, element in enumerate(self.hashes)
]
self.hash = "".join([hex(value)[2:].zfill(8) for value in self.hashes])
def ror(self, value: int, rotations: int) -> int:
"""
Right rotate a given unsigned number by a certain amount of rotations
"""
return 0xFFFFFFFF & (value << (32 - rotations)) | (value >> rotations)
class SHA256HashTest(unittest.TestCase):
"""
Test class for the SHA256 class. Inherits the TestCase class from unittest
"""
def test_match_hashes(self) -> None:
import hashlib
msg = bytes("Test String", "utf-8")
assert SHA256(msg).hash == hashlib.sha256(msg).hexdigest()
def main() -> None:
"""
Provides option 'string' or 'file' to take input
and prints the calculated SHA-256 hash
"""
# unittest.main()
import doctest
doctest.testmod()
parser = argparse.ArgumentParser()
parser.add_argument(
"-s",
"--string",
dest="input_string",
default="Hello World!! Welcome to Cryptography",
help="Hash the string",
)
parser.add_argument(
"-f", "--file", dest="input_file", help="Hash contents of a file"
)
args = parser.parse_args()
input_string = args.input_string
# hash input should be a bytestring
if args.input_file:
with open(args.input_file, "rb") as f:
hash_input = f.read()
else:
hash_input = bytes(input_string, "utf-8")
print(SHA256(hash_input).hash)
if __name__ == "__main__":
main()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/hashes/hamming_code.py | hashes/hamming_code.py | # Author: João Gustavo A. Amorim & Gabriel Kunz
# Author email: joaogustavoamorim@gmail.com and gabriel-kunz@uergs.edu.br
# Coding date: apr 2019
# Black: True
"""
* This code implement the Hamming code:
https://en.wikipedia.org/wiki/Hamming_code - In telecommunication,
Hamming codes are a family of linear error-correcting codes. Hamming
codes can detect up to two-bit errors or correct one-bit errors
without detection of uncorrected errors. By contrast, the simple
parity code cannot correct errors, and can detect only an odd number
of bits in error. Hamming codes are perfect codes, that is, they
achieve the highest possible rate for codes with their block length
and minimum distance of three.
* the implemented code consists of:
* a function responsible for encoding the message (emitterConverter)
* return the encoded message
* a function responsible for decoding the message (receptorConverter)
* return the decoded message and a ack of data integrity
* how to use:
to be used you must declare how many parity bits (sizePari)
you want to include in the message.
it is desired (for test purposes) to select a bit to be set
as an error. This serves to check whether the code is working correctly.
Lastly, the variable of the message/word that must be desired to be
encoded (text).
* how this work:
declaration of variables (sizePari, be, text)
converts the message/word (text) to binary using the
text_to_bits function
encodes the message using the rules of hamming encoding
decodes the message using the rules of hamming encoding
print the original message, the encoded message and the
decoded message
forces an error in the coded text variable
decodes the message that was forced the error
print the original message, the encoded message, the bit changed
message and the decoded message
"""
# Imports
import numpy as np
# Functions of binary conversion--------------------------------------
def text_to_bits(text, encoding="utf-8", errors="surrogatepass"):
"""
>>> text_to_bits("msg")
'011011010111001101100111'
"""
bits = bin(int.from_bytes(text.encode(encoding, errors), "big"))[2:]
return bits.zfill(8 * ((len(bits) + 7) // 8))
def text_from_bits(bits, encoding="utf-8", errors="surrogatepass"):
"""
>>> text_from_bits('011011010111001101100111')
'msg'
"""
n = int(bits, 2)
return n.to_bytes((n.bit_length() + 7) // 8, "big").decode(encoding, errors) or "\0"
# Functions of hamming code-------------------------------------------
def emitter_converter(size_par, data):
"""
:param size_par: how many parity bits the message must have
:param data: information bits
:return: message to be transmitted by unreliable medium
- bits of information merged with parity bits
>>> emitter_converter(4, "101010111111")
['1', '1', '1', '1', '0', '1', '0', '0', '1', '0', '1', '1', '1', '1', '1', '1']
>>> emitter_converter(5, "101010111111")
Traceback (most recent call last):
...
ValueError: size of parity don't match with size of data
"""
if size_par + len(data) <= 2**size_par - (len(data) - 1):
raise ValueError("size of parity don't match with size of data")
data_out = []
parity = []
bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data) + 1)]
# sorted information data for the size of the output data
data_ord = []
# data position template + parity
data_out_gab = []
# parity bit counter
qtd_bp = 0
# counter position of data bits
cont_data = 0
for x in range(1, size_par + len(data) + 1):
# Performs a template of bit positions - who should be given,
# and who should be parity
if qtd_bp < size_par:
if (np.log(x) / np.log(2)).is_integer():
data_out_gab.append("P")
qtd_bp = qtd_bp + 1
else:
data_out_gab.append("D")
else:
data_out_gab.append("D")
# Sorts the data to the new output size
if data_out_gab[-1] == "D":
data_ord.append(data[cont_data])
cont_data += 1
else:
data_ord.append(None)
# Calculates parity
qtd_bp = 0 # parity bit counter
for bp in range(1, size_par + 1):
# Bit counter one for a given parity
cont_bo = 0
# counter to control the loop reading
for cont_loop, x in enumerate(data_ord):
if x is not None:
try:
aux = (bin_pos[cont_loop])[-1 * (bp)]
except IndexError:
aux = "0"
if aux == "1" and x == "1":
cont_bo += 1
parity.append(cont_bo % 2)
qtd_bp += 1
# Mount the message
cont_bp = 0 # parity bit counter
for x in range(size_par + len(data)):
if data_ord[x] is None:
data_out.append(str(parity[cont_bp]))
cont_bp += 1
else:
data_out.append(data_ord[x])
return data_out
def receptor_converter(size_par, data):
"""
>>> receptor_converter(4, "1111010010111111")
(['1', '0', '1', '0', '1', '0', '1', '1', '1', '1', '1', '1'], True)
"""
# data position template + parity
data_out_gab = []
# Parity bit counter
qtd_bp = 0
# Counter p data bit reading
cont_data = 0
# list of parity received
parity_received = []
data_output = []
for i, item in enumerate(data, 1):
# Performs a template of bit positions - who should be given,
# and who should be parity
if qtd_bp < size_par and (np.log(i) / np.log(2)).is_integer():
data_out_gab.append("P")
qtd_bp = qtd_bp + 1
else:
data_out_gab.append("D")
# Sorts the data to the new output size
if data_out_gab[-1] == "D":
data_output.append(item)
else:
parity_received.append(item)
# -----------calculates the parity with the data
data_out = []
parity = []
bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data_output) + 1)]
# sorted information data for the size of the output data
data_ord = []
# Data position feedback + parity
data_out_gab = []
# Parity bit counter
qtd_bp = 0
# Counter p data bit reading
cont_data = 0
for x in range(1, size_par + len(data_output) + 1):
# Performs a template position of bits - who should be given,
# and who should be parity
if qtd_bp < size_par and (np.log(x) / np.log(2)).is_integer():
data_out_gab.append("P")
qtd_bp = qtd_bp + 1
else:
data_out_gab.append("D")
# Sorts the data to the new output size
if data_out_gab[-1] == "D":
data_ord.append(data_output[cont_data])
cont_data += 1
else:
data_ord.append(None)
# Calculates parity
qtd_bp = 0 # parity bit counter
for bp in range(1, size_par + 1):
# Bit counter one for a certain parity
cont_bo = 0
for cont_loop, x in enumerate(data_ord):
if x is not None:
try:
aux = (bin_pos[cont_loop])[-1 * (bp)]
except IndexError:
aux = "0"
if aux == "1" and x == "1":
cont_bo += 1
parity.append(str(cont_bo % 2))
qtd_bp += 1
# Mount the message
cont_bp = 0 # Parity bit counter
for x in range(size_par + len(data_output)):
if data_ord[x] is None:
data_out.append(str(parity[cont_bp]))
cont_bp += 1
else:
data_out.append(data_ord[x])
ack = parity_received == parity
return data_output, ack
# ---------------------------------------------------------------------
"""
# Example how to use
# number of parity bits
sizePari = 4
# location of the bit that will be forced an error
be = 2
# Message/word to be encoded and decoded with hamming
# text = input("Enter the word to be read: ")
text = "Message01"
# Convert the message to binary
binaryText = text_to_bits(text)
# Prints the binary of the string
print("Text input in binary is '" + binaryText + "'")
# total transmitted bits
totalBits = len(binaryText) + sizePari
print("Size of data is " + str(totalBits))
print("\n --Message exchange--")
print("Data to send ------------> " + binaryText)
dataOut = emitterConverter(sizePari, binaryText)
print("Data converted ----------> " + "".join(dataOut))
dataReceiv, ack = receptorConverter(sizePari, dataOut)
print(
"Data receive ------------> "
+ "".join(dataReceiv)
+ "\t\t -- Data integrity: "
+ str(ack)
)
print("\n --Force error--")
print("Data to send ------------> " + binaryText)
dataOut = emitterConverter(sizePari, binaryText)
print("Data converted ----------> " + "".join(dataOut))
# forces error
dataOut[-be] = "1" * (dataOut[-be] == "0") + "0" * (dataOut[-be] == "1")
print("Data after transmission -> " + "".join(dataOut))
dataReceiv, ack = receptorConverter(sizePari, dataOut)
print(
"Data receive ------------> "
+ "".join(dataReceiv)
+ "\t\t -- Data integrity: "
+ str(ack)
)
"""
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/hashes/chaos_machine.py | hashes/chaos_machine.py | """example of simple chaos machine"""
# Chaos Machine (K, t, m)
K = [0.33, 0.44, 0.55, 0.44, 0.33]
t = 3
m = 5
# Buffer Space (with Parameters Space)
buffer_space: list[float] = []
params_space: list[float] = []
# Machine Time
machine_time = 0
def push(seed):
global buffer_space, params_space, machine_time, K, m, t
# Choosing Dynamical Systems (All)
for key, value in enumerate(buffer_space):
# Evolution Parameter
e = float(seed / value)
# Control Theory: Orbit Change
value = (buffer_space[(key + 1) % m] + e) % 1
# Control Theory: Trajectory Change
r = (params_space[key] + e) % 1 + 3
# Modification (Transition Function) - Jumps
buffer_space[key] = round(float(r * value * (1 - value)), 10)
params_space[key] = r # Saving to Parameters Space
# Logistic Map
assert max(buffer_space) < 1
assert max(params_space) < 4
# Machine Time
machine_time += 1
def pull():
global buffer_space, params_space, machine_time, K, m, t
# PRNG (Xorshift by George Marsaglia)
def xorshift(x, y):
x ^= y >> 13
y ^= x << 17
x ^= y >> 5
return x
# Choosing Dynamical Systems (Increment)
key = machine_time % m
# Evolution (Time Length)
for _ in range(t):
# Variables (Position + Parameters)
r = params_space[key]
value = buffer_space[key]
# Modification (Transition Function) - Flow
buffer_space[key] = round(float(r * value * (1 - value)), 10)
params_space[key] = (machine_time * 0.01 + r * 1.01) % 1 + 3
# Choosing Chaotic Data
x = int(buffer_space[(key + 2) % m] * (10**10))
y = int(buffer_space[(key - 2) % m] * (10**10))
# Machine Time
machine_time += 1
return xorshift(x, y) % 0xFFFFFFFF
def reset():
global buffer_space, params_space, machine_time, K, m, t
buffer_space = K
params_space = [0] * m
machine_time = 0
if __name__ == "__main__":
# Initialization
reset()
# Pushing Data (Input)
import random
message = random.sample(range(0xFFFFFFFF), 100)
for chunk in message:
push(chunk)
# for controlling
inp = ""
# Pulling Data (Output)
while inp in ("e", "E"):
print(f"{format(pull(), '#04x')}")
print(buffer_space)
print(params_space)
inp = input("(e)exit? ").strip()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/geodesy/lamberts_ellipsoidal_distance.py | geodesy/lamberts_ellipsoidal_distance.py | from math import atan, cos, radians, sin, tan
from .haversine_distance import haversine_distance
AXIS_A = 6378137.0
AXIS_B = 6356752.314245
EQUATORIAL_RADIUS = 6378137
def lamberts_ellipsoidal_distance(
lat1: float, lon1: float, lat2: float, lon2: float
) -> float:
"""
Calculate the shortest distance along the surface of an ellipsoid between
two points on the surface of earth given longitudes and latitudes
https://en.wikipedia.org/wiki/Geographical_distance#Lambert's_formula_for_long_lines
NOTE: This algorithm uses geodesy/haversine_distance.py to compute central angle,
sigma
Representing the earth as an ellipsoid allows us to approximate distances between
points on the surface much better than a sphere. Ellipsoidal formulas treat the
Earth as an oblate ellipsoid which means accounting for the flattening that happens
at the North and South poles. Lambert's formulae provide accuracy on the order of
10 meteres over thousands of kilometeres. Other methods can provide
millimeter-level accuracy but this is a simpler method to calculate long range
distances without increasing computational intensity.
Args:
lat1, lon1: latitude and longitude of coordinate 1
lat2, lon2: latitude and longitude of coordinate 2
Returns:
geographical distance between two points in metres
>>> from collections import namedtuple
>>> point_2d = namedtuple("point_2d", "lat lon")
>>> SAN_FRANCISCO = point_2d(37.774856, -122.424227)
>>> YOSEMITE = point_2d(37.864742, -119.537521)
>>> NEW_YORK = point_2d(40.713019, -74.012647)
>>> VENICE = point_2d(45.443012, 12.313071)
>>> f"{lamberts_ellipsoidal_distance(*SAN_FRANCISCO, *YOSEMITE):0,.0f} meters"
'254,351 meters'
>>> f"{lamberts_ellipsoidal_distance(*SAN_FRANCISCO, *NEW_YORK):0,.0f} meters"
'4,138,992 meters'
>>> f"{lamberts_ellipsoidal_distance(*SAN_FRANCISCO, *VENICE):0,.0f} meters"
'9,737,326 meters'
"""
# CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System
# Distance in metres(m)
# Equation Parameters
# https://en.wikipedia.org/wiki/Geographical_distance#Lambert's_formula_for_long_lines
flattening = (AXIS_A - AXIS_B) / AXIS_A
# Parametric latitudes
# https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude
b_lat1 = atan((1 - flattening) * tan(radians(lat1)))
b_lat2 = atan((1 - flattening) * tan(radians(lat2)))
# Compute central angle between two points
# using haversine theta. sigma = haversine_distance / equatorial radius
sigma = haversine_distance(lat1, lon1, lat2, lon2) / EQUATORIAL_RADIUS
# Intermediate P and Q values
p_value = (b_lat1 + b_lat2) / 2
q_value = (b_lat2 - b_lat1) / 2
# Intermediate X value
# X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2)
x_numerator = (sin(p_value) ** 2) * (cos(q_value) ** 2)
x_demonimator = cos(sigma / 2) ** 2
x_value = (sigma - sin(sigma)) * (x_numerator / x_demonimator)
# Intermediate Y value
# Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2)
y_numerator = (cos(p_value) ** 2) * (sin(q_value) ** 2)
y_denominator = sin(sigma / 2) ** 2
y_value = (sigma + sin(sigma)) * (y_numerator / y_denominator)
return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value)))
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/geodesy/haversine_distance.py | geodesy/haversine_distance.py | from math import asin, atan, cos, radians, sin, sqrt, tan
AXIS_A = 6378137.0
AXIS_B = 6356752.314245
RADIUS = 6378137
def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
"""
Calculate great circle distance between two points in a sphere,
given longitudes and latitudes https://en.wikipedia.org/wiki/Haversine_formula
We know that the globe is "sort of" spherical, so a path between two points
isn't exactly a straight line. We need to account for the Earth's curvature
when calculating distance from point A to B. This effect is negligible for
small distances but adds up as distance increases. The Haversine method treats
the earth as a sphere which allows us to "project" the two points A and B
onto the surface of that sphere and approximate the spherical distance between
them. Since the Earth is not a perfect sphere, other methods which model the
Earth's ellipsoidal nature are more accurate but a quick and modifiable
computation like Haversine can be handy for shorter range distances.
Args:
* `lat1`, `lon1`: latitude and longitude of coordinate 1
* `lat2`, `lon2`: latitude and longitude of coordinate 2
Returns:
geographical distance between two points in metres
>>> from collections import namedtuple
>>> point_2d = namedtuple("point_2d", "lat lon")
>>> SAN_FRANCISCO = point_2d(37.774856, -122.424227)
>>> YOSEMITE = point_2d(37.864742, -119.537521)
>>> f"{haversine_distance(*SAN_FRANCISCO, *YOSEMITE):0,.0f} meters"
'254,352 meters'
"""
# CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System
# Distance in metres(m)
# Equation parameters
# Equation https://en.wikipedia.org/wiki/Haversine_formula#Formulation
flattening = (AXIS_A - AXIS_B) / AXIS_A
phi_1 = atan((1 - flattening) * tan(radians(lat1)))
phi_2 = atan((1 - flattening) * tan(radians(lat2)))
lambda_1 = radians(lon1)
lambda_2 = radians(lon2)
# Equation
sin_sq_phi = sin((phi_2 - phi_1) / 2)
sin_sq_lambda = sin((lambda_2 - lambda_1) / 2)
# Square both values
sin_sq_phi *= sin_sq_phi
sin_sq_lambda *= sin_sq_lambda
h_value = sqrt(sin_sq_phi + (cos(phi_1) * cos(phi_2) * sin_sq_lambda))
return 2 * RADIUS * asin(h_value)
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/geodesy/__init__.py | geodesy/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/random_anime_character.py | web_programming/random_anime_character.py | # /// script
# requires-python = ">=3.13"
# dependencies = [
# "beautifulsoup4",
# "fake-useragent",
# "httpx",
# ]
# ///
import os
import httpx
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
headers = {"UserAgent": UserAgent().random}
URL = "https://www.mywaifulist.moe/random"
def save_image(image_url: str, image_title: str) -> None:
"""
Saves the image of anime character
"""
image = httpx.get(image_url, headers=headers, timeout=10)
with open(image_title, "wb") as file:
file.write(image.content)
def random_anime_character() -> tuple[str, str, str]:
"""
Returns the Title, Description, and Image Title of a random anime character .
"""
soup = BeautifulSoup(
httpx.get(URL, headers=headers, timeout=10).text, "html.parser"
)
title = soup.find("meta", attrs={"property": "og:title"}).attrs["content"]
image_url = soup.find("meta", attrs={"property": "og:image"}).attrs["content"]
description = soup.find("p", id="description").get_text()
_, image_extension = os.path.splitext(os.path.basename(image_url))
image_title = title.strip().replace(" ", "_")
image_title = f"{image_title}{image_extension}"
save_image(image_url, image_title)
return (title, description, image_title)
if __name__ == "__main__":
title, desc, image_title = random_anime_character()
print(f"{title}\n\n{desc}\n\nImage saved : {image_title}")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/get_ip_geolocation.py | web_programming/get_ip_geolocation.py | # /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# ]
# ///
import httpx
# Function to get geolocation data for an IP address
def get_ip_geolocation(ip_address: str) -> str:
try:
# Construct the URL for the IP geolocation API
url = f"https://ipinfo.io/{ip_address}/json"
# Send a GET request to the API
response = httpx.get(url, timeout=10)
# Check if the HTTP request was successful
response.raise_for_status()
# Parse the response as JSON
data = response.json()
# Check if city, region, and country information is available
if "city" in data and "region" in data and "country" in data:
location = f"Location: {data['city']}, {data['region']}, {data['country']}"
else:
location = "Location data not found."
return location
except httpx.RequestError as e:
# Handle network-related exceptions
return f"Request error: {e}"
except ValueError as e:
# Handle JSON parsing errors
return f"JSON parsing error: {e}"
if __name__ == "__main__":
# Prompt the user to enter an IP address
ip_address = input("Enter an IP address: ")
# Get the geolocation data and print it
location = get_ip_geolocation(ip_address)
print(location)
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/fetch_quotes.py | web_programming/fetch_quotes.py | """
This file fetches quotes from the " ZenQuotes API ".
It does not require any API key as it uses free tier.
For more details and premium features visit:
https://zenquotes.io/
"""
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# ]
# ///
import pprint
import httpx
API_ENDPOINT_URL = "https://zenquotes.io/api"
def quote_of_the_day() -> list:
return httpx.get(API_ENDPOINT_URL + "/today", timeout=10).json()
def random_quotes() -> list:
return httpx.get(API_ENDPOINT_URL + "/random", timeout=10).json()
if __name__ == "__main__":
"""
response object has all the info with the quote
To retrieve the actual quote access the response.json() object as below
response.json() is a list of json object
response.json()[0]['q'] = actual quote.
response.json()[0]['a'] = author name.
response.json()[0]['h'] = in html format.
"""
response = random_quotes()
pprint.pprint(response)
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/get_top_hn_posts.py | web_programming/get_top_hn_posts.py | # /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# ]
# ///
from __future__ import annotations
import httpx
def get_hackernews_story(story_id: str) -> dict:
url = f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty"
return httpx.get(url, timeout=10).json()
def hackernews_top_stories(max_stories: int = 10) -> list[dict]:
"""
Get the top max_stories posts from HackerNews - https://news.ycombinator.com/
"""
url = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty"
story_ids = httpx.get(url, timeout=10).json()[:max_stories]
return [get_hackernews_story(story_id) for story_id in story_ids]
def hackernews_top_stories_as_markdown(max_stories: int = 10) -> str:
stories = hackernews_top_stories(max_stories)
return "\n".join("* [{title}]({url})".format(**story) for story in stories)
if __name__ == "__main__":
print(hackernews_top_stories_as_markdown())
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/test_fetch_github_info.py | web_programming/test_fetch_github_info.py | import json
import httpx
from .fetch_github_info import AUTHENTICATED_USER_ENDPOINT, fetch_github_info
def test_fetch_github_info(monkeypatch):
class FakeResponse:
def __init__(self, content) -> None:
assert isinstance(content, (bytes, str))
self.content = content
def json(self):
return json.loads(self.content)
def mock_response(*args, **kwargs):
assert args[0] == AUTHENTICATED_USER_ENDPOINT
assert "Authorization" in kwargs["headers"]
assert kwargs["headers"]["Authorization"].startswith("token ")
assert "Accept" in kwargs["headers"]
return FakeResponse(b'{"login":"test","id":1}')
monkeypatch.setattr(httpx, "get", mock_response)
result = fetch_github_info("token")
assert result["login"] == "test"
assert result["id"] == 1
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/fetch_bbc_news.py | web_programming/fetch_bbc_news.py | # Created by sarathkaul on 12/11/19
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# ]
# ///
import httpx
_NEWS_API = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey="
def fetch_bbc_news(bbc_news_api_key: str) -> None:
# fetching a list of articles in json format
bbc_news_page = httpx.get(_NEWS_API + bbc_news_api_key, timeout=10).json()
# each article in the list is a dict
for i, article in enumerate(bbc_news_page["articles"], 1):
print(f"{i}.) {article['title']}")
if __name__ == "__main__":
fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/current_stock_price.py | web_programming/current_stock_price.py | # /// script
# requires-python = ">=3.13"
# dependencies = [
# "beautifulsoup4",
# "httpx",
# ]
# ///
import httpx
from bs4 import BeautifulSoup
"""
Get the HTML code of finance yahoo and select the current qsp-price
Current AAPL stock price is 228.43
Current AMZN stock price is 201.85
Current IBM stock price is 210.30
Current GOOG stock price is 177.86
Current MSFT stock price is 414.82
Current ORCL stock price is 188.87
"""
def stock_price(symbol: str = "AAPL") -> str:
"""
>>> stock_price("EEEE")
'No <fin-streamer> tag with the specified data-testid attribute found.'
>>> isinstance(float(stock_price("GOOG")),float)
True
"""
url = f"https://finance.yahoo.com/quote/{symbol}?p={symbol}"
yahoo_finance_source = httpx.get(
url, headers={"USER-AGENT": "Mozilla/5.0"}, timeout=10, follow_redirects=True
).text
soup = BeautifulSoup(yahoo_finance_source, "html.parser")
if specific_fin_streamer_tag := soup.find("span", {"data-testid": "qsp-price"}):
return specific_fin_streamer_tag.get_text()
return "No <fin-streamer> tag with the specified data-testid attribute found."
# Search for the symbol at https://finance.yahoo.com/lookup
if __name__ == "__main__":
from doctest import testmod
testmod()
for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split():
print(f"Current {symbol:<4} stock price is {stock_price(symbol):>8}")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/crawl_google_scholar_citation.py | web_programming/crawl_google_scholar_citation.py | """
Get the citation from google scholar
using title and year of publication, and volume and pages of journal.
"""
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "beautifulsoup4",
# "httpx",
# ]
# ///
import httpx
from bs4 import BeautifulSoup
def get_citation(base_url: str, params: dict) -> str:
"""
Return the citation number.
"""
soup = BeautifulSoup(
httpx.get(base_url, params=params, timeout=10).content, "html.parser"
)
div = soup.find("div", attrs={"class": "gs_ri"})
anchors = div.find("div", attrs={"class": "gs_fl"}).find_all("a")
return anchors[2].get_text()
if __name__ == "__main__":
params = {
"title": (
"Precisely geometry controlled microsupercapacitors for ultrahigh areal "
"capacitance, volumetric capacitance, and energy density"
),
"journal": "Chem. Mater.",
"volume": 30,
"pages": "3979-3990",
"year": 2018,
"hl": "en",
}
print(get_citation("https://scholar.google.com/scholar_lookup", params=params))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/reddit.py | web_programming/reddit.py | # /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# ]
# ///
from __future__ import annotations
import httpx
valid_terms = set(
"""approved_at_utc approved_by author_flair_background_color
author_flair_css_class author_flair_richtext author_flair_template_id author_fullname
author_premium can_mod_post category clicked content_categories created_utc downs
edited gilded gildings hidden hide_score is_created_from_ads_ui is_meta
is_original_content is_reddit_media_domain is_video link_flair_css_class
link_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title
name permalink pwls quarantine saved score secure_media secure_media_embed selftext
subreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type
total_awards_received ups upvote_ratio url user_reports""".split()
)
def get_subreddit_data(
subreddit: str, limit: int = 1, age: str = "new", wanted_data: list | None = None
) -> dict:
"""
subreddit : Subreddit to query
limit : Number of posts to fetch
age : ["new", "top", "hot"]
wanted_data : Get only the required data in the list
"""
wanted_data = wanted_data or []
if invalid_search_terms := ", ".join(sorted(set(wanted_data) - valid_terms)):
msg = f"Invalid search term: {invalid_search_terms}"
raise ValueError(msg)
response = httpx.get(
f"https://www.reddit.com/r/{subreddit}/{age}.json?limit={limit}",
headers={"User-agent": "A random string"},
timeout=10,
)
response.raise_for_status()
if response.status_code == 429:
raise httpx.HTTPError(response=response)
data = response.json()
if not wanted_data:
return {id_: data["data"]["children"][id_] for id_ in range(limit)}
data_dict = {}
for id_ in range(limit):
data_dict[id_] = {
item: data["data"]["children"][id_]["data"][item] for item in wanted_data
}
return data_dict
if __name__ == "__main__":
# If you get Error 429, that means you are rate limited.Try after some time
print(get_subreddit_data("learnpython", wanted_data=["title", "url", "selftext"]))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/recaptcha_verification.py | web_programming/recaptcha_verification.py | """
Recaptcha is a free captcha service offered by Google in order to secure websites and
forms. At https://www.google.com/recaptcha/admin/create you can create new recaptcha
keys and see the keys that your have already created.
* Keep in mind that recaptcha doesn't work with localhost
When you create a recaptcha key, your will get two separate keys: ClientKey & SecretKey.
ClientKey should be kept in your site's front end
SecretKey should be kept in your site's back end
# An example HTML login form with recaptcha tag is shown below
<form action="" method="post">
<h2 class="text-center">Log in</h2>
{% csrf_token %}
<div class="form-group">
<input type="text" name="username" required="required">
</div>
<div class="form-group">
<input type="password" name="password" required="required">
</div>
<div class="form-group">
<button type="submit">Log in</button>
</div>
<!-- Below is the recaptcha tag of html -->
<div class="g-recaptcha" data-sitekey="ClientKey"></div>
</form>
<!-- Below is the recaptcha script to be kept inside html tag -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
Below a Django function for the views.py file contains a login form for demonstrating
recaptcha verification.
"""
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# ]
# ///
import httpx
try:
from django.contrib.auth import authenticate, login
from django.shortcuts import redirect, render
except ImportError:
authenticate = login = render = redirect = print
def login_using_recaptcha(request):
# Enter your recaptcha secret key here
secret_key = "secretKey" # noqa: S105
url = "https://www.google.com/recaptcha/api/siteverify"
# when method is not POST, direct user to login page
if request.method != "POST":
return render(request, "login.html")
# from the frontend, get username, password, and client_key
username = request.POST.get("username")
password = request.POST.get("password")
client_key = request.POST.get("g-recaptcha-response")
# post recaptcha response to Google's recaptcha api
response = httpx.post(
url, data={"secret": secret_key, "response": client_key}, timeout=10
)
# if the recaptcha api verified our keys
if response.json().get("success", False):
# authenticate the user
user_in_database = authenticate(request, username=username, password=password)
if user_in_database:
login(request, user_in_database)
return redirect("/your-webpage")
return render(request, "login.html")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/fetch_github_info.py | web_programming/fetch_github_info.py | #!/usr/bin/env python3
"""
Created by sarathkaul on 14/11/19
Updated by lawric1 on 24/11/20
Authentication will be made via access token.
To generate your personal access token visit https://github.com/settings/tokens.
NOTE:
Never hardcode any credential information in the code. Always use an environment
file to store the private information and use the `os` module to get the information
during runtime.
Create a ".env" file in the root directory and write these two lines in that file
with your token::
#!/usr/bin/env bash
export USER_TOKEN=""
"""
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# ]
# ///
from __future__ import annotations
import os
from typing import Any
import httpx
BASE_URL = "https://api.github.com"
# https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user
AUTHENTICATED_USER_ENDPOINT = BASE_URL + "/user"
# https://github.com/settings/tokens
USER_TOKEN = os.environ.get("USER_TOKEN", "")
def fetch_github_info(auth_token: str) -> dict[Any, Any]:
"""
Fetch GitHub info of a user using the httpx module
"""
headers = {
"Authorization": f"token {auth_token}",
"Accept": "application/vnd.github.v3+json",
}
return httpx.get(AUTHENTICATED_USER_ENDPOINT, headers=headers, timeout=10).json()
if __name__ == "__main__": # pragma: no cover
if USER_TOKEN:
for key, value in fetch_github_info(USER_TOKEN).items():
print(f"{key}: {value}")
else:
raise ValueError("'USER_TOKEN' field cannot be empty.")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/get_amazon_product_data.py | web_programming/get_amazon_product_data.py | """
This file provides a function which will take a product name as input from the user,
and fetch from Amazon information about products of this name or category. The product
information will include title, URL, price, ratings, and the discount available.
"""
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "beautifulsoup4",
# "httpx",
# "pandas",
# ]
# ///
from itertools import zip_longest
import httpx
from bs4 import BeautifulSoup
from pandas import DataFrame
def get_amazon_product_data(product: str = "laptop") -> DataFrame:
"""
Take a product name or category as input and return product information from Amazon
including title, URL, price, ratings, and the discount available.
"""
url = f"https://www.amazon.in/laptop/s?k={product}"
header = {
"User-Agent": (
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36"
"(KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36"
),
"Accept-Language": "en-US, en;q=0.5",
}
soup = BeautifulSoup(
httpx.get(url, headers=header, timeout=10).text, features="lxml"
)
# Initialize a Pandas dataframe with the column titles
data_frame = DataFrame(
columns=[
"Product Title",
"Product Link",
"Current Price of the product",
"Product Rating",
"MRP of the product",
"Discount",
]
)
# Loop through each entry and store them in the dataframe
for item, _ in zip_longest(
soup.find_all(
"div",
attrs={"class": "s-result-item", "data-component-type": "s-search-result"},
),
soup.find_all("div", attrs={"class": "a-row a-size-base a-color-base"}),
):
try:
product_title = item.h2.text
product_link = "https://www.amazon.in/" + item.h2.a["href"]
product_price = item.find("span", attrs={"class": "a-offscreen"}).text
try:
product_rating = item.find("span", attrs={"class": "a-icon-alt"}).text
except AttributeError:
product_rating = "Not available"
try:
product_mrp = (
"₹"
+ item.find(
"span", attrs={"class": "a-price a-text-price"}
).text.split("₹")[1]
)
except AttributeError:
product_mrp = ""
try:
discount = float(
(
(
float(product_mrp.strip("₹").replace(",", ""))
- float(product_price.strip("₹").replace(",", ""))
)
/ float(product_mrp.strip("₹").replace(",", ""))
)
* 100
)
except ValueError:
discount = float("nan")
except AttributeError:
continue
data_frame.loc[str(len(data_frame.index))] = [
product_title,
product_link,
product_price,
product_rating,
product_mrp,
discount,
]
data_frame.loc[
data_frame["Current Price of the product"] > data_frame["MRP of the product"],
"MRP of the product",
] = " "
data_frame.loc[
data_frame["Current Price of the product"] > data_frame["MRP of the product"],
"Discount",
] = " "
data_frame.index += 1
return data_frame
if __name__ == "__main__":
product = "headphones"
get_amazon_product_data(product).to_csv(f"Amazon Product Data for {product}.csv")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/currency_converter.py | web_programming/currency_converter.py | """
This is used to convert the currency using the Amdoren Currency API
https://www.amdoren.com
"""
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# ]
# ///
import os
import httpx
URL_BASE = "https://www.amdoren.com/api/currency.php"
# Currency and their description
list_of_currencies = """
AED United Arab Emirates Dirham
AFN Afghan Afghani
ALL Albanian Lek
AMD Armenian Dram
ANG Netherlands Antillean Guilder
AOA Angolan Kwanza
ARS Argentine Peso
AUD Australian Dollar
AWG Aruban Florin
AZN Azerbaijani Manat
BAM Bosnia & Herzegovina Convertible Mark
BBD Barbadian Dollar
BDT Bangladeshi Taka
BGN Bulgarian Lev
BHD Bahraini Dinar
BIF Burundian Franc
BMD Bermudian Dollar
BND Brunei Dollar
BOB Bolivian Boliviano
BRL Brazilian Real
BSD Bahamian Dollar
BTN Bhutanese Ngultrum
BWP Botswana Pula
BYN Belarus Ruble
BZD Belize Dollar
CAD Canadian Dollar
CDF Congolese Franc
CHF Swiss Franc
CLP Chilean Peso
CNY Chinese Yuan
COP Colombian Peso
CRC Costa Rican Colon
CUC Cuban Convertible Peso
CVE Cape Verdean Escudo
CZK Czech Republic Koruna
DJF Djiboutian Franc
DKK Danish Krone
DOP Dominican Peso
DZD Algerian Dinar
EGP Egyptian Pound
ERN Eritrean Nakfa
ETB Ethiopian Birr
EUR Euro
FJD Fiji Dollar
GBP British Pound Sterling
GEL Georgian Lari
GHS Ghanaian Cedi
GIP Gibraltar Pound
GMD Gambian Dalasi
GNF Guinea Franc
GTQ Guatemalan Quetzal
GYD Guyanaese Dollar
HKD Hong Kong Dollar
HNL Honduran Lempira
HRK Croatian Kuna
HTG Haiti Gourde
HUF Hungarian Forint
IDR Indonesian Rupiah
ILS Israeli Shekel
INR Indian Rupee
IQD Iraqi Dinar
IRR Iranian Rial
ISK Icelandic Krona
JMD Jamaican Dollar
JOD Jordanian Dinar
JPY Japanese Yen
KES Kenyan Shilling
KGS Kyrgystani Som
KHR Cambodian Riel
KMF Comorian Franc
KPW North Korean Won
KRW South Korean Won
KWD Kuwaiti Dinar
KYD Cayman Islands Dollar
KZT Kazakhstan Tenge
LAK Laotian Kip
LBP Lebanese Pound
LKR Sri Lankan Rupee
LRD Liberian Dollar
LSL Lesotho Loti
LYD Libyan Dinar
MAD Moroccan Dirham
MDL Moldovan Leu
MGA Malagasy Ariary
MKD Macedonian Denar
MMK Myanma Kyat
MNT Mongolian Tugrik
MOP Macau Pataca
MRO Mauritanian Ouguiya
MUR Mauritian Rupee
MVR Maldivian Rufiyaa
MWK Malawi Kwacha
MXN Mexican Peso
MYR Malaysian Ringgit
MZN Mozambican Metical
NAD Namibian Dollar
NGN Nigerian Naira
NIO Nicaragua Cordoba
NOK Norwegian Krone
NPR Nepalese Rupee
NZD New Zealand Dollar
OMR Omani Rial
PAB Panamanian Balboa
PEN Peruvian Nuevo Sol
PGK Papua New Guinean Kina
PHP Philippine Peso
PKR Pakistani Rupee
PLN Polish Zloty
PYG Paraguayan Guarani
QAR Qatari Riyal
RON Romanian Leu
RSD Serbian Dinar
RUB Russian Ruble
RWF Rwanda Franc
SAR Saudi Riyal
SBD Solomon Islands Dollar
SCR Seychellois Rupee
SDG Sudanese Pound
SEK Swedish Krona
SGD Singapore Dollar
SHP Saint Helena Pound
SLL Sierra Leonean Leone
SOS Somali Shilling
SRD Surinamese Dollar
SSP South Sudanese Pound
STD Sao Tome and Principe Dobra
SYP Syrian Pound
SZL Swazi Lilangeni
THB Thai Baht
TJS Tajikistan Somoni
TMT Turkmenistani Manat
TND Tunisian Dinar
TOP Tonga Paanga
TRY Turkish Lira
TTD Trinidad and Tobago Dollar
TWD New Taiwan Dollar
TZS Tanzanian Shilling
UAH Ukrainian Hryvnia
UGX Ugandan Shilling
USD United States Dollar
UYU Uruguayan Peso
UZS Uzbekistan Som
VEF Venezuelan Bolivar
VND Vietnamese Dong
VUV Vanuatu Vatu
WST Samoan Tala
XAF Central African CFA franc
XCD East Caribbean Dollar
XOF West African CFA franc
XPF CFP Franc
YER Yemeni Rial
ZAR South African Rand
ZMW Zambian Kwacha
"""
def convert_currency(
from_: str = "USD", to: str = "INR", amount: float = 1.0, api_key: str = ""
) -> str:
"""https://www.amdoren.com/currency-api/"""
# Instead of manually generating parameters
params = locals()
# from is a reserved keyword
params["from"] = params.pop("from_")
res = httpx.get(URL_BASE, params=params, timeout=10).json()
return str(res["amount"]) if res["error"] == 0 else res["error_message"]
if __name__ == "__main__":
TESTING = os.getenv("CI", "")
API_KEY = os.getenv("AMDOREN_API_KEY", "")
if not API_KEY and not TESTING:
raise KeyError(
"API key must be provided in the 'AMDOREN_API_KEY' environment variable."
)
print(
convert_currency(
input("Enter from currency: ").strip(),
input("Enter to currency: ").strip(),
float(input("Enter the amount: ").strip()),
API_KEY,
)
)
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/covid_stats_via_xpath.py | web_programming/covid_stats_via_xpath.py | """
This script demonstrates fetching simple COVID-19 statistics from the
Worldometers archive site using lxml. lxml is chosen over BeautifulSoup
for its speed and convenience in Python web projects (such as Django or
Flask).
"""
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# "lxml",
# ]
# ///
from typing import NamedTuple
import httpx
from lxml import html
class CovidData(NamedTuple):
cases: str
deaths: str
recovered: str
def covid_stats(
url: str = (
"https://web.archive.org/web/20250825095350/"
"https://www.worldometers.info/coronavirus/"
),
) -> CovidData:
xpath_str = '//div[@class = "maincounter-number"]/span/text()'
try:
response = httpx.get(url, timeout=10).raise_for_status()
except httpx.TimeoutException:
print(
"Request timed out. Please check your network connection "
"or try again later."
)
return CovidData("N/A", "N/A", "N/A")
except httpx.HTTPStatusError as e:
print(f"HTTP error occurred: {e}")
return CovidData("N/A", "N/A", "N/A")
data = html.fromstring(response.content).xpath(xpath_str)
if len(data) != 3:
print("Unexpected data format. The page structure may have changed.")
data = "N/A", "N/A", "N/A"
return CovidData(*data)
if __name__ == "__main__":
fmt = (
"Total COVID-19 cases in the world: {}\n"
"Total deaths due to COVID-19 in the world: {}\n"
"Total COVID-19 patients recovered in the world: {}"
)
print(fmt.format(*covid_stats()))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/instagram_video.py | web_programming/instagram_video.py | # /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# ]
# ///
from datetime import UTC, datetime
import httpx
def download_video(url: str) -> bytes:
base_url = "https://downloadgram.net/wp-json/wppress/video-downloader/video?url="
video_url = httpx.get(base_url + url, timeout=10)
return httpx.get(video_url, timeout=10).content
if __name__ == "__main__":
url = input("Enter Video/IGTV url: ").strip()
file_name = f"{datetime.now(tz=UTC).astimezone():%Y-%m-%d_%H-%M-%S}.mp4"
with open(file_name, "wb") as fp:
fp.write(download_video(url))
print(f"Done. Video saved to disk as {file_name}.")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/open_google_results.py | web_programming/open_google_results.py | # /// script
# requires-python = ">=3.13"
# dependencies = [
# "beautifulsoup4",
# "fake-useragent",
# "httpx",
# ]
# ///
import webbrowser
from sys import argv
from urllib.parse import parse_qs, quote
import httpx
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
if __name__ == "__main__":
query = "%20".join(argv[1:]) if len(argv) > 1 else quote(str(input("Search: ")))
print("Googling.....")
url = f"https://www.google.com/search?q={query}&num=100"
res = httpx.get(
url,
headers={"User-Agent": str(UserAgent().random)},
timeout=10,
)
try:
link = BeautifulSoup(res.text, "html.parser").find("div").find("a").get("href")
except AttributeError:
link = parse_qs(
BeautifulSoup(res.text, "html.parser").find("div").find("a").get("href")
)["url"][0]
webbrowser.open(link)
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/instagram_pic.py | web_programming/instagram_pic.py | # /// script
# requires-python = ">=3.13"
# dependencies = [
# "beautifulsoup4",
# "httpx",
# ]
# ///
from datetime import UTC, datetime
import httpx
from bs4 import BeautifulSoup
def download_image(url: str) -> str:
"""
Download an image from a given URL by scraping the 'og:image' meta tag.
Parameters:
url: The URL to scrape.
Returns:
A message indicating the result of the operation.
"""
try:
response = httpx.get(url, timeout=10)
response.raise_for_status()
except httpx.RequestError as e:
return f"An error occurred during the HTTP request to {url}: {e!r}"
soup = BeautifulSoup(response.text, "html.parser")
image_meta_tag = soup.find("meta", {"property": "og:image"})
if not image_meta_tag:
return "No meta tag with property 'og:image' was found."
image_url = image_meta_tag.get("content")
if not image_url:
return f"Image URL not found in meta tag {image_meta_tag}."
try:
image_data = httpx.get(image_url, timeout=10).content
except httpx.RequestError as e:
return f"An error occurred during the HTTP request to {image_url}: {e!r}"
if not image_data:
return f"Failed to download the image from {image_url}."
file_name = f"{datetime.now(tz=UTC).astimezone():%Y-%m-%d_%H-%M-%S}.jpg"
with open(file_name, "wb") as out_file:
out_file.write(image_data)
return f"Image downloaded and saved in the file {file_name}"
if __name__ == "__main__":
url = input("Enter image URL: ").strip() or "https://www.instagram.com"
print(f"download_image({url}): {download_image(url)}")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/giphy.py | web_programming/giphy.py | #!/usr/bin/env python3
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# ]
# ///
import httpx
giphy_api_key = "YOUR API KEY"
# Can be fetched from https://developers.giphy.com/dashboard/
def get_gifs(query: str, api_key: str = giphy_api_key) -> list:
"""
Get a list of URLs of GIFs based on a given query..
"""
formatted_query = "+".join(query.split())
url = f"https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}"
gifs = httpx.get(url, timeout=10).json()["data"]
return [gif["url"] for gif in gifs]
if __name__ == "__main__":
print("\n".join(get_gifs("space ship")))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/nasa_data.py | web_programming/nasa_data.py | # /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# ]
# ///
import httpx
def get_apod_data(api_key: str) -> dict:
"""
Get the APOD(Astronomical Picture of the day) data
Get your API Key from: https://api.nasa.gov/
"""
url = "https://api.nasa.gov/planetary/apod"
return httpx.get(url, params={"api_key": api_key}, timeout=10).json()
def save_apod(api_key: str, path: str = ".") -> dict:
apod_data = get_apod_data(api_key)
img_url = apod_data["url"]
img_name = img_url.split("/")[-1]
response = httpx.get(img_url, timeout=10)
with open(f"{path}/{img_name}", "wb+") as img_file:
img_file.write(response.content)
del response
return apod_data
def get_archive_data(query: str) -> dict:
"""
Get the data of a particular query from NASA archives
"""
url = "https://images-api.nasa.gov/search"
return httpx.get(url, params={"q": query}, timeout=10).json()
if __name__ == "__main__":
print(save_apod("YOUR API KEY"))
apollo_2011_items = get_archive_data("apollo 2011")["collection"]["items"]
print(apollo_2011_items[0]["data"][0]["description"])
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/slack_message.py | web_programming/slack_message.py | # Created by sarathkaul on 12/11/19
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# ]
# ///
import httpx
def send_slack_message(message_body: str, slack_url: str) -> None:
headers = {"Content-Type": "application/json"}
response = httpx.post(
slack_url, json={"text": message_body}, headers=headers, timeout=10
)
if response.status_code != 200:
msg = (
"Request to slack returned an error "
f"{response.status_code}, the response is:\n{response.text}"
)
raise ValueError(msg)
if __name__ == "__main__":
# Set the slack url to the one provided by Slack when you create the webhook at
# https://my.slack.com/services/new/incoming-webhook/
send_slack_message("<YOUR MESSAGE BODY>", "<SLACK CHANNEL URL>")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/daily_horoscope.py | web_programming/daily_horoscope.py | # /// script
# requires-python = ">=3.13"
# dependencies = [
# "beautifulsoup4",
# "httpx",
# ]
# ///
import httpx
from bs4 import BeautifulSoup
def horoscope(zodiac_sign: int, day: str) -> str:
url = (
"https://www.horoscope.com/us/horoscopes/general/"
f"horoscope-general-daily-{day}.aspx?sign={zodiac_sign}"
)
soup = BeautifulSoup(httpx.get(url, timeout=10).content, "html.parser")
return soup.find("div", class_="main-horoscope").p.text
if __name__ == "__main__":
print("Daily Horoscope. \n")
print(
"enter your Zodiac sign number:\n",
"1. Aries\n",
"2. Taurus\n",
"3. Gemini\n",
"4. Cancer\n",
"5. Leo\n",
"6. Virgo\n",
"7. Libra\n",
"8. Scorpio\n",
"9. Sagittarius\n",
"10. Capricorn\n",
"11. Aquarius\n",
"12. Pisces\n",
)
zodiac_sign = int(input("number> ").strip())
print("choose some day:\n", "yesterday\n", "today\n", "tomorrow\n")
day = input("enter the day> ")
horoscope_text = horoscope(zodiac_sign, day)
print(horoscope_text)
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/fetch_well_rx_price.py | web_programming/fetch_well_rx_price.py | """
Scrape the price and pharmacy name for a prescription drug from rx site
after providing the drug name and zipcode.
"""
import httpx
from bs4 import BeautifulSoup
BASE_URL = "https://www.wellrx.com/prescriptions/{}/{}/?freshSearch=true"
def fetch_pharmacy_and_price_list(drug_name: str, zip_code: str) -> list | None:
"""[summary]
This function will take input of drug name and zipcode,
then request to the BASE_URL site.
Get the page data and scrape it to generate the
list of the lowest prices for the prescription drug.
Args:
drug_name (str): [Drug name]
zip_code(str): [Zip code]
Returns:
list: [List of pharmacy name and price]
>>> print(fetch_pharmacy_and_price_list(None, None))
None
>>> print(fetch_pharmacy_and_price_list(None, 30303))
None
>>> print(fetch_pharmacy_and_price_list("eliquis", None))
None
"""
try:
# Has user provided both inputs?
if not drug_name or not zip_code:
return None
request_url = BASE_URL.format(drug_name, zip_code)
response = httpx.get(request_url, timeout=10).raise_for_status()
# Scrape the data using bs4
soup = BeautifulSoup(response.text, "html.parser")
# This list will store the name and price.
pharmacy_price_list = []
# Fetch all the grids that contain the items.
grid_list = soup.find_all("div", {"class": "grid-x pharmCard"})
if grid_list and len(grid_list) > 0:
for grid in grid_list:
# Get the pharmacy price.
pharmacy_name = grid.find("p", {"class": "list-title"}).text
# Get the price of the drug.
price = grid.find("span", {"p", "price price-large"}).text
pharmacy_price_list.append(
{
"pharmacy_name": pharmacy_name,
"price": price,
}
)
return pharmacy_price_list
except (httpx.HTTPError, ValueError):
return None
if __name__ == "__main__":
# Enter a drug name and a zip code
drug_name = input("Enter drug name: ").strip()
zip_code = input("Enter zip code: ").strip()
pharmacy_price_list: list | None = fetch_pharmacy_and_price_list(
drug_name, zip_code
)
if pharmacy_price_list:
print(f"\nSearch results for {drug_name} at location {zip_code}:")
for pharmacy_price in pharmacy_price_list:
name = pharmacy_price["pharmacy_name"]
price = pharmacy_price["price"]
print(f"Pharmacy: {name} Price: {price}")
else:
print(f"No results found for {drug_name}")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/__init__.py | web_programming/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/search_books_by_isbn.py | web_programming/search_books_by_isbn.py | """
Get book and author data from https://openlibrary.org
ISBN: https://en.wikipedia.org/wiki/International_Standard_Book_Number
"""
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# ]
# ///
from json import JSONDecodeError
import httpx
def get_openlibrary_data(olid: str = "isbn/0140328726") -> dict:
"""
Given an 'isbn/0140328726', return book data from Open Library as a Python dict.
Given an '/authors/OL34184A', return authors data as a Python dict.
This code must work for olids with or without a leading slash ('/').
# Comment out doctests if they take too long or have results that may change
# >>> get_openlibrary_data(olid='isbn/0140328726') # doctest: +ELLIPSIS
{'publishers': ['Puffin'], 'number_of_pages': 96, 'isbn_10': ['0140328726'], ...
# >>> get_openlibrary_data(olid='/authors/OL7353617A') # doctest: +ELLIPSIS
{'name': 'Adrian Brisku', 'created': {'type': '/type/datetime', ...
"""
new_olid = olid.strip().strip("/") # Remove leading/trailing whitespace & slashes
if new_olid.count("/") != 1:
msg = f"{olid} is not a valid Open Library olid"
raise ValueError(msg)
return httpx.get(
f"https://openlibrary.org/{new_olid}.json", timeout=10, follow_redirects=True
).json()
def summarize_book(ol_book_data: dict) -> dict:
"""
Given Open Library book data, return a summary as a Python dict.
"""
desired_keys = {
"title": "Title",
"publish_date": "Publish date",
"authors": "Authors",
"number_of_pages": "Number of pages",
"isbn_10": "ISBN (10)",
"isbn_13": "ISBN (13)",
}
data = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()}
data["Authors"] = [
get_openlibrary_data(author["key"])["name"] for author in data["Authors"]
]
for key, value in data.items():
if isinstance(value, list):
data[key] = ", ".join(value)
return data
if __name__ == "__main__":
import doctest
doctest.testmod()
while True:
isbn = input("\nEnter the ISBN code to search (or 'quit' to stop): ").strip()
if isbn.lower() in ("", "q", "quit", "exit", "stop"):
break
if len(isbn) not in (10, 13) or not isbn.isdigit():
print(f"Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.")
continue
print(f"\nSearching Open Library for ISBN: {isbn}...\n")
try:
book_summary = summarize_book(get_openlibrary_data(f"isbn/{isbn}"))
print("\n".join(f"{key}: {value}" for key, value in book_summary.items()))
except JSONDecodeError:
print(f"Sorry, there are no results for ISBN: {isbn}.")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/get_imdb_top_250_movies_csv.py | web_programming/get_imdb_top_250_movies_csv.py | # /// script
# requires-python = ">=3.13"
# dependencies = [
# "beautifulsoup4",
# "httpx",
# ]
# ///
from __future__ import annotations
import csv
import httpx
from bs4 import BeautifulSoup
def get_imdb_top_250_movies(url: str = "") -> dict[str, float]:
url = url or "https://www.imdb.com/chart/top/?ref_=nv_mv_250"
soup = BeautifulSoup(httpx.get(url, timeout=10).text, "html.parser")
titles = soup.find_all("h3", class_="ipc-title__text")
ratings = soup.find_all("span", class_="ipc-rating-star--rating")
return {
title.a.text: float(rating.strong.text)
for title, rating in zip(titles, ratings)
}
def write_movies(filename: str = "IMDb_Top_250_Movies.csv") -> None:
movies = get_imdb_top_250_movies()
with open(filename, "w", newline="") as out_file:
writer = csv.writer(out_file)
writer.writerow(["Movie title", "IMDb rating"])
for title, rating in movies.items():
writer.writerow([title, rating])
if __name__ == "__main__":
write_movies()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/world_covid19_stats.py | web_programming/world_covid19_stats.py | #!/usr/bin/env python3
"""
Provide the current worldwide COVID-19 statistics.
This data is being scrapped from 'https://www.worldometers.info/coronavirus/'.
"""
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "beautifulsoup4",
# "httpx",
# ]
# ///
import httpx
from bs4 import BeautifulSoup
def world_covid19_stats(
url: str = "https://www.worldometers.info/coronavirus/",
) -> dict:
"""
Return a dict of current worldwide COVID-19 statistics
"""
soup = BeautifulSoup(
httpx.get(url, timeout=10, follow_redirects=True).text, "html.parser"
)
keys = soup.find_all("h1")
values = soup.find_all("div", {"class": "maincounter-number"})
keys += soup.find_all("span", {"class": "panel-title"})
values += soup.find_all("div", {"class": "number-table-main"})
return {key.text.strip(): value.text.strip() for key, value in zip(keys, values)}
if __name__ == "__main__":
print("\033[1m COVID-19 Status of the World \033[0m\n")
print("\n".join(f"{key}\n{value}" for key, value in world_covid19_stats().items()))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/crawl_google_results.py | web_programming/crawl_google_results.py | # /// script
# requires-python = ">=3.13"
# dependencies = [
# "beautifulsoup4",
# "fake-useragent",
# "httpx",
# ]
# ///
import sys
import webbrowser
import httpx
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
if __name__ == "__main__":
print("Googling.....")
url = "https://www.google.com/search?q=" + " ".join(sys.argv[1:])
res = httpx.get(
url,
headers={"UserAgent": UserAgent().random},
timeout=10,
follow_redirects=True,
)
# res.raise_for_status()
with open("project1a.html", "wb") as out_file: # only for knowing the class
for data in res.iter_content(10000):
out_file.write(data)
soup = BeautifulSoup(res.text, "html.parser")
links = list(soup.select(".eZt8xd"))[:5]
print(len(links))
for link in links:
if link.text == "Maps":
webbrowser.open(link.get("href"))
else:
webbrowser.open(f"https://google.com{link.get('href')}")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/instagram_crawler.py | web_programming/instagram_crawler.py | #!/usr/bin/env python3
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "beautifulsoup4",
# "fake-useragent",
# "httpx",
# ]
# ///
from __future__ import annotations
import json
import httpx
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
headers = {"UserAgent": UserAgent().random}
def extract_user_profile(script) -> dict:
"""
May raise json.decoder.JSONDecodeError
"""
data = script.contents[0]
info = json.loads(data[data.find('{"config"') : -1])
return info["entry_data"]["ProfilePage"][0]["graphql"]["user"]
class InstagramUser:
"""
Class Instagram crawl instagram user information
Usage: (doctest failing on GitHub Actions)
# >>> instagram_user = InstagramUser("github")
# >>> instagram_user.is_verified
True
# >>> instagram_user.biography
'Built for developers.'
"""
def __init__(self, username):
self.url = f"https://www.instagram.com/{username}/"
self.user_data = self.get_json()
def get_json(self) -> dict:
"""
Return a dict of user information
"""
html = httpx.get(self.url, headers=headers, timeout=10).text
scripts = BeautifulSoup(html, "html.parser").find_all("script")
try:
return extract_user_profile(scripts[4])
except (json.decoder.JSONDecodeError, KeyError):
return extract_user_profile(scripts[3])
def __repr__(self) -> str:
return f"{self.__class__.__name__}('{self.username}')"
def __str__(self) -> str:
return f"{self.fullname} ({self.username}) is {self.biography}"
@property
def username(self) -> str:
return self.user_data["username"]
@property
def fullname(self) -> str:
return self.user_data["full_name"]
@property
def biography(self) -> str:
return self.user_data["biography"]
@property
def email(self) -> str:
return self.user_data["business_email"]
@property
def website(self) -> str:
return self.user_data["external_url"]
@property
def number_of_followers(self) -> int:
return self.user_data["edge_followed_by"]["count"]
@property
def number_of_followings(self) -> int:
return self.user_data["edge_follow"]["count"]
@property
def number_of_posts(self) -> int:
return self.user_data["edge_owner_to_timeline_media"]["count"]
@property
def profile_picture_url(self) -> str:
return self.user_data["profile_pic_url_hd"]
@property
def is_verified(self) -> bool:
return self.user_data["is_verified"]
@property
def is_private(self) -> bool:
return self.user_data["is_private"]
def test_instagram_user(username: str = "github") -> None:
"""
A self running doctest
>>> test_instagram_user()
"""
import os
if os.environ.get("CI"):
return # test failing on GitHub Actions
instagram_user = InstagramUser(username)
assert instagram_user.user_data
assert isinstance(instagram_user.user_data, dict)
assert instagram_user.username == username
if username != "github":
return
assert instagram_user.fullname == "GitHub"
assert instagram_user.biography == "Built for developers."
assert instagram_user.number_of_posts > 150
assert instagram_user.number_of_followers > 120000
assert instagram_user.number_of_followings > 15
assert instagram_user.email == "support@github.com"
assert instagram_user.website == "https://github.com/readme"
assert instagram_user.profile_picture_url.startswith("https://instagram.")
assert instagram_user.is_verified is True
assert instagram_user.is_private is False
if __name__ == "__main__":
import doctest
doctest.testmod()
instagram_user = InstagramUser("github")
print(instagram_user)
print(f"{instagram_user.number_of_posts = }")
print(f"{instagram_user.number_of_followers = }")
print(f"{instagram_user.number_of_followings = }")
print(f"{instagram_user.email = }")
print(f"{instagram_user.website = }")
print(f"{instagram_user.profile_picture_url = }")
print(f"{instagram_user.is_verified = }")
print(f"{instagram_user.is_private = }")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/fetch_jobs.py | web_programming/fetch_jobs.py | """
Scraping jobs given job title and location from indeed website
"""
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "beautifulsoup4",
# "httpx",
# ]
# ///
from __future__ import annotations
from collections.abc import Generator
import httpx
from bs4 import BeautifulSoup
url = "https://www.indeed.co.in/jobs?q=mobile+app+development&l="
def fetch_jobs(location: str = "mumbai") -> Generator[tuple[str, str]]:
soup = BeautifulSoup(httpx.get(url + location, timeout=10).content, "html.parser")
# This attribute finds out all the specifics listed in a job
for job in soup.find_all("div", attrs={"data-tn-component": "organicJob"}):
job_title = job.find("a", attrs={"data-tn-element": "jobTitle"}).text.strip()
company_name = job.find("span", {"class": "company"}).text.strip()
yield job_title, company_name
if __name__ == "__main__":
for i, job in enumerate(fetch_jobs("Bangalore"), 1):
print(f"Job {i:>2} is {job[0]} at {job[1]}")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/get_top_billionaires.py | web_programming/get_top_billionaires.py | """
CAUTION: You may get a json.decoding error.
This works for some of us but fails for others.
"""
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# "rich",
# ]
# ///
from datetime import UTC, date, datetime
import httpx
from rich import box
from rich import console as rich_console
from rich import table as rich_table
LIMIT = 10
TODAY = datetime.now(tz=UTC)
API_URL = (
"https://www.forbes.com/forbesapi/person/rtb/0/position/true.json"
"?fields=personName,gender,source,countryOfCitizenship,birthDate,finalWorth"
f"&limit={LIMIT}"
)
def years_old(birth_timestamp: int, today: date | None = None) -> int:
"""
Calculate the age in years based on the given birth date. Only the year, month,
and day are used in the calculation. The time of day is ignored.
Args:
birth_timestamp: The date of birth.
today: (useful for writing tests) or if None then datetime.date.today().
Returns:
int: The age in years.
Examples:
>>> today = date(2024, 1, 12)
>>> years_old(birth_timestamp=datetime(1959, 11, 20).timestamp(), today=today)
64
>>> years_old(birth_timestamp=datetime(1970, 2, 13).timestamp(), today=today)
53
>>> all(
... years_old(datetime(today.year - i, 1, 12).timestamp(), today=today) == i
... for i in range(1, 111)
... )
True
"""
today = today or TODAY.date()
birth_date = datetime.fromtimestamp(birth_timestamp, tz=UTC).date()
return (today.year - birth_date.year) - (
(today.month, today.day) < (birth_date.month, birth_date.day)
)
def get_forbes_real_time_billionaires() -> list[dict[str, int | str]]:
"""
Get the top 10 real-time billionaires using Forbes API.
Returns:
List of top 10 realtime billionaires data.
"""
response_json = httpx.get(API_URL, timeout=10).json()
return [
{
"Name": person["personName"],
"Source": person["source"],
"Country": person["countryOfCitizenship"],
"Gender": person["gender"],
"Worth ($)": f"{person['finalWorth'] / 1000:.1f} Billion",
"Age": str(years_old(person["birthDate"] / 1000)),
}
for person in response_json["personList"]["personsLists"]
]
def display_billionaires(forbes_billionaires: list[dict[str, int | str]]) -> None:
"""
Display Forbes real-time billionaires in a rich table.
Args:
forbes_billionaires (list): Forbes top 10 real-time billionaires
"""
table = rich_table.Table(
title=f"Forbes Top {LIMIT} Real-Time Billionaires at {TODAY:%Y-%m-%d %H:%M}",
style="green",
highlight=True,
box=box.SQUARE,
)
for key in forbes_billionaires[0]:
table.add_column(key)
for billionaire in forbes_billionaires:
table.add_row(*billionaire.values())
rich_console.Console().print(table)
if __name__ == "__main__":
from doctest import testmod
testmod()
display_billionaires(get_forbes_real_time_billionaires())
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/download_images_from_google_query.py | web_programming/download_images_from_google_query.py | # /// script
# requires-python = ">=3.13"
# dependencies = [
# "beautifulsoup4",
# "httpx",
# ]
# ///
import json
import os
import re
import sys
import urllib.request
import httpx
from bs4 import BeautifulSoup
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
" (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}
def download_images_from_google_query(query: str = "dhaka", max_images: int = 5) -> int:
"""
Searches google using the provided query term and downloads the images in a folder.
Args:
query : The image search term to be provided by the user. Defaults to
"dhaka".
image_numbers : [description]. Defaults to 5.
Returns:
The number of images successfully downloaded.
# Comment out slow (4.20s call) doctests
# >>> download_images_from_google_query()
5
# >>> download_images_from_google_query("potato")
5
"""
max_images = min(max_images, 50) # Prevent abuse!
params = {
"q": query,
"tbm": "isch",
"hl": "en",
"ijn": "0",
}
html = httpx.get(
"https://www.google.com/search", params=params, headers=headers, timeout=10
)
soup = BeautifulSoup(html.text, "html.parser")
matched_images_data = "".join(
re.findall(r"AF_initDataCallback\(([^<]+)\);", str(soup.select("script")))
)
matched_images_data_fix = json.dumps(matched_images_data)
matched_images_data_json = json.loads(matched_images_data_fix)
matched_google_image_data = re.findall(
r"\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",",
matched_images_data_json,
)
if not matched_google_image_data:
return 0
removed_matched_google_images_thumbnails = re.sub(
r"\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]",
"",
str(matched_google_image_data),
)
matched_google_full_resolution_images = re.findall(
r"(?:'|,),\[\"(https:|http.*?)\",\d+,\d+\]",
removed_matched_google_images_thumbnails,
)
for index, fixed_full_res_image in enumerate(matched_google_full_resolution_images):
if index >= max_images:
return index
original_size_img_not_fixed = bytes(fixed_full_res_image, "ascii").decode(
"unicode-escape"
)
original_size_img = bytes(original_size_img_not_fixed, "ascii").decode(
"unicode-escape"
)
opener = urllib.request.build_opener()
opener.addheaders = [
(
"User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
" (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582",
)
]
urllib.request.install_opener(opener)
path_name = f"query_{query.replace(' ', '_')}"
if not os.path.exists(path_name):
os.makedirs(path_name)
urllib.request.urlretrieve( # noqa: S310
original_size_img, f"{path_name}/original_size_img_{index}.jpg"
)
return index
if __name__ == "__main__":
try:
image_count = download_images_from_google_query(sys.argv[1])
print(f"{image_count} images were downloaded to disk.")
except IndexError:
print("Please provide a search term.")
raise
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/current_weather.py | web_programming/current_weather.py | # /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# ]
# ///
import httpx
# Put your API key(s) here
OPENWEATHERMAP_API_KEY = ""
WEATHERSTACK_API_KEY = ""
# Define the URL for the APIs with placeholders
OPENWEATHERMAP_URL_BASE = "https://api.openweathermap.org/data/2.5/weather"
WEATHERSTACK_URL_BASE = "http://api.weatherstack.com/current"
def current_weather(location: str) -> list[dict]:
"""
>>> current_weather("location")
Traceback (most recent call last):
...
ValueError: No API keys provided or no valid data returned.
"""
weather_data = []
if OPENWEATHERMAP_API_KEY:
params_openweathermap = {"q": location, "appid": OPENWEATHERMAP_API_KEY}
response_openweathermap = httpx.get(
OPENWEATHERMAP_URL_BASE, params=params_openweathermap, timeout=10
)
weather_data.append({"OpenWeatherMap": response_openweathermap.json()})
if WEATHERSTACK_API_KEY:
params_weatherstack = {"query": location, "access_key": WEATHERSTACK_API_KEY}
response_weatherstack = httpx.get(
WEATHERSTACK_URL_BASE, params=params_weatherstack, timeout=10
)
weather_data.append({"Weatherstack": response_weatherstack.json()})
if not weather_data:
raise ValueError("No API keys provided or no valid data returned.")
return weather_data
if __name__ == "__main__":
from pprint import pprint
location = "to be determined..."
while location:
location = input("Enter a location (city name or latitude,longitude): ").strip()
if location:
try:
weather_data = current_weather(location)
for forecast in weather_data:
pprint(forecast)
except ValueError as e:
print(repr(e))
location = ""
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/co2_emission.py | web_programming/co2_emission.py | """
Get CO2 emission data from the UK CarbonIntensity API
"""
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# ]
# ///
from datetime import date
import httpx
BASE_URL = "https://api.carbonintensity.org.uk/intensity"
# Emission in the last half hour
def fetch_last_half_hour() -> str:
last_half_hour = httpx.get(BASE_URL, timeout=10).json()["data"][0]
return last_half_hour["intensity"]["actual"]
# Emissions in a specific date range
def fetch_from_to(start, end) -> list:
return httpx.get(f"{BASE_URL}/{start}/{end}", timeout=10).json()["data"]
if __name__ == "__main__":
for entry in fetch_from_to(start=date(2020, 10, 1), end=date(2020, 10, 3)):
print("from {from} to {to}: {intensity[actual]}".format(**entry))
print(f"{fetch_last_half_hour() = }")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/fetch_anime_and_play.py | web_programming/fetch_anime_and_play.py | # /// script
# requires-python = ">=3.13"
# dependencies = [
# "beautifulsoup4",
# "fake-useragent",
# "httpx",
# ]
# ///
import httpx
from bs4 import BeautifulSoup, NavigableString, Tag
from fake_useragent import UserAgent
BASE_URL = "https://ww7.gogoanime2.org"
def search_scraper(anime_name: str) -> list:
"""[summary]
Take an url and
return list of anime after scraping the site.
>>> type(search_scraper("demon_slayer"))
<class 'list'>
Args:
anime_name (str): [Name of anime]
Raises:
e: [Raises exception on failure]
Returns:
[list]: [List of animes]
"""
# concat the name to form the search url.
search_url = f"{BASE_URL}/search?keyword={anime_name}"
response = httpx.get(
search_url, headers={"UserAgent": UserAgent().chrome}, timeout=10
) # request the url.
# Is the response ok?
response.raise_for_status()
# parse with soup.
soup = BeautifulSoup(response.text, "html.parser")
# get list of anime
anime_ul = soup.find("ul", {"class": "items"})
if anime_ul is None or isinstance(anime_ul, NavigableString):
msg = f"Could not find and anime with name {anime_name}"
raise ValueError(msg)
anime_li = anime_ul.children
# for each anime, insert to list. the name and url.
anime_list = []
for anime in anime_li:
if isinstance(anime, Tag):
anime_url = anime.find("a")
if anime_url is None or isinstance(anime_url, NavigableString):
continue
anime_title = anime.find("a")
if anime_title is None or isinstance(anime_title, NavigableString):
continue
anime_list.append({"title": anime_title["title"], "url": anime_url["href"]})
return anime_list
def search_anime_episode_list(episode_endpoint: str) -> list:
"""[summary]
Take an url and
return list of episodes after scraping the site
for an url.
>>> type(search_anime_episode_list("/anime/kimetsu-no-yaiba"))
<class 'list'>
Args:
episode_endpoint (str): [Endpoint of episode]
Raises:
e: [description]
Returns:
[list]: [List of episodes]
"""
request_url = f"{BASE_URL}{episode_endpoint}"
response = httpx.get(
url=request_url, headers={"UserAgent": UserAgent().chrome}, timeout=10
)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
# With this id. get the episode list.
episode_page_ul = soup.find("ul", {"id": "episode_related"})
if episode_page_ul is None or isinstance(episode_page_ul, NavigableString):
msg = f"Could not find any anime eposiodes with name {anime_name}"
raise ValueError(msg)
episode_page_li = episode_page_ul.children
episode_list = []
for episode in episode_page_li:
if isinstance(episode, Tag):
url = episode.find("a")
if url is None or isinstance(url, NavigableString):
continue
title = episode.find("div", {"class": "name"})
if title is None or isinstance(title, NavigableString):
continue
episode_list.append(
{"title": title.text.replace(" ", ""), "url": url["href"]}
)
return episode_list
def get_anime_episode(episode_endpoint: str) -> list:
"""[summary]
Get click url and download url from episode url
>>> type(get_anime_episode("/watch/kimetsu-no-yaiba/1"))
<class 'list'>
Args:
episode_endpoint (str): [Endpoint of episode]
Raises:
e: [description]
Returns:
[list]: [List of download and watch url]
"""
episode_page_url = f"{BASE_URL}{episode_endpoint}"
response = httpx.get(
url=episode_page_url, headers={"User-Agent": UserAgent().chrome}, timeout=10
)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
url = soup.find("iframe", {"id": "playerframe"})
if url is None or isinstance(url, NavigableString):
msg = f"Could not find url and download url from {episode_endpoint}"
raise RuntimeError(msg)
episode_url = url["src"]
if not isinstance(episode_url, str):
msg = f"Could not find url and download url from {episode_endpoint}"
raise RuntimeError(msg)
download_url = episode_url.replace("/embed/", "/playlist/") + ".m3u8"
return [f"{BASE_URL}{episode_url}", f"{BASE_URL}{download_url}"]
if __name__ == "__main__":
anime_name = input("Enter anime name: ").strip()
anime_list = search_scraper(anime_name)
print("\n")
if len(anime_list) == 0:
print("No anime found with this name")
else:
print(f"Found {len(anime_list)} results: ")
for i, anime in enumerate(anime_list):
anime_title = anime["title"]
print(f"{i + 1}. {anime_title}")
anime_choice = int(input("\nPlease choose from the following list: ").strip())
chosen_anime = anime_list[anime_choice - 1]
print(f"You chose {chosen_anime['title']}. Searching for episodes...")
episode_list = search_anime_episode_list(chosen_anime["url"])
if len(episode_list) == 0:
print("No episode found for this anime")
else:
print(f"Found {len(episode_list)} results: ")
for i, episode in enumerate(episode_list):
print(f"{i + 1}. {episode['title']}")
episode_choice = int(input("\nChoose an episode by serial no: ").strip())
chosen_episode = episode_list[episode_choice - 1]
print(f"You chose {chosen_episode['title']}. Searching...")
episode_url, download_url = get_anime_episode(chosen_episode["url"])
print(f"\nTo watch, ctrl+click on {episode_url}.")
print(f"To download, ctrl+click on {download_url}.")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/web_programming/emails_from_url.py | web_programming/emails_from_url.py | """Get the site emails from URL."""
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# ]
# ///
from __future__ import annotations
__author__ = "Muhammad Umer Farooq"
__license__ = "MIT"
__version__ = "1.0.0"
__maintainer__ = "Muhammad Umer Farooq"
__email__ = "contact@muhammadumerfarooq.me"
__status__ = "Alpha"
import re
from html.parser import HTMLParser
from urllib import parse
import httpx
class Parser(HTMLParser):
def __init__(self, domain: str) -> None:
super().__init__()
self.urls: list[str] = []
self.domain = domain
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
"""
This function parse html to take takes url from tags
"""
# Only parse the 'anchor' tag.
if tag == "a":
# Check the list of defined attributes.
for name, value in attrs:
# If href is defined, not empty nor # print it and not already in urls.
if name == "href" and value not in (*self.urls, "", "#"):
url = parse.urljoin(self.domain, value)
self.urls.append(url)
# Get main domain name (example.com)
def get_domain_name(url: str) -> str:
"""
This function get the main domain name
>>> get_domain_name("https://a.b.c.d/e/f?g=h,i=j#k")
'c.d'
>>> get_domain_name("Not a URL!")
''
"""
return ".".join(get_sub_domain_name(url).split(".")[-2:])
# Get sub domain name (sub.example.com)
def get_sub_domain_name(url: str) -> str:
"""
>>> get_sub_domain_name("https://a.b.c.d/e/f?g=h,i=j#k")
'a.b.c.d'
>>> get_sub_domain_name("Not a URL!")
''
"""
return parse.urlparse(url).netloc
def emails_from_url(url: str = "https://github.com") -> list[str]:
"""
This function takes url and return all valid urls
"""
# Get the base domain from the url
domain = get_domain_name(url)
# Initialize the parser
parser = Parser(domain)
try:
# Open URL
r = httpx.get(url, timeout=10, follow_redirects=True)
# pass the raw HTML to the parser to get links
parser.feed(r.text)
# Get links and loop through
valid_emails = set()
for link in parser.urls:
# open URL.
# Check if the link is already absolute
if not link.startswith("http://") and not link.startswith("https://"):
# Prepend protocol only if link starts with domain, normalize otherwise
if link.startswith(domain):
link = f"https://{link}"
else:
link = parse.urljoin(f"https://{domain}", link)
try:
read = httpx.get(link, timeout=10, follow_redirects=True)
# Get the valid email.
emails = re.findall("[a-zA-Z0-9]+@" + domain, read.text)
# If not in list then append it.
for email in emails:
valid_emails.add(email)
except ValueError:
pass
except ValueError:
raise SystemExit(1)
# Finally return a sorted list of email addresses with no duplicates.
return sorted(valid_emails)
if __name__ == "__main__":
emails = emails_from_url("https://github.com")
print(f"{len(emails)} emails found:")
print("\n".join(sorted(emails)))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/divide_and_conquer/inversions.py | divide_and_conquer/inversions.py | """
Given an array-like data structure A[1..n], how many pairs
(i, j) for all 1 <= i < j <= n such that A[i] > A[j]? These pairs are
called inversions. Counting the number of such inversions in an array-like
object is the important. Among other things, counting inversions can help
us determine how close a given array is to being sorted.
In this implementation, I provide two algorithms, a divide-and-conquer
algorithm which runs in nlogn and the brute-force n^2 algorithm.
"""
def count_inversions_bf(arr):
"""
Counts the number of inversions using a naive brute-force algorithm
Parameters
----------
arr: arr: array-like, the list containing the items for which the number
of inversions is desired. The elements of `arr` must be comparable.
Returns
-------
num_inversions: The total number of inversions in `arr`
Examples
---------
>>> count_inversions_bf([1, 4, 2, 4, 1])
4
>>> count_inversions_bf([1, 1, 2, 4, 4])
0
>>> count_inversions_bf([])
0
"""
num_inversions = 0
n = len(arr)
for i in range(n - 1):
for j in range(i + 1, n):
if arr[i] > arr[j]:
num_inversions += 1
return num_inversions
def count_inversions_recursive(arr):
"""
Counts the number of inversions using a divide-and-conquer algorithm
Parameters
-----------
arr: array-like, the list containing the items for which the number
of inversions is desired. The elements of `arr` must be comparable.
Returns
-------
C: a sorted copy of `arr`.
num_inversions: int, the total number of inversions in 'arr'
Examples
--------
>>> count_inversions_recursive([1, 4, 2, 4, 1])
([1, 1, 2, 4, 4], 4)
>>> count_inversions_recursive([1, 1, 2, 4, 4])
([1, 1, 2, 4, 4], 0)
>>> count_inversions_recursive([])
([], 0)
"""
if len(arr) <= 1:
return arr, 0
mid = len(arr) // 2
p = arr[0:mid]
q = arr[mid:]
a, inversion_p = count_inversions_recursive(p)
b, inversions_q = count_inversions_recursive(q)
c, cross_inversions = _count_cross_inversions(a, b)
num_inversions = inversion_p + inversions_q + cross_inversions
return c, num_inversions
def _count_cross_inversions(p, q):
"""
Counts the inversions across two sorted arrays.
And combine the two arrays into one sorted array
For all 1<= i<=len(P) and for all 1 <= j <= len(Q),
if P[i] > Q[j], then (i, j) is a cross inversion
Parameters
----------
P: array-like, sorted in non-decreasing order
Q: array-like, sorted in non-decreasing order
Returns
------
R: array-like, a sorted array of the elements of `P` and `Q`
num_inversion: int, the number of inversions across `P` and `Q`
Examples
--------
>>> _count_cross_inversions([1, 2, 3], [0, 2, 5])
([0, 1, 2, 2, 3, 5], 4)
>>> _count_cross_inversions([1, 2, 3], [3, 4, 5])
([1, 2, 3, 3, 4, 5], 0)
"""
r = []
i = j = num_inversion = 0
while i < len(p) and j < len(q):
if p[i] > q[j]:
# if P[1] > Q[j], then P[k] > Q[k] for all i < k <= len(P)
# These are all inversions. The claim emerges from the
# property that P is sorted.
num_inversion += len(p) - i
r.append(q[j])
j += 1
else:
r.append(p[i])
i += 1
if i < len(p):
r.extend(p[i:])
else:
r.extend(q[j:])
return r, num_inversion
def main():
arr_1 = [10, 2, 1, 5, 5, 2, 11]
# this arr has 8 inversions:
# (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2)
num_inversions_bf = count_inversions_bf(arr_1)
_, num_inversions_recursive = count_inversions_recursive(arr_1)
assert num_inversions_bf == num_inversions_recursive == 8
print("number of inversions = ", num_inversions_bf)
# testing an array with zero inversion (a sorted arr_1)
arr_1.sort()
num_inversions_bf = count_inversions_bf(arr_1)
_, num_inversions_recursive = count_inversions_recursive(arr_1)
assert num_inversions_bf == num_inversions_recursive == 0
print("number of inversions = ", num_inversions_bf)
# an empty list should also have zero inversions
arr_1 = []
num_inversions_bf = count_inversions_bf(arr_1)
_, num_inversions_recursive = count_inversions_recursive(arr_1)
assert num_inversions_bf == num_inversions_recursive == 0
print("number of inversions = ", num_inversions_bf)
if __name__ == "__main__":
main()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/divide_and_conquer/peak.py | divide_and_conquer/peak.py | """
Finding the peak of a unimodal list using divide and conquer.
A unimodal array is defined as follows: array is increasing up to index p,
then decreasing afterwards. (for p >= 1)
An obvious solution can be performed in O(n),
to find the maximum of the array.
(From Kleinberg and Tardos. Algorithm Design.
Addison Wesley 2006: Chapter 5 Solved Exercise 1)
"""
from __future__ import annotations
def peak(lst: list[int]) -> int:
"""
Return the peak value of `lst`.
>>> peak([1, 2, 3, 4, 5, 4, 3, 2, 1])
5
>>> peak([1, 10, 9, 8, 7, 6, 5, 4])
10
>>> peak([1, 9, 8, 7])
9
>>> peak([1, 2, 3, 4, 5, 6, 7, 0])
7
>>> peak([1, 2, 3, 4, 3, 2, 1, 0, -1, -2])
4
"""
# middle index
m = len(lst) // 2
# choose the middle 3 elements
three = lst[m - 1 : m + 2]
# if middle element is peak
if three[1] > three[0] and three[1] > three[2]:
return three[1]
# if increasing, recurse on right
elif three[0] < three[2]:
if len(lst[:m]) == 2:
m -= 1
return peak(lst[m:])
# decreasing
else:
if len(lst[:m]) == 2:
m += 1
return peak(lst[:m])
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/heaps_algorithm.py | divide_and_conquer/heaps_algorithm.py | """
Heap's algorithm returns the list of all permutations possible from a list.
It minimizes movement by generating each permutation from the previous one
by swapping only two elements.
More information:
https://en.wikipedia.org/wiki/Heap%27s_algorithm.
"""
def heaps(arr: list) -> list:
"""
Pure python implementation of the Heap's algorithm (recursive version),
returning all permutations of a list.
>>> heaps([])
[()]
>>> heaps([0])
[(0,)]
>>> heaps([-1, 1])
[(-1, 1), (1, -1)]
>>> heaps([1, 2, 3])
[(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)]
>>> from itertools import permutations
>>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3]))
True
>>> all(sorted(heaps(x)) == sorted(permutations(x))
... for x in ([], [0], [-1, 1], [1, 2, 3]))
True
"""
if len(arr) <= 1:
return [tuple(arr)]
res = []
def generate(k: int, arr: list):
if k == 1:
res.append(tuple(arr[:]))
return
generate(k - 1, arr)
for i in range(k - 1):
if k % 2 == 0: # k is even
arr[i], arr[k - 1] = arr[k - 1], arr[i]
else: # k is odd
arr[0], arr[k - 1] = arr[k - 1], arr[0]
generate(k - 1, arr)
generate(len(arr), arr)
return res
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
arr = [int(item) for item in user_input.split(",")]
print(heaps(arr))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/divide_and_conquer/convex_hull.py | divide_and_conquer/convex_hull.py | """
The convex hull problem is problem of finding all the vertices of convex polygon, P of
a set of points in a plane such that all the points are either on the vertices of P or
inside P. TH convex hull problem has several applications in geometrical problems,
computer graphics and game development.
Two algorithms have been implemented for the convex hull problem here.
1. A brute-force algorithm which runs in O(n^3)
2. A divide-and-conquer algorithm which runs in O(n log(n))
There are other several other algorithms for the convex hull problem
which have not been implemented here, yet.
"""
from __future__ import annotations
from collections.abc import Iterable
class Point:
"""
Defines a 2-d point for use by all convex-hull algorithms.
Parameters
----------
x: an int or a float, the x-coordinate of the 2-d point
y: an int or a float, the y-coordinate of the 2-d point
Examples
--------
>>> Point(1, 2)
(1.0, 2.0)
>>> Point("1", "2")
(1.0, 2.0)
>>> Point(1, 2) > Point(0, 1)
True
>>> Point(1, 1) == Point(1, 1)
True
>>> Point(-0.5, 1) == Point(0.5, 1)
False
>>> Point("pi", "e")
Traceback (most recent call last):
...
ValueError: could not convert string to float: 'pi'
"""
def __init__(self, x, y):
self.x, self.y = float(x), float(y)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __ne__(self, other):
return not self == other
def __gt__(self, other):
if self.x > other.x:
return True
elif self.x == other.x:
return self.y > other.y
return False
def __lt__(self, other):
return not self > other
def __ge__(self, other):
if self.x > other.x:
return True
elif self.x == other.x:
return self.y >= other.y
return False
def __le__(self, other):
if self.x < other.x:
return True
elif self.x == other.x:
return self.y <= other.y
return False
def __repr__(self):
return f"({self.x}, {self.y})"
def __hash__(self):
return hash(self.x)
def _construct_points(
list_of_tuples: list[Point] | list[list[float]] | Iterable[list[float]],
) -> list[Point]:
"""
constructs a list of points from an array-like object of numbers
Arguments
---------
list_of_tuples: array-like object of type numbers. Acceptable types so far
are lists, tuples and sets.
Returns
--------
points: a list where each item is of type Point. This contains only objects
which can be converted into a Point.
Examples
-------
>>> _construct_points([[1, 1], [2, -1], [0.3, 4]])
[(1.0, 1.0), (2.0, -1.0), (0.3, 4.0)]
>>> _construct_points([1, 2])
Ignoring deformed point 1. All points must have at least 2 coordinates.
Ignoring deformed point 2. All points must have at least 2 coordinates.
[]
>>> _construct_points([])
[]
>>> _construct_points(None)
[]
"""
points: list[Point] = []
if list_of_tuples:
for p in list_of_tuples:
if isinstance(p, Point):
points.append(p)
else:
try:
points.append(Point(p[0], p[1]))
except (IndexError, TypeError):
print(
f"Ignoring deformed point {p}. All points"
" must have at least 2 coordinates."
)
return points
def _validate_input(points: list[Point] | list[list[float]]) -> list[Point]:
"""
validates an input instance before a convex-hull algorithms uses it
Parameters
---------
points: array-like, the 2d points to validate before using with
a convex-hull algorithm. The elements of points must be either lists, tuples or
Points.
Returns
-------
points: array_like, an iterable of all well-defined Points constructed passed in.
Exception
---------
ValueError: if points is empty or None, or if a wrong data structure like a scalar
is passed
TypeError: if an iterable but non-indexable object (eg. dictionary) is passed.
The exception to this a set which we'll convert to a list before using
Examples
-------
>>> _validate_input([[1, 2]])
[(1.0, 2.0)]
>>> _validate_input([(1, 2)])
[(1.0, 2.0)]
>>> _validate_input([Point(2, 1), Point(-1, 2)])
[(2.0, 1.0), (-1.0, 2.0)]
>>> _validate_input([])
Traceback (most recent call last):
...
ValueError: Expecting a list of points but got []
>>> _validate_input(1)
Traceback (most recent call last):
...
ValueError: Expecting an iterable object but got an non-iterable type 1
"""
if not hasattr(points, "__iter__"):
msg = f"Expecting an iterable object but got an non-iterable type {points}"
raise ValueError(msg)
if not points:
msg = f"Expecting a list of points but got {points}"
raise ValueError(msg)
return _construct_points(points)
def _det(a: Point, b: Point, c: Point) -> float:
"""
Computes the sign perpendicular distance of a 2d point c from a line segment
ab. The sign indicates the direction of c relative to ab.
A Positive value means c is above ab (to the left), while a negative value
means c is below ab (to the right). 0 means all three points are on a straight line.
As a side note, 0.5 * abs|det| is the area of triangle abc
Parameters
----------
a: point, the point on the left end of line segment ab
b: point, the point on the right end of line segment ab
c: point, the point for which the direction and location is desired.
Returns
--------
det: float, abs(det) is the distance of c from ab. The sign
indicates which side of line segment ab c is. det is computed as
(a_xb_y + c_xa_y + b_xc_y) - (a_yb_x + c_ya_x + b_yc_x)
Examples
----------
>>> _det(Point(1, 1), Point(1, 2), Point(1, 5))
0.0
>>> _det(Point(0, 0), Point(10, 0), Point(0, 10))
100.0
>>> _det(Point(0, 0), Point(10, 0), Point(0, -10))
-100.0
"""
det = (a.x * b.y + b.x * c.y + c.x * a.y) - (a.y * b.x + b.y * c.x + c.y * a.x)
return det
def convex_hull_bf(points: list[Point]) -> list[Point]:
"""
Constructs the convex hull of a set of 2D points using a brute force algorithm.
The algorithm basically considers all combinations of points (i, j) and uses the
definition of convexity to determine whether (i, j) is part of the convex hull or
not. (i, j) is part of the convex hull if and only iff there are no points on both
sides of the line segment connecting the ij, and there is no point k such that k is
on either end of the ij.
Runtime: O(n^3) - definitely horrible
Parameters
---------
points: array-like of object of Points, lists or tuples.
The set of 2d points for which the convex-hull is needed
Returns
------
convex_set: list, the convex-hull of points sorted in non-decreasing order.
See Also
--------
convex_hull_recursive,
Examples
---------
>>> convex_hull_bf([[0, 0], [1, 0], [10, 1]])
[(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)]
>>> convex_hull_bf([[0, 0], [1, 0], [10, 0]])
[(0.0, 0.0), (10.0, 0.0)]
>>> convex_hull_bf([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1],
... [-0.75, 1]])
[(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)]
>>> convex_hull_bf([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3),
... (2, -1), (2, -4), (1, -3)])
[(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)]
"""
points = sorted(_validate_input(points))
n = len(points)
convex_set = set()
for i in range(n - 1):
for j in range(i + 1, n):
points_left_of_ij = points_right_of_ij = False
ij_part_of_convex_hull = True
for k in range(n):
if k not in {i, j}:
det_k = _det(points[i], points[j], points[k])
if det_k > 0:
points_left_of_ij = True
elif det_k < 0:
points_right_of_ij = True
# point[i], point[j], point[k] all lie on a straight line
# if point[k] is to the left of point[i] or it's to the
# right of point[j], then point[i], point[j] cannot be
# part of the convex hull of A
elif points[k] < points[i] or points[k] > points[j]:
ij_part_of_convex_hull = False
break
if points_left_of_ij and points_right_of_ij:
ij_part_of_convex_hull = False
break
if ij_part_of_convex_hull:
convex_set.update([points[i], points[j]])
return sorted(convex_set)
def convex_hull_recursive(points: list[Point]) -> list[Point]:
"""
Constructs the convex hull of a set of 2D points using a divide-and-conquer strategy
The algorithm exploits the geometric properties of the problem by repeatedly
partitioning the set of points into smaller hulls, and finding the convex hull of
these smaller hulls. The union of the convex hull from smaller hulls is the
solution to the convex hull of the larger problem.
Parameter
---------
points: array-like of object of Points, lists or tuples.
The set of 2d points for which the convex-hull is needed
Runtime: O(n log n)
Returns
-------
convex_set: list, the convex-hull of points sorted in non-decreasing order.
Examples
---------
>>> convex_hull_recursive([[0, 0], [1, 0], [10, 1]])
[(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)]
>>> convex_hull_recursive([[0, 0], [1, 0], [10, 0]])
[(0.0, 0.0), (10.0, 0.0)]
>>> convex_hull_recursive([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1],
... [-0.75, 1]])
[(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)]
>>> convex_hull_recursive([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3),
... (2, -1), (2, -4), (1, -3)])
[(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)]
"""
points = sorted(_validate_input(points))
n = len(points)
# divide all the points into an upper hull and a lower hull
# the left most point and the right most point are definitely
# members of the convex hull by definition.
# use these two anchors to divide all the points into two hulls,
# an upper hull and a lower hull.
# all points to the left (above) the line joining the extreme points belong to the
# upper hull
# all points to the right (below) the line joining the extreme points below to the
# lower hull
# ignore all points on the line joining the extreme points since they cannot be
# part of the convex hull
left_most_point = points[0]
right_most_point = points[n - 1]
convex_set = {left_most_point, right_most_point}
upper_hull = []
lower_hull = []
for i in range(1, n - 1):
det = _det(left_most_point, right_most_point, points[i])
if det > 0:
upper_hull.append(points[i])
elif det < 0:
lower_hull.append(points[i])
_construct_hull(upper_hull, left_most_point, right_most_point, convex_set)
_construct_hull(lower_hull, right_most_point, left_most_point, convex_set)
return sorted(convex_set)
def _construct_hull(
points: list[Point], left: Point, right: Point, convex_set: set[Point]
) -> None:
"""
Parameters
---------
points: list or None, the hull of points from which to choose the next convex-hull
point
left: Point, the point to the left of line segment joining left and right
right: The point to the right of the line segment joining left and right
convex_set: set, the current convex-hull. The state of convex-set gets updated by
this function
Note
----
For the line segment 'ab', 'a' is on the left and 'b' on the right.
but the reverse is true for the line segment 'ba'.
Returns
-------
Nothing, only updates the state of convex-set
"""
if points:
extreme_point = None
extreme_point_distance = float("-inf")
candidate_points = []
for p in points:
det = _det(left, right, p)
if det > 0:
candidate_points.append(p)
if det > extreme_point_distance:
extreme_point_distance = det
extreme_point = p
if extreme_point:
_construct_hull(candidate_points, left, extreme_point, convex_set)
convex_set.add(extreme_point)
_construct_hull(candidate_points, extreme_point, right, convex_set)
def convex_hull_melkman(points: list[Point]) -> list[Point]:
"""
Constructs the convex hull of a set of 2D points using the melkman algorithm.
The algorithm works by iteratively inserting points of a simple polygonal chain
(meaning that no line segments between two consecutive points cross each other).
Sorting the points yields such a polygonal chain.
For a detailed description, see http://cgm.cs.mcgill.ca/~athens/cs601/Melkman.html
Runtime: O(n log n) - O(n) if points are already sorted in the input
Parameters
---------
points: array-like of object of Points, lists or tuples.
The set of 2d points for which the convex-hull is needed
Returns
------
convex_set: list, the convex-hull of points sorted in non-decreasing order.
See Also
--------
Examples
---------
>>> convex_hull_melkman([[0, 0], [1, 0], [10, 1]])
[(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)]
>>> convex_hull_melkman([[0, 0], [1, 0], [10, 0]])
[(0.0, 0.0), (10.0, 0.0)]
>>> convex_hull_melkman([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1],
... [-0.75, 1]])
[(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)]
>>> convex_hull_melkman([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3),
... (2, -1), (2, -4), (1, -3)])
[(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)]
"""
points = sorted(_validate_input(points))
n = len(points)
convex_hull = points[:2]
for i in range(2, n):
det = _det(convex_hull[1], convex_hull[0], points[i])
if det > 0:
convex_hull.insert(0, points[i])
break
elif det < 0:
convex_hull.append(points[i])
break
else:
convex_hull[1] = points[i]
i += 1
for j in range(i, n):
if (
_det(convex_hull[0], convex_hull[-1], points[j]) > 0
and _det(convex_hull[-1], convex_hull[0], points[1]) < 0
):
# The point lies within the convex hull
continue
convex_hull.insert(0, points[j])
convex_hull.append(points[j])
while _det(convex_hull[0], convex_hull[1], convex_hull[2]) >= 0:
del convex_hull[1]
while _det(convex_hull[-1], convex_hull[-2], convex_hull[-3]) <= 0:
del convex_hull[-2]
# `convex_hull` is contains the convex hull in circular order
return sorted(convex_hull[1:] if len(convex_hull) > 3 else convex_hull)
def main():
points = [
(0, 3),
(2, 2),
(1, 1),
(2, 1),
(3, 0),
(0, 0),
(3, 3),
(2, -1),
(2, -4),
(1, -3),
]
# the convex set of points is
# [(0, 0), (0, 3), (1, -3), (2, -4), (3, 0), (3, 3)]
results_bf = convex_hull_bf(points)
results_recursive = convex_hull_recursive(points)
assert results_bf == results_recursive
results_melkman = convex_hull_melkman(points)
assert results_bf == results_melkman
print(results_bf)
if __name__ == "__main__":
main()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/divide_and_conquer/power.py | divide_and_conquer/power.py | def actual_power(a: int, b: int) -> int:
"""
Function using divide and conquer to calculate a^b.
It only works for integer a,b.
:param a: The base of the power operation, an integer.
:param b: The exponent of the power operation, a non-negative integer.
:return: The result of a^b.
Examples:
>>> actual_power(3, 2)
9
>>> actual_power(5, 3)
125
>>> actual_power(2, 5)
32
>>> actual_power(7, 0)
1
"""
if b == 0:
return 1
half = actual_power(a, b // 2)
if (b % 2) == 0:
return half * half
else:
return a * half * half
def power(a: int, b: int) -> float:
"""
:param a: The base (integer).
:param b: The exponent (integer).
:return: The result of a^b, as a float for negative exponents.
>>> power(4,6)
4096
>>> power(2,3)
8
>>> power(-2,3)
-8
>>> power(2,-3)
0.125
>>> power(-2,-3)
-0.125
"""
if b < 0:
return 1 / actual_power(a, -b)
return actual_power(a, b)
if __name__ == "__main__":
print(power(-2, -3)) # output -0.125
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/divide_and_conquer/heaps_algorithm_iterative.py | divide_and_conquer/heaps_algorithm_iterative.py | """
Heap's (iterative) algorithm returns the list of all permutations possible from a list.
It minimizes movement by generating each permutation from the previous one
by swapping only two elements.
More information:
https://en.wikipedia.org/wiki/Heap%27s_algorithm.
"""
def heaps(arr: list) -> list:
"""
Pure python implementation of the iterative Heap's algorithm,
returning all permutations of a list.
>>> heaps([])
[()]
>>> heaps([0])
[(0,)]
>>> heaps([-1, 1])
[(-1, 1), (1, -1)]
>>> heaps([1, 2, 3])
[(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)]
>>> from itertools import permutations
>>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3]))
True
>>> all(sorted(heaps(x)) == sorted(permutations(x))
... for x in ([], [0], [-1, 1], [1, 2, 3]))
True
"""
if len(arr) <= 1:
return [tuple(arr)]
res = []
def generate(n: int, arr: list):
c = [0] * n
res.append(tuple(arr))
i = 0
while i < n:
if c[i] < i:
if i % 2 == 0:
arr[0], arr[i] = arr[i], arr[0]
else:
arr[c[i]], arr[i] = arr[i], arr[c[i]]
res.append(tuple(arr))
c[i] += 1
i = 0
else:
c[i] = 0
i += 1
generate(len(arr), arr)
return res
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
arr = [int(item) for item in user_input.split(",")]
print(heaps(arr))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/divide_and_conquer/max_subarray.py | divide_and_conquer/max_subarray.py | """
The maximum subarray problem is the task of finding the continuous subarray that has the
maximum sum within a given array of numbers. For example, given the array
[-2, 1, -3, 4, -1, 2, 1, -5, 4], the contiguous subarray with the maximum sum is
[4, -1, 2, 1], which has a sum of 6.
This divide-and-conquer algorithm finds the maximum subarray in O(n log n) time.
"""
from __future__ import annotations
import time
from collections.abc import Sequence
from random import randint
from matplotlib import pyplot as plt
def max_subarray(
arr: Sequence[float], low: int, high: int
) -> tuple[int | None, int | None, float]:
"""
Solves the maximum subarray problem using divide and conquer.
:param arr: the given array of numbers
:param low: the start index
:param high: the end index
:return: the start index of the maximum subarray, the end index of the
maximum subarray, and the maximum subarray sum
>>> nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
>>> max_subarray(nums, 0, len(nums) - 1)
(3, 6, 6)
>>> nums = [2, 8, 9]
>>> max_subarray(nums, 0, len(nums) - 1)
(0, 2, 19)
>>> nums = [0, 0]
>>> max_subarray(nums, 0, len(nums) - 1)
(0, 0, 0)
>>> nums = [-1.0, 0.0, 1.0]
>>> max_subarray(nums, 0, len(nums) - 1)
(2, 2, 1.0)
>>> nums = [-2, -3, -1, -4, -6]
>>> max_subarray(nums, 0, len(nums) - 1)
(2, 2, -1)
>>> max_subarray([], 0, 0)
(None, None, 0)
"""
if not arr:
return None, None, 0
if low == high:
return low, high, arr[low]
mid = (low + high) // 2
left_low, left_high, left_sum = max_subarray(arr, low, mid)
right_low, right_high, right_sum = max_subarray(arr, mid + 1, high)
cross_left, cross_right, cross_sum = max_cross_sum(arr, low, mid, high)
if left_sum >= right_sum and left_sum >= cross_sum:
return left_low, left_high, left_sum
elif right_sum >= left_sum and right_sum >= cross_sum:
return right_low, right_high, right_sum
return cross_left, cross_right, cross_sum
def max_cross_sum(
arr: Sequence[float], low: int, mid: int, high: int
) -> tuple[int, int, float]:
left_sum, max_left = float("-inf"), -1
right_sum, max_right = float("-inf"), -1
summ: int | float = 0
for i in range(mid, low - 1, -1):
summ += arr[i]
if summ > left_sum:
left_sum = summ
max_left = i
summ = 0
for i in range(mid + 1, high + 1):
summ += arr[i]
if summ > right_sum:
right_sum = summ
max_right = i
return max_left, max_right, (left_sum + right_sum)
def time_max_subarray(input_size: int) -> float:
arr = [randint(1, input_size) for _ in range(input_size)]
start = time.time()
max_subarray(arr, 0, input_size - 1)
end = time.time()
return end - start
def plot_runtimes() -> None:
input_sizes = [10, 100, 1000, 10000, 50000, 100000, 200000, 300000, 400000, 500000]
runtimes = [time_max_subarray(input_size) for input_size in input_sizes]
print("No of Inputs\t\tTime Taken")
for input_size, runtime in zip(input_sizes, runtimes):
print(input_size, "\t\t", runtime)
plt.plot(input_sizes, runtimes)
plt.xlabel("Number of Inputs")
plt.ylabel("Time taken in seconds")
plt.show()
if __name__ == "__main__":
"""
A random simulation of this algorithm.
"""
from doctest import testmod
testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/divide_and_conquer/mergesort.py | divide_and_conquer/mergesort.py | from __future__ import annotations
def merge(left_half: list, right_half: list) -> list:
"""Helper function for mergesort.
>>> left_half = [-2]
>>> right_half = [-1]
>>> merge(left_half, right_half)
[-2, -1]
>>> left_half = [1,2,3]
>>> right_half = [4,5,6]
>>> merge(left_half, right_half)
[1, 2, 3, 4, 5, 6]
>>> left_half = [-2]
>>> right_half = [-1]
>>> merge(left_half, right_half)
[-2, -1]
>>> left_half = [12, 15]
>>> right_half = [13, 14]
>>> merge(left_half, right_half)
[12, 13, 14, 15]
>>> left_half = []
>>> right_half = []
>>> merge(left_half, right_half)
[]
"""
sorted_array = [None] * (len(right_half) + len(left_half))
pointer1 = 0 # pointer to current index for left Half
pointer2 = 0 # pointer to current index for the right Half
index = 0 # pointer to current index for the sorted array Half
while pointer1 < len(left_half) and pointer2 < len(right_half):
if left_half[pointer1] < right_half[pointer2]:
sorted_array[index] = left_half[pointer1]
pointer1 += 1
index += 1
else:
sorted_array[index] = right_half[pointer2]
pointer2 += 1
index += 1
while pointer1 < len(left_half):
sorted_array[index] = left_half[pointer1]
pointer1 += 1
index += 1
while pointer2 < len(right_half):
sorted_array[index] = right_half[pointer2]
pointer2 += 1
index += 1
return sorted_array
def merge_sort(array: list) -> list:
"""Returns a list of sorted array elements using merge sort.
>>> from random import shuffle
>>> array = [-2, 3, -10, 11, 99, 100000, 100, -200]
>>> shuffle(array)
>>> merge_sort(array)
[-200, -10, -2, 3, 11, 99, 100, 100000]
>>> shuffle(array)
>>> merge_sort(array)
[-200, -10, -2, 3, 11, 99, 100, 100000]
>>> array = [-200]
>>> merge_sort(array)
[-200]
>>> array = [-2, 3, -10, 11, 99, 100000, 100, -200]
>>> shuffle(array)
>>> sorted(array) == merge_sort(array)
True
>>> array = [-2]
>>> merge_sort(array)
[-2]
>>> array = []
>>> merge_sort(array)
[]
>>> array = [10000000, 1, -1111111111, 101111111112, 9000002]
>>> sorted(array) == merge_sort(array)
True
"""
if len(array) <= 1:
return array
# the actual formula to calculate the middle element = left + (right - left) // 2
# this avoids integer overflow in case of large N
middle = 0 + (len(array) - 0) // 2
# Split the array into halves till the array length becomes equal to One
# merge the arrays of single length returned by mergeSort function and
# pass them into the merge arrays function which merges the array
left_half = array[:middle]
right_half = array[middle:]
return merge(merge_sort(left_half), merge_sort(right_half))
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/strassen_matrix_multiplication.py | divide_and_conquer/strassen_matrix_multiplication.py | from __future__ import annotations
import math
def default_matrix_multiplication(a: list, b: list) -> list:
"""
Multiplication only for 2x2 matrices
"""
if len(a) != 2 or len(a[0]) != 2 or len(b) != 2 or len(b[0]) != 2:
raise Exception("Matrices are not 2x2")
new_matrix = [
[a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]],
[a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]],
]
return new_matrix
def matrix_addition(matrix_a: list, matrix_b: list):
return [
[matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row]))]
for row in range(len(matrix_a))
]
def matrix_subtraction(matrix_a: list, matrix_b: list):
return [
[matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row]))]
for row in range(len(matrix_a))
]
def split_matrix(a: list) -> tuple[list, list, list, list]:
"""
Given an even length matrix, returns the top_left, top_right, bot_left, bot_right
quadrant.
>>> split_matrix([[4,3,2,4],[2,3,1,1],[6,5,4,3],[8,4,1,6]])
([[4, 3], [2, 3]], [[2, 4], [1, 1]], [[6, 5], [8, 4]], [[4, 3], [1, 6]])
>>> split_matrix([
... [4,3,2,4,4,3,2,4],[2,3,1,1,2,3,1,1],[6,5,4,3,6,5,4,3],[8,4,1,6,8,4,1,6],
... [4,3,2,4,4,3,2,4],[2,3,1,1,2,3,1,1],[6,5,4,3,6,5,4,3],[8,4,1,6,8,4,1,6]
... ]) # doctest: +NORMALIZE_WHITESPACE
([[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4],
[2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4], [2, 3, 1, 1],
[6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3],
[8, 4, 1, 6]])
"""
if len(a) % 2 != 0 or len(a[0]) % 2 != 0:
raise Exception("Odd matrices are not supported!")
matrix_length = len(a)
mid = matrix_length // 2
top_right = [[a[i][j] for j in range(mid, matrix_length)] for i in range(mid)]
bot_right = [
[a[i][j] for j in range(mid, matrix_length)] for i in range(mid, matrix_length)
]
top_left = [[a[i][j] for j in range(mid)] for i in range(mid)]
bot_left = [[a[i][j] for j in range(mid)] for i in range(mid, matrix_length)]
return top_left, top_right, bot_left, bot_right
def matrix_dimensions(matrix: list) -> tuple[int, int]:
return len(matrix), len(matrix[0])
def print_matrix(matrix: list) -> None:
print("\n".join(str(line) for line in matrix))
def actual_strassen(matrix_a: list, matrix_b: list) -> list:
"""
Recursive function to calculate the product of two matrices, using the Strassen
Algorithm. It only supports square matrices of any size that is a power of 2.
"""
if matrix_dimensions(matrix_a) == (2, 2):
return default_matrix_multiplication(matrix_a, matrix_b)
a, b, c, d = split_matrix(matrix_a)
e, f, g, h = split_matrix(matrix_b)
t1 = actual_strassen(a, matrix_subtraction(f, h))
t2 = actual_strassen(matrix_addition(a, b), h)
t3 = actual_strassen(matrix_addition(c, d), e)
t4 = actual_strassen(d, matrix_subtraction(g, e))
t5 = actual_strassen(matrix_addition(a, d), matrix_addition(e, h))
t6 = actual_strassen(matrix_subtraction(b, d), matrix_addition(g, h))
t7 = actual_strassen(matrix_subtraction(a, c), matrix_addition(e, f))
top_left = matrix_addition(matrix_subtraction(matrix_addition(t5, t4), t2), t6)
top_right = matrix_addition(t1, t2)
bot_left = matrix_addition(t3, t4)
bot_right = matrix_subtraction(matrix_subtraction(matrix_addition(t1, t5), t3), t7)
# construct the new matrix from our 4 quadrants
new_matrix = []
for i in range(len(top_right)):
new_matrix.append(top_left[i] + top_right[i])
for i in range(len(bot_right)):
new_matrix.append(bot_left[i] + bot_right[i])
return new_matrix
def strassen(matrix1: list, matrix2: list) -> list:
"""
>>> strassen([[2,1,3],[3,4,6],[1,4,2],[7,6,7]], [[4,2,3,4],[2,1,1,1],[8,6,4,2]])
[[34, 23, 19, 15], [68, 46, 37, 28], [28, 18, 15, 12], [96, 62, 55, 48]]
>>> strassen([[3,7,5,6,9],[1,5,3,7,8],[1,4,4,5,7]], [[2,4],[5,2],[1,7],[5,5],[7,8]])
[[139, 163], [121, 134], [100, 121]]
"""
if matrix_dimensions(matrix1)[1] != matrix_dimensions(matrix2)[0]:
msg = (
"Unable to multiply these matrices, please check the dimensions.\n"
f"Matrix A: {matrix1}\n"
f"Matrix B: {matrix2}"
)
raise Exception(msg)
dimension1 = matrix_dimensions(matrix1)
dimension2 = matrix_dimensions(matrix2)
if dimension1[0] == dimension1[1] and dimension2[0] == dimension2[1]:
return [matrix1, matrix2]
maximum = max(*dimension1, *dimension2)
maxim = int(math.pow(2, math.ceil(math.log2(maximum))))
new_matrix1 = matrix1
new_matrix2 = matrix2
# Adding zeros to the matrices to convert them both into square matrices of equal
# dimensions that are a power of 2
for i in range(maxim):
if i < dimension1[0]:
for _ in range(dimension1[1], maxim):
new_matrix1[i].append(0)
else:
new_matrix1.append([0] * maxim)
if i < dimension2[0]:
for _ in range(dimension2[1], maxim):
new_matrix2[i].append(0)
else:
new_matrix2.append([0] * maxim)
final_matrix = actual_strassen(new_matrix1, new_matrix2)
# Removing the additional zeros
for i in range(maxim):
if i < dimension1[0]:
for _ in range(dimension2[1], maxim):
final_matrix[i].pop()
else:
final_matrix.pop()
return final_matrix
if __name__ == "__main__":
matrix1 = [
[2, 3, 4, 5],
[6, 4, 3, 1],
[2, 3, 6, 7],
[3, 1, 2, 4],
[2, 3, 4, 5],
[6, 4, 3, 1],
[2, 3, 6, 7],
[3, 1, 2, 4],
[2, 3, 4, 5],
[6, 2, 3, 1],
]
matrix2 = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]]
print(strassen(matrix1, matrix2))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/divide_and_conquer/__init__.py | divide_and_conquer/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/divide_and_conquer/closest_pair_of_points.py | divide_and_conquer/closest_pair_of_points.py | """
The algorithm finds distance between closest pair of points
in the given n points.
Approach used -> Divide and conquer
The points are sorted based on Xco-ords and
then based on Yco-ords separately.
And by applying divide and conquer approach,
minimum distance is obtained recursively.
>> Closest points can lie on different sides of partition.
This case handled by forming a strip of points
whose Xco-ords distance is less than closest_pair_dis
from mid-point's Xco-ords. Points sorted based on Yco-ords
are used in this step to reduce sorting time.
Closest pair distance is found in the strip of points. (closest_in_strip)
min(closest_pair_dis, closest_in_strip) would be the final answer.
Time complexity: O(n * log n)
"""
def euclidean_distance_sqr(point1, point2):
"""
>>> euclidean_distance_sqr([1,2],[2,4])
5
"""
return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2
def column_based_sort(array, column=0):
"""
>>> column_based_sort([(5, 1), (4, 2), (3, 0)], 1)
[(3, 0), (5, 1), (4, 2)]
"""
return sorted(array, key=lambda x: x[column])
def dis_between_closest_pair(points, points_counts, min_dis=float("inf")):
"""
brute force approach to find distance between closest pair points
Parameters :
points, points_count, min_dis (list(tuple(int, int)), int, int)
Returns :
min_dis (float): distance between closest pair of points
>>> dis_between_closest_pair([[1,2],[2,4],[5,7],[8,9],[11,0]],5)
5
"""
for i in range(points_counts - 1):
for j in range(i + 1, points_counts):
current_dis = euclidean_distance_sqr(points[i], points[j])
min_dis = min(min_dis, current_dis)
return min_dis
def dis_between_closest_in_strip(points, points_counts, min_dis=float("inf")):
"""
closest pair of points in strip
Parameters :
points, points_count, min_dis (list(tuple(int, int)), int, int)
Returns :
min_dis (float): distance btw closest pair of points in the strip (< min_dis)
>>> dis_between_closest_in_strip([[1,2],[2,4],[5,7],[8,9],[11,0]],5)
85
"""
for i in range(min(6, points_counts - 1), points_counts):
for j in range(max(0, i - 6), i):
current_dis = euclidean_distance_sqr(points[i], points[j])
min_dis = min(min_dis, current_dis)
return min_dis
def closest_pair_of_points_sqr(points_sorted_on_x, points_sorted_on_y, points_counts):
"""divide and conquer approach
Parameters :
points, points_count (list(tuple(int, int)), int)
Returns :
(float): distance btw closest pair of points
>>> closest_pair_of_points_sqr([(1, 2), (3, 4)], [(5, 6), (7, 8)], 2)
8
"""
# base case
if points_counts <= 3:
return dis_between_closest_pair(points_sorted_on_x, points_counts)
# recursion
mid = points_counts // 2
closest_in_left = closest_pair_of_points_sqr(
points_sorted_on_x, points_sorted_on_y[:mid], mid
)
closest_in_right = closest_pair_of_points_sqr(
points_sorted_on_y, points_sorted_on_y[mid:], points_counts - mid
)
closest_pair_dis = min(closest_in_left, closest_in_right)
"""
cross_strip contains the points, whose Xcoords are at a
distance(< closest_pair_dis) from mid's Xcoord
"""
cross_strip = []
for point in points_sorted_on_x:
if abs(point[0] - points_sorted_on_x[mid][0]) < closest_pair_dis:
cross_strip.append(point)
closest_in_strip = dis_between_closest_in_strip(
cross_strip, len(cross_strip), closest_pair_dis
)
return min(closest_pair_dis, closest_in_strip)
def closest_pair_of_points(points, points_counts):
"""
>>> closest_pair_of_points([(2, 3), (12, 30)], len([(2, 3), (12, 30)]))
28.792360097775937
"""
points_sorted_on_x = column_based_sort(points, column=0)
points_sorted_on_y = column_based_sort(points, column=1)
return (
closest_pair_of_points_sqr(
points_sorted_on_x, points_sorted_on_y, points_counts
)
) ** 0.5
if __name__ == "__main__":
points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)]
print("Distance:", closest_pair_of_points(points, len(points)))
| 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.