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/project_euler/problem_551/sol1.py
project_euler/problem_551/sol1.py
""" Sum of digits sequence Problem 551 Let a(0), a(1),... be an integer sequence defined by: a(0) = 1 for n >= 1, a(n) is the sum of the digits of all preceding terms The sequence starts with 1, 1, 2, 4, 8, ... You are given a(10^6) = 31054319. Find a(10^15) """ ks = range(2, 20 + 1) base = [10**k for k in range(ks[-1] + 1)] memo: dict[int, dict[int, list[list[int]]]] = {} def next_term(a_i, k, i, n): """ Calculates and updates a_i in-place to either the n-th term or the smallest term for which c > 10^k when the terms are written in the form: a(i) = b * 10^k + c For any a(i), if digitsum(b) and c have the same value, the difference between subsequent terms will be the same until c >= 10^k. This difference is cached to greatly speed up the computation. Arguments: a_i -- array of digits starting from the one's place that represent the i-th term in the sequence k -- k when terms are written in the from a(i) = b*10^k + c. Term are calulcated until c > 10^k or the n-th term is reached. i -- position along the sequence n -- term to calculate up to if k is large enough Return: a tuple of difference between ending term and starting term, and the number of terms calculated. ex. if starting term is a_0=1, and ending term is a_10=62, then (61, 9) is returned. """ # ds_b - digitsum(b) ds_b = sum(a_i[j] for j in range(k, len(a_i))) c = sum(a_i[j] * base[j] for j in range(min(len(a_i), k))) diff, dn = 0, 0 max_dn = n - i sub_memo = memo.get(ds_b) if sub_memo is not None: jumps = sub_memo.get(c) if jumps is not None and len(jumps) > 0: # find and make the largest jump without going over max_jump = -1 for _k in range(len(jumps) - 1, -1, -1): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: max_jump = _k break if max_jump >= 0: diff, dn, _kk = jumps[max_jump] # since the difference between jumps is cached, add c new_c = diff + c for j in range(min(k, len(a_i))): new_c, a_i[j] = divmod(new_c, 10) if new_c > 0: add(a_i, k, new_c) else: sub_memo[c] = [] else: sub_memo = {c: []} memo[ds_b] = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps _diff, terms_jumped = next_term(a_i, k - 1, i + dn, n) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead _diff, terms_jumped = compute(a_i, k, i + dn, n) diff += _diff dn += terms_jumped jumps = sub_memo[c] # keep jumps sorted by # of terms skipped j = 0 while j < len(jumps): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(j, (diff, dn, k)) return (diff, dn) def compute(a_i, k, i, n): """ same as next_term(a_i, k, i, n) but computes terms without memoizing results. """ if i >= n: return 0, i if k > len(a_i): a_i.extend([0 for _ in range(k - len(a_i))]) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) start_i = i ds_b, ds_c, diff = 0, 0, 0 for j in range(len(a_i)): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 addend = ds_c + ds_b diff += addend ds_c = 0 for j in range(k): s = a_i[j] + addend addend, a_i[j] = divmod(s, 10) ds_c += a_i[j] if addend > 0: break if addend > 0: add(a_i, k, addend) return diff, i - start_i def add(digits, k, addend): """ adds addend to digit array given in digits starting at index k """ for j in range(k, len(digits)): s = digits[j] + addend if s >= 10: quotient, digits[j] = divmod(s, 10) addend = addend // 10 + quotient else: digits[j] = s addend = addend // 10 if addend == 0: break while addend > 0: addend, digit = divmod(addend, 10) digits.append(digit) def solution(n: int = 10**15) -> int: """ returns n-th term of sequence >>> solution(10) 62 >>> solution(10**6) 31054319 >>> solution(10**15) 73597483551591773 """ digits = [1] i = 1 dn = 0 while True: _diff, terms_jumped = next_term(digits, 20, i + dn, n) dn += terms_jumped if dn == n - i: break a_n = 0 for j in range(len(digits)): a_n += digits[j] * 10**j return a_n if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_551/__init__.py
project_euler/problem_551/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_034/sol1.py
project_euler/problem_034/sol1.py
""" Problem 34: https://projecteuler.net/problem=34 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. Find the sum of all numbers which are equal to the sum of the factorial of their digits. Note: As 1! = 1 and 2! = 2 are not sums they are not included. """ from math import factorial DIGIT_FACTORIAL = {str(d): factorial(d) for d in range(10)} def sum_of_digit_factorial(n: int) -> int: """ Returns the sum of the factorial of digits in n >>> sum_of_digit_factorial(15) 121 >>> sum_of_digit_factorial(0) 1 """ return sum(DIGIT_FACTORIAL[d] for d in str(n)) def solution() -> int: """ Returns the sum of all numbers whose sum of the factorials of all digits add up to the number itself. >>> solution() 40730 """ limit = 7 * factorial(9) + 1 return sum(i for i in range(3, limit) if sum_of_digit_factorial(i) == i) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_034/__init__.py
project_euler/problem_034/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_070/sol1.py
project_euler/problem_070/sol1.py
""" Project Euler Problem 70: https://projecteuler.net/problem=70 Euler's Totient function, φ(n) [sometimes called the phi function], is used to determine the number of positive numbers less than or equal to n which are relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively prime to nine, φ(9)=6. The number 1 is considered to be relatively prime to every positive number, so φ(1)=1. Interestingly, φ(87109)=79180, and it can be seen that 87109 is a permutation of 79180. Find the value of n, 1 < n < 10^7, for which φ(n) is a permutation of n and the ratio n/φ(n) produces a minimum. ----- This is essentially brute force. Calculate all totients up to 10^7 and find the minimum ratio of n/φ(n) that way. To minimize the ratio, we want to minimize n and maximize φ(n) as much as possible, so we can store the minimum fraction's numerator and denominator and calculate new fractions with each totient to compare against. To avoid dividing by zero, I opt to use cross multiplication. References: Finding totients https://en.wikipedia.org/wiki/Euler's_totient_function#Euler's_product_formula """ from __future__ import annotations import numpy as np def get_totients(max_one: int) -> list[int]: """ Calculates a list of totients from 0 to max_one exclusive, using the definition of Euler's product formula. >>> get_totients(5) [0, 1, 1, 2, 2] >>> get_totients(10) [0, 1, 1, 2, 2, 4, 2, 6, 4, 6] """ totients = np.arange(max_one) for i in range(2, max_one): if totients[i] == i: x = np.arange(i, max_one, i) # array of indexes to select totients[x] -= totients[x] // i return totients.tolist() def has_same_digits(num1: int, num2: int) -> bool: """ Return True if num1 and num2 have the same frequency of every digit, False otherwise. >>> has_same_digits(123456789, 987654321) True >>> has_same_digits(123, 23) False >>> has_same_digits(1234566, 123456) False """ return sorted(str(num1)) == sorted(str(num2)) def solution(max_n: int = 10000000) -> int: """ Finds the value of n from 1 to max such that n/φ(n) produces a minimum. >>> solution(100) 21 >>> solution(10000) 4435 """ min_numerator = 1 # i min_denominator = 0 # φ(i) totients = get_totients(max_n + 1) for i in range(2, max_n + 1): t = totients[i] if i * min_denominator < min_numerator * t and has_same_digits(i, t): min_numerator = i min_denominator = t return min_numerator if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_070/__init__.py
project_euler/problem_070/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_095/sol1.py
project_euler/problem_095/sol1.py
""" Project Euler Problem 95: https://projecteuler.net/problem=95 Amicable Chains The proper divisors of a number are all the divisors excluding the number itself. For example, the proper divisors of 28 are 1, 2, 4, 7, and 14. As the sum of these divisors is equal to 28, we call it a perfect number. Interestingly the sum of the proper divisors of 220 is 284 and the sum of the proper divisors of 284 is 220, forming a chain of two numbers. For this reason, 220 and 284 are called an amicable pair. Perhaps less well known are longer chains. For example, starting with 12496, we form a chain of five numbers: 12496 -> 14288 -> 15472 -> 14536 -> 14264 (-> 12496 -> ...) Since this chain returns to its starting point, it is called an amicable chain. Find the smallest member of the longest amicable chain with no element exceeding one million. Solution is doing the following: - Get relevant prime numbers - Iterate over product combination of prime numbers to generate all non-prime numbers up to max number, by keeping track of prime factors - Calculate the sum of factors for each number - Iterate over found some factors to find longest chain """ from math import isqrt def generate_primes(max_num: int) -> list[int]: """ Calculates the list of primes up to and including `max_num`. >>> generate_primes(6) [2, 3, 5] """ are_primes = [True] * (max_num + 1) are_primes[0] = are_primes[1] = False for i in range(2, isqrt(max_num) + 1): if are_primes[i]: for j in range(i * i, max_num + 1, i): are_primes[j] = False return [prime for prime, is_prime in enumerate(are_primes) if is_prime] def multiply( chain: list[int], primes: list[int], min_prime_idx: int, prev_num: int, max_num: int, prev_sum: int, primes_degrees: dict[int, int], ) -> None: """ Run over all prime combinations to generate non-prime numbers. >>> chain = [0] * 3 >>> primes_degrees = {} >>> multiply( ... chain=chain, ... primes=[2], ... min_prime_idx=0, ... prev_num=1, ... max_num=2, ... prev_sum=0, ... primes_degrees=primes_degrees, ... ) >>> chain [0, 0, 1] >>> primes_degrees {2: 1} """ min_prime = primes[min_prime_idx] num = prev_num * min_prime min_prime_degree = primes_degrees.get(min_prime, 0) min_prime_degree += 1 primes_degrees[min_prime] = min_prime_degree new_sum = prev_sum * min_prime + (prev_sum + prev_num) * (min_prime - 1) // ( min_prime**min_prime_degree - 1 ) chain[num] = new_sum for prime_idx in range(min_prime_idx, len(primes)): if primes[prime_idx] * num > max_num: break multiply( chain=chain, primes=primes, min_prime_idx=prime_idx, prev_num=num, max_num=max_num, prev_sum=new_sum, primes_degrees=primes_degrees.copy(), ) def find_longest_chain(chain: list[int], max_num: int) -> int: """ Finds the smallest element of longest chain >>> find_longest_chain(chain=[0, 0, 0, 0, 0, 0, 6], max_num=6) 6 """ max_len = 0 min_elem = 0 for start in range(2, len(chain)): visited = {start} elem = chain[start] length = 1 while elem > 1 and elem <= max_num and elem not in visited: visited.add(elem) elem = chain[elem] length += 1 if elem == start and length > max_len: max_len = length min_elem = start return min_elem def solution(max_num: int = 1000000) -> int: """ Runs the calculation for numbers <= `max_num`. >>> solution(10) 6 >>> solution(200000) 12496 """ primes = generate_primes(max_num) chain = [0] * (max_num + 1) for prime_idx, prime in enumerate(primes): if prime**2 > max_num: break multiply( chain=chain, primes=primes, min_prime_idx=prime_idx, prev_num=1, max_num=max_num, prev_sum=0, primes_degrees={}, ) return find_longest_chain(chain=chain, max_num=max_num) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_095/__init__.py
project_euler/problem_095/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_054/sol1.py
project_euler/problem_054/sol1.py
""" Problem: https://projecteuler.net/problem=54 In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way: High Card: Highest value card. One Pair: Two cards of the same value. Two Pairs: Two different pairs. Three of a Kind: Three cards of the same value. Straight: All cards are consecutive values. Flush: All cards of the same suit. Full House: Three of a kind and a pair. Four of a Kind: Four cards of the same value. Straight Flush: All cards are consecutive values of same suit. Royal Flush: Ten, Jack, Queen, King, Ace, in same suit. The cards are valued in the order: 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace. If two players have the same ranked hands then the rank made up of the highest value wins; for example, a pair of eights beats a pair of fives. But if two ranks tie, for example, both players have a pair of queens, then highest cards in each hand are compared; if the highest cards tie then the next highest cards are compared, and so on. The file, poker.txt, contains one-thousand random hands dealt to two players. Each line of the file contains ten cards (separated by a single space): the first five are Player 1's cards and the last five are Player 2's cards. You can assume that all hands are valid (no invalid characters or repeated cards), each player's hand is in no specific order, and in each hand there is a clear winner. How many hands does Player 1 win? Resources used: https://en.wikipedia.org/wiki/Texas_hold_%27em https://en.wikipedia.org/wiki/List_of_poker_hands Similar problem on codewars: https://www.codewars.com/kata/ranking-poker-hands https://www.codewars.com/kata/sortable-poker-hands """ from __future__ import annotations import os class PokerHand: """Create an object representing a Poker Hand based on an input of a string which represents the best 5-card combination from the player's hand and board cards. Attributes: (read-only) hand: a string representing the hand consisting of five cards Methods: compare_with(opponent): takes in player's hand (self) and opponent's hand (opponent) and compares both hands according to the rules of Texas Hold'em. Returns one of 3 strings (Win, Loss, Tie) based on whether player's hand is better than the opponent's hand. hand_name(): Returns a string made up of two parts: hand name and high card. Supported operators: Rich comparison operators: <, >, <=, >=, ==, != Supported built-in methods and functions: list.sort(), sorted() """ _HAND_NAME = ( "High card", "One pair", "Two pairs", "Three of a kind", "Straight", "Flush", "Full house", "Four of a kind", "Straight flush", "Royal flush", ) _CARD_NAME = ( "", # placeholder as tuples are zero-indexed "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace", ) def __init__(self, hand: str) -> None: """ Initialize hand. Hand should of type str and should contain only five cards each separated by a space. The cards should be of the following format: [card value][card suit] The first character is the value of the card: 2, 3, 4, 5, 6, 7, 8, 9, T(en), J(ack), Q(ueen), K(ing), A(ce) The second character represents the suit: S(pades), H(earts), D(iamonds), C(lubs) For example: "6S 4C KC AS TH" """ if not isinstance(hand, str): msg = f"Hand should be of type 'str': {hand!r}" raise TypeError(msg) # split removes duplicate whitespaces so no need of strip if len(hand.split(" ")) != 5: msg = f"Hand should contain only 5 cards: {hand!r}" raise ValueError(msg) self._hand = hand self._first_pair = 0 self._second_pair = 0 self._card_values, self._card_suit = self._internal_state() self._hand_type = self._get_hand_type() self._high_card = self._card_values[0] @property def hand(self): """Returns the self hand""" return self._hand def compare_with(self, other: PokerHand) -> str: """ Determines the outcome of comparing self hand with other hand. Returns the output as 'Win', 'Loss', 'Tie' according to the rules of Texas Hold'em. Here are some examples: >>> player = PokerHand("2H 3H 4H 5H 6H") # Stright flush >>> opponent = PokerHand("KS AS TS QS JS") # Royal flush >>> player.compare_with(opponent) 'Loss' >>> player = PokerHand("2S AH 2H AS AC") # Full house >>> opponent = PokerHand("2H 3H 5H 6H 7H") # Flush >>> player.compare_with(opponent) 'Win' >>> player = PokerHand("2S AH 4H 5S 6C") # High card >>> opponent = PokerHand("AD 4C 5H 6H 2C") # High card >>> player.compare_with(opponent) 'Tie' """ # Breaking the tie works on the following order of precedence: # 1. First pair (default 0) # 2. Second pair (default 0) # 3. Compare all cards in reverse order because they are sorted. # First pair and second pair will only be a non-zero value if the card # type is either from the following: # 21: Four of a kind # 20: Full house # 17: Three of a kind # 16: Two pairs # 15: One pair if self._hand_type > other._hand_type: return "Win" elif self._hand_type < other._hand_type: return "Loss" elif self._first_pair == other._first_pair: if self._second_pair == other._second_pair: return self._compare_cards(other) else: return "Win" if self._second_pair > other._second_pair else "Loss" return "Win" if self._first_pair > other._first_pair else "Loss" # This function is not part of the problem, I did it just for fun def hand_name(self) -> str: """ Return the name of the hand in the following format: 'hand name, high card' Here are some examples: >>> PokerHand("KS AS TS QS JS").hand_name() 'Royal flush' >>> PokerHand("2D 6D 3D 4D 5D").hand_name() 'Straight flush, Six-high' >>> PokerHand("JC 6H JS JD JH").hand_name() 'Four of a kind, Jacks' >>> PokerHand("3D 2H 3H 2C 2D").hand_name() 'Full house, Twos over Threes' >>> PokerHand("2H 4D 3C AS 5S").hand_name() # Low ace 'Straight, Five-high' Source: https://en.wikipedia.org/wiki/List_of_poker_hands """ name = PokerHand._HAND_NAME[self._hand_type - 14] high = PokerHand._CARD_NAME[self._high_card] pair1 = PokerHand._CARD_NAME[self._first_pair] pair2 = PokerHand._CARD_NAME[self._second_pair] if self._hand_type in [22, 19, 18]: return name + f", {high}-high" elif self._hand_type in [21, 17, 15]: return name + f", {pair1}s" elif self._hand_type in [20, 16]: join = "over" if self._hand_type == 20 else "and" return name + f", {pair1}s {join} {pair2}s" elif self._hand_type == 23: return name else: return name + f", {high}" def _compare_cards(self, other: PokerHand) -> str: # Enumerate gives us the index as well as the element of a list for index, card_value in enumerate(self._card_values): if card_value != other._card_values[index]: return "Win" if card_value > other._card_values[index] else "Loss" return "Tie" def _get_hand_type(self) -> int: # Number representing the type of hand internally: # 23: Royal flush # 22: Straight flush # 21: Four of a kind # 20: Full house # 19: Flush # 18: Straight # 17: Three of a kind # 16: Two pairs # 15: One pair # 14: High card if self._is_flush(): if self._is_five_high_straight() or self._is_straight(): return 23 if sum(self._card_values) == 60 else 22 return 19 elif self._is_five_high_straight() or self._is_straight(): return 18 return 14 + self._is_same_kind() def _is_flush(self) -> bool: return len(self._card_suit) == 1 def _is_five_high_straight(self) -> bool: # If a card is a five high straight (low ace) change the location of # ace from the start of the list to the end. Check whether the first # element is ace or not. (Don't want to change again) # Five high straight (low ace): AH 2H 3S 4C 5D # Why use sorted here? One call to this function will mutate the list to # [5, 4, 3, 2, 14] and so for subsequent calls (which will be rare) we # need to compare the sorted version. # Refer test_multiple_calls_five_high_straight in test_poker_hand.py if sorted(self._card_values) == [2, 3, 4, 5, 14]: if self._card_values[0] == 14: # Remember, our list is sorted in reverse order ace_card = self._card_values.pop(0) self._card_values.append(ace_card) return True return False def _is_straight(self) -> bool: for i in range(4): if self._card_values[i] - self._card_values[i + 1] != 1: return False return True def _is_same_kind(self) -> int: # Kind Values for internal use: # 7: Four of a kind # 6: Full house # 3: Three of a kind # 2: Two pairs # 1: One pair # 0: False kind = val1 = val2 = 0 for i in range(4): # Compare two cards at a time, if they are same increase 'kind', # add the value of the card to val1, if it is repeating again we # will add 2 to 'kind' as there are now 3 cards with same value. # If we get card of different value than val1, we will do the same # thing with val2 if self._card_values[i] == self._card_values[i + 1]: if not val1: val1 = self._card_values[i] kind += 1 elif val1 == self._card_values[i]: kind += 2 elif not val2: val2 = self._card_values[i] kind += 1 elif val2 == self._card_values[i]: kind += 2 # For consistency in hand type (look at note in _get_hand_type function) kind = kind + 2 if kind in [4, 5] else kind # first meaning first pair to compare in 'compare_with' first = max(val1, val2) second = min(val1, val2) # If it's full house (three count pair + two count pair), make sure # first pair is three count and if not then switch them both. if kind == 6 and self._card_values.count(first) != 3: first, second = second, first self._first_pair = first self._second_pair = second return kind def _internal_state(self) -> tuple[list[int], set[str]]: # Internal representation of hand as a list of card values and # a set of card suit trans: dict = {"T": "10", "J": "11", "Q": "12", "K": "13", "A": "14"} new_hand = self._hand.translate(str.maketrans(trans)).split() card_values = [int(card[:-1]) for card in new_hand] card_suit = {card[-1] for card in new_hand} return sorted(card_values, reverse=True), card_suit def __repr__(self): return f'{self.__class__}("{self._hand}")' def __str__(self): return self._hand # Rich comparison operators (used in list.sort() and sorted() builtin functions) # Note that this is not part of the problem but another extra feature where # if you have a list of PokerHand objects, you can sort them just through # the builtin functions. def __eq__(self, other): if isinstance(other, PokerHand): return self.compare_with(other) == "Tie" return NotImplemented def __lt__(self, other): if isinstance(other, PokerHand): return self.compare_with(other) == "Loss" return NotImplemented def __le__(self, other): if isinstance(other, PokerHand): return self < other or self == other return NotImplemented def __gt__(self, other): if isinstance(other, PokerHand): return not self < other and self != other return NotImplemented def __ge__(self, other): if isinstance(other, PokerHand): return not self < other return NotImplemented def __hash__(self): return object.__hash__(self) def solution() -> int: # Solution for problem number 54 from Project Euler # Input from poker_hands.txt file answer = 0 script_dir = os.path.abspath(os.path.dirname(__file__)) poker_hands = os.path.join(script_dir, "poker_hands.txt") with open(poker_hands) as file_hand: for line in file_hand: player_hand = line[:14].strip() opponent_hand = line[15:].strip() player, opponent = PokerHand(player_hand), PokerHand(opponent_hand) output = player.compare_with(opponent) if output == "Win": answer += 1 return answer if __name__ == "__main__": solution()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_054/test_poker_hand.py
project_euler/problem_054/test_poker_hand.py
import os from itertools import chain from random import randrange, shuffle import pytest from .sol1 import PokerHand SORTED_HANDS = ( "4S 3H 2C 7S 5H", "9D 8H 2C 6S 7H", "2D 6D 9D TH 7D", "TC 8C 2S JH 6C", "JH 8S TH AH QH", "TS KS 5S 9S AC", "KD 6S 9D TH AD", "KS 8D 4D 9S 4S", # pair "8C 4S KH JS 4D", # pair "QH 8H KD JH 8S", # pair "KC 4H KS 2H 8D", # pair "KD 4S KC 3H 8S", # pair "AH 8S AS KC JH", # pair "3H 4C 4H 3S 2H", # 2 pairs "5S 5D 2C KH KH", # 2 pairs "3C KH 5D 5S KH", # 2 pairs "AS 3C KH AD KH", # 2 pairs "7C 7S 3S 7H 5S", # 3 of a kind "7C 7S KH 2H 7H", # 3 of a kind "AC KH QH AH AS", # 3 of a kind "2H 4D 3C AS 5S", # straight (low ace) "3C 5C 4C 2C 6H", # straight "6S 8S 7S 5H 9H", # straight "JS QS 9H TS KH", # straight "QC KH TS JS AH", # straight (high ace) "8C 9C 5C 3C TC", # flush "3S 8S 9S 5S KS", # flush "4C 5C 9C 8C KC", # flush "JH 8H AH KH QH", # flush "3D 2H 3H 2C 2D", # full house "2H 2C 3S 3H 3D", # full house "KH KC 3S 3H 3D", # full house "JC 6H JS JD JH", # 4 of a kind "JC 7H JS JD JH", # 4 of a kind "JC KH JS JD JH", # 4 of a kind "2S AS 4S 5S 3S", # straight flush (low ace) "2D 6D 3D 4D 5D", # straight flush "5C 6C 3C 7C 4C", # straight flush "JH 9H TH KH QH", # straight flush "JH AH TH KH QH", # royal flush (high ace straight flush) ) TEST_COMPARE = ( ("2H 3H 4H 5H 6H", "KS AS TS QS JS", "Loss"), ("2H 3H 4H 5H 6H", "AS AD AC AH JD", "Win"), ("AS AH 2H AD AC", "JS JD JC JH 3D", "Win"), ("2S AH 2H AS AC", "JS JD JC JH AD", "Loss"), ("2S AH 2H AS AC", "2H 3H 5H 6H 7H", "Win"), ("AS 3S 4S 8S 2S", "2H 3H 5H 6H 7H", "Win"), ("2H 3H 5H 6H 7H", "2S 3H 4H 5S 6C", "Win"), ("2S 3H 4H 5S 6C", "3D 4C 5H 6H 2S", "Tie"), ("2S 3H 4H 5S 6C", "AH AC 5H 6H AS", "Win"), ("2S 2H 4H 5S 4C", "AH AC 5H 6H AS", "Loss"), ("2S 2H 4H 5S 4C", "AH AC 5H 6H 7S", "Win"), ("6S AD 7H 4S AS", "AH AC 5H 6H 7S", "Loss"), ("2S AH 4H 5S KC", "AH AC 5H 6H 7S", "Loss"), ("2S 3H 6H 7S 9C", "7H 3C TH 6H 9S", "Loss"), ("4S 5H 6H TS AC", "3S 5H 6H TS AC", "Win"), ("2S AH 4H 5S 6C", "AD 4C 5H 6H 2C", "Tie"), ("AS AH 3H AD AC", "AS AH 2H AD AC", "Win"), ("AH AC 5H 5C QS", "AH AC 5H 5C KS", "Loss"), ("AH AC 5H 5C QS", "KH KC 5H 5C QS", "Win"), ("7C 7S KH 2H 7H", "3C 3S AH 2H 3H", "Win"), ("3C 3S AH 2H 3H", "7C 7S KH 2H 7H", "Loss"), ("6H 5H 4H 3H 2H", "5H 4H 3H 2H AH", "Win"), ("5H 4H 3H 2H AH", "5H 4H 3H 2H AH", "Tie"), ("5H 4H 3H 2H AH", "6H 5H 4H 3H 2H", "Loss"), ("AH AD KS KC AC", "AH KD KH AC KC", "Win"), ("2H 4D 3C AS 5S", "2H 4D 3C 6S 5S", "Loss"), ("2H 3S 3C 3H 2S", "3S 3C 2S 2H 2D", "Win"), ("4D 6D 5D 2D JH", "3S 8S 3H TC KH", "Loss"), ("4S 6C 8S 3S 7S", "AD KS 2D 7D 7C", "Loss"), ("6S 4C 7H 8C 3H", "5H JC AH 9D 9C", "Loss"), ("9D 9H JH TC QH", "3C 2S JS 5C 7H", "Win"), ("2H TC 8S AD 9S", "4H TS 7H 2C 5C", "Win"), ("9D 3S 2C 7S 7C", "JC TD 3C TC 9H", "Loss"), ) TEST_FLUSH = ( ("2H 3H 4H 5H 6H", True), ("AS AH 2H AD AC", False), ("2H 3H 5H 6H 7H", True), ("KS AS TS QS JS", True), ("8H 9H QS JS TH", False), ("AS 3S 4S 8S 2S", True), ) TEST_STRAIGHT = ( ("2H 3H 4H 5H 6H", True), ("AS AH 2H AD AC", False), ("2H 3H 5H 6H 7H", False), ("KS AS TS QS JS", True), ("8H 9H QS JS TH", True), ) TEST_FIVE_HIGH_STRAIGHT = ( ("2H 4D 3C AS 5S", True, [5, 4, 3, 2, 14]), ("2H 5D 3C AS 5S", False, [14, 5, 5, 3, 2]), ("JH QD KC AS TS", False, [14, 13, 12, 11, 10]), ("9D 3S 2C 7S 7C", False, [9, 7, 7, 3, 2]), ) TEST_KIND = ( ("JH AH TH KH QH", 0), ("JH 9H TH KH QH", 0), ("JC KH JS JD JH", 7), ("KH KC 3S 3H 3D", 6), ("8C 9C 5C 3C TC", 0), ("JS QS 9H TS KH", 0), ("7C 7S KH 2H 7H", 3), ("3C KH 5D 5S KH", 2), ("QH 8H KD JH 8S", 1), ("2D 6D 9D TH 7D", 0), ) TEST_TYPES = ( ("JH AH TH KH QH", 23), ("JH 9H TH KH QH", 22), ("JC KH JS JD JH", 21), ("KH KC 3S 3H 3D", 20), ("8C 9C 5C 3C TC", 19), ("JS QS 9H TS KH", 18), ("7C 7S KH 2H 7H", 17), ("3C KH 5D 5S KH", 16), ("QH 8H KD JH 8S", 15), ("2D 6D 9D TH 7D", 14), ) def generate_random_hand(): play, oppo = randrange(len(SORTED_HANDS)), randrange(len(SORTED_HANDS)) expected = ["Loss", "Tie", "Win"][(play >= oppo) + (play > oppo)] hand, other = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def generate_random_hands(number_of_hands: int = 100): return (generate_random_hand() for _ in range(number_of_hands)) @pytest.mark.parametrize(("hand", "expected"), TEST_FLUSH) def test_hand_is_flush(hand, expected): assert PokerHand(hand)._is_flush() == expected @pytest.mark.parametrize(("hand", "expected"), TEST_STRAIGHT) def test_hand_is_straight(hand, expected): assert PokerHand(hand)._is_straight() == expected @pytest.mark.parametrize(("hand", "expected", "card_values"), TEST_FIVE_HIGH_STRAIGHT) def test_hand_is_five_high_straight(hand, expected, card_values): player = PokerHand(hand) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize(("hand", "expected"), TEST_KIND) def test_hand_is_same_kind(hand, expected): assert PokerHand(hand)._is_same_kind() == expected @pytest.mark.parametrize(("hand", "expected"), TEST_TYPES) def test_hand_values(hand, expected): assert PokerHand(hand)._hand_type == expected @pytest.mark.parametrize(("hand", "other", "expected"), TEST_COMPARE) def test_compare_simple(hand, other, expected): assert PokerHand(hand).compare_with(PokerHand(other)) == expected @pytest.mark.parametrize(("hand", "other", "expected"), generate_random_hands()) def test_compare_random(hand, other, expected): assert PokerHand(hand).compare_with(PokerHand(other)) == expected def test_hand_sorted(): poker_hands = [PokerHand(hand) for hand in SORTED_HANDS] list_copy = poker_hands.copy() shuffle(list_copy) user_sorted = chain(sorted(list_copy)) for index, hand in enumerate(user_sorted): assert hand == poker_hands[index] def test_custom_sort_five_high_straight(): # Test that five high straights are compared correctly. pokerhands = [PokerHand("2D AC 3H 4H 5S"), PokerHand("2S 3H 4H 5S 6C")] pokerhands.sort(reverse=True) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def test_multiple_calls_five_high_straight(): # Multiple calls to five_high_straight function should still return True # and shouldn't mutate the list in every call other than the first. pokerhand = PokerHand("2C 4S AS 3D 5C") expected = True expected_card_values = [5, 4, 3, 2, 14] for _ in range(10): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def test_euler_project(): # Problem number 54 from Project Euler # Testing from poker_hands.txt file answer = 0 script_dir = os.path.abspath(os.path.dirname(__file__)) poker_hands = os.path.join(script_dir, "poker_hands.txt") with open(poker_hands) as file_hand: for line in file_hand: player_hand = line[:14].strip() opponent_hand = line[15:].strip() player, opponent = PokerHand(player_hand), PokerHand(opponent_hand) output = player.compare_with(opponent) if output == "Win": answer += 1 assert answer == 376
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_054/__init__.py
project_euler/problem_054/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_125/sol1.py
project_euler/problem_125/sol1.py
""" Problem 125: https://projecteuler.net/problem=125 The palindromic number 595 is interesting because it can be written as the sum of consecutive squares: 6^2 + 7^2 + 8^2 + 9^2 + 10^2 + 11^2 + 12^2. There are exactly eleven palindromes below one-thousand that can be written as consecutive square sums, and the sum of these palindromes is 4164. Note that 1 = 0^2 + 1^2 has not been included as this problem is concerned with the squares of positive integers. Find the sum of all the numbers less than 10^8 that are both palindromic and can be written as the sum of consecutive squares. """ LIMIT = 10**8 def is_palindrome(n: int) -> bool: """ Check if an integer is palindromic. >>> is_palindrome(12521) True >>> is_palindrome(12522) False >>> is_palindrome(12210) False """ if n % 10 == 0: return False s = str(n) return s == s[::-1] def solution() -> int: """ Returns the sum of all numbers less than 1e8 that are both palindromic and can be written as the sum of consecutive squares. """ answer = set() first_square = 1 sum_squares = 5 while sum_squares < LIMIT: last_square = first_square + 1 while sum_squares < LIMIT: if is_palindrome(sum_squares): answer.add(sum_squares) last_square += 1 sum_squares += last_square**2 first_square += 1 sum_squares = first_square**2 + (first_square + 1) ** 2 return sum(answer) if __name__ == "__main__": print(solution())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_125/__init__.py
project_euler/problem_125/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_038/sol1.py
project_euler/problem_038/sol1.py
""" Project Euler Problem 38: https://projecteuler.net/problem=38 Take the number 192 and multiply it by each of 1, 2, and 3: 192 x 1 = 192 192 x 2 = 384 192 x 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1? Solution: Since n>1, the largest candidate for the solution will be a concactenation of a 4-digit number and its double, a 5-digit number. Let a be the 4-digit number. a has 4 digits => 1000 <= a < 10000 2a has 5 digits => 10000 <= 2a < 100000 => 5000 <= a < 10000 The concatenation of a with 2a = a * 10^5 + 2a so our candidate for a given a is 100002 * a. We iterate through the search space 5000 <= a < 10000 in reverse order, calculating the candidates for each a and checking if they are 1-9 pandigital. In case there are no 4-digit numbers that satisfy this property, we check the 3-digit numbers with a similar formula (the example a=192 gives a lower bound on the length of a): a has 3 digits, etc... => 100 <= a < 334, candidate = a * 10^6 + 2a * 10^3 + 3a = 1002003 * a """ from __future__ import annotations def is_9_pandigital(n: int) -> bool: """ Checks whether n is a 9-digit 1 to 9 pandigital number. >>> is_9_pandigital(12345) False >>> is_9_pandigital(156284973) True >>> is_9_pandigital(1562849733) False """ s = str(n) return len(s) == 9 and set(s) == set("123456789") def solution() -> int | None: """ Return the largest 1 to 9 pandigital 9-digital number that can be formed as the concatenated product of an integer with (1,2,...,n) where n > 1. """ for base_num in range(9999, 4999, -1): candidate = 100002 * base_num if is_9_pandigital(candidate): return candidate for base_num in range(333, 99, -1): candidate = 1002003 * base_num if is_9_pandigital(candidate): return candidate return None if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_038/__init__.py
project_euler/problem_038/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_205/sol1.py
project_euler/problem_205/sol1.py
""" Project Euler Problem 205: https://projecteuler.net/problem=205 Peter has nine four-sided (pyramidal) dice, each with faces numbered 1, 2, 3, 4. Colin has six six-sided (cubic) dice, each with faces numbered 1, 2, 3, 4, 5, 6. Peter and Colin roll their dice and compare totals: the highest total wins. The result is a draw if the totals are equal. What is the probability that Pyramidal Peter beats Cubic Colin? Give your answer rounded to seven decimal places in the form 0.abcdefg """ from itertools import product def total_frequency_distribution(sides_number: int, dice_number: int) -> list[int]: """ Returns frequency distribution of total >>> total_frequency_distribution(sides_number=6, dice_number=1) [0, 1, 1, 1, 1, 1, 1] >>> total_frequency_distribution(sides_number=4, dice_number=2) [0, 0, 1, 2, 3, 4, 3, 2, 1] """ max_face_number = sides_number max_total = max_face_number * dice_number totals_frequencies = [0] * (max_total + 1) min_face_number = 1 faces_numbers = range(min_face_number, max_face_number + 1) for dice_numbers in product(faces_numbers, repeat=dice_number): total = sum(dice_numbers) totals_frequencies[total] += 1 return totals_frequencies def solution() -> float: """ Returns probability that Pyramidal Peter beats Cubic Colin rounded to seven decimal places in the form 0.abcdefg >>> solution() 0.5731441 """ peter_totals_frequencies = total_frequency_distribution( sides_number=4, dice_number=9 ) colin_totals_frequencies = total_frequency_distribution( sides_number=6, dice_number=6 ) peter_wins_count = 0 min_peter_total = 9 max_peter_total = 4 * 9 min_colin_total = 6 for peter_total in range(min_peter_total, max_peter_total + 1): peter_wins_count += peter_totals_frequencies[peter_total] * sum( colin_totals_frequencies[min_colin_total:peter_total] ) total_games_number = (4**9) * (6**6) peter_win_probability = peter_wins_count / total_games_number rounded_peter_win_probability = round(peter_win_probability, ndigits=7) return rounded_peter_win_probability if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_205/__init__.py
project_euler/problem_205/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_049/sol1.py
project_euler/problem_049/sol1.py
""" Prime permutations Problem 49 The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, (ii) each of the 4-digit numbers are permutations of one another. There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence. What 12-digit number do you form by concatenating the three terms in this sequence? Solution: First, we need to generate all 4 digits prime numbers. Then greedy all of them and use permutation to form new numbers. Use binary search to check if the permutated numbers is in our prime list and include them in a candidate list. After that, bruteforce all passed candidates sequences using 3 nested loops since we know the answer will be 12 digits. The bruteforce of this solution will be about 1 sec. """ import math from itertools import permutations def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def search(target: int, prime_list: list) -> bool: """ function to search a number in a list using Binary Search. >>> search(3, [1, 2, 3]) True >>> search(4, [1, 2, 3]) False >>> search(101, list(range(-100, 100))) False """ left, right = 0, len(prime_list) - 1 while left <= right: middle = (left + right) // 2 if prime_list[middle] == target: return True elif prime_list[middle] < target: left = middle + 1 else: right = middle - 1 return False def solution(): """ Return the solution of the problem. >>> solution() 296962999629 """ prime_list = [n for n in range(1001, 10000, 2) if is_prime(n)] candidates = [] for number in prime_list: tmp_numbers = [] for prime_member in permutations(list(str(number))): prime = int("".join(prime_member)) if prime % 2 == 0: continue if search(prime, prime_list): tmp_numbers.append(prime) tmp_numbers.sort() if len(tmp_numbers) >= 3: candidates.append(tmp_numbers) passed = [] for candidate in candidates: length = len(candidate) found = False for i in range(length): for j in range(i + 1, length): for k in range(j + 1, length): if ( abs(candidate[i] - candidate[j]) == abs(candidate[j] - candidate[k]) and len({candidate[i], candidate[j], candidate[k]}) == 3 ): passed.append( sorted([candidate[i], candidate[j], candidate[k]]) ) found = True if found: break if found: break if found: break answer = set() for seq in passed: answer.add("".join([str(i) for i in seq])) return max(int(x) for x in answer) if __name__ == "__main__": print(solution())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_049/__init__.py
project_euler/problem_049/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_129/sol1.py
project_euler/problem_129/sol1.py
""" Project Euler Problem 129: https://projecteuler.net/problem=129 A number consisting entirely of ones is called a repunit. We shall define R(k) to be a repunit of length k; for example, R(6) = 111111. Given that n is a positive integer and GCD(n, 10) = 1, it can be shown that there always exists a value, k, for which R(k) is divisible by n, and let A(n) be the least such value of k; for example, A(7) = 6 and A(41) = 5. The least value of n for which A(n) first exceeds ten is 17. Find the least value of n for which A(n) first exceeds one-million. """ def least_divisible_repunit(divisor: int) -> int: """ Return the least value k such that the Repunit of length k is divisible by divisor. >>> least_divisible_repunit(7) 6 >>> least_divisible_repunit(41) 5 >>> least_divisible_repunit(1234567) 34020 """ if divisor % 5 == 0 or divisor % 2 == 0: return 0 repunit = 1 repunit_index = 1 while repunit: repunit = (10 * repunit + 1) % divisor repunit_index += 1 return repunit_index def solution(limit: int = 1000000) -> int: """ Return the least value of n for which least_divisible_repunit(n) first exceeds limit. >>> solution(10) 17 >>> solution(100) 109 >>> solution(1000) 1017 """ divisor = limit - 1 if divisor % 2 == 0: divisor += 1 while least_divisible_repunit(divisor) <= limit: divisor += 2 return divisor if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_129/__init__.py
project_euler/problem_129/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_301/sol1.py
project_euler/problem_301/sol1.py
""" Project Euler Problem 301: https://projecteuler.net/problem=301 Problem Statement: Nim is a game played with heaps of stones, where two players take it in turn to remove any number of stones from any heap until no stones remain. We'll consider the three-heap normal-play version of Nim, which works as follows: - At the start of the game there are three heaps of stones. - On each player's turn, the player may remove any positive number of stones from any single heap. - The first player unable to move (because no stones remain) loses. If (n1, n2, n3) indicates a Nim position consisting of heaps of size n1, n2, and n3, then there is a simple function, which you may look up or attempt to deduce for yourself, X(n1, n2, n3) that returns: - zero if, with perfect strategy, the player about to move will eventually lose; or - non-zero if, with perfect strategy, the player about to move will eventually win. For example X(1,2,3) = 0 because, no matter what the current player does, the opponent can respond with a move that leaves two heaps of equal size, at which point every move by the current player can be mirrored by the opponent until no stones remain; so the current player loses. To illustrate: - current player moves to (1,2,1) - opponent moves to (1,0,1) - current player moves to (0,0,1) - opponent moves to (0,0,0), and so wins. For how many positive integers n <= 2^30 does X(n,2n,3n) = 0? """ def solution(exponent: int = 30) -> int: """ For any given exponent x >= 0, 1 <= n <= 2^x. This function returns how many Nim games are lost given that each Nim game has three heaps of the form (n, 2*n, 3*n). >>> solution(0) 1 >>> solution(2) 3 >>> solution(10) 144 """ # To find how many total games were lost for a given exponent x, # we need to find the Fibonacci number F(x+2). fibonacci_index = exponent + 2 phi = (1 + 5**0.5) / 2 fibonacci = (phi**fibonacci_index - (phi - 1) ** fibonacci_index) / 5**0.5 return int(fibonacci) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_301/__init__.py
project_euler/problem_301/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_019/sol1.py
project_euler/problem_019/sol1.py
""" Counting Sundays Problem 19 You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? """ def solution(): """Returns the number of mondays that fall on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? >>> solution() 171 """ days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] day = 6 month = 1 year = 1901 sundays = 0 while year < 2001: day += 7 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): if day > days_per_month[month - 1] and month != 2: month += 1 day = day - days_per_month[month - 2] elif day > 29 and month == 2: month += 1 day = day - 29 elif day > days_per_month[month - 1]: month += 1 day = day - days_per_month[month - 2] if month > 12: year += 1 month = 1 if year < 2001 and day == 1: sundays += 1 return sundays if __name__ == "__main__": print(solution())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_019/__init__.py
project_euler/problem_019/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_009/sol2.py
project_euler/problem_009/sol2.py
""" Project Euler Problem 9: https://projecteuler.net/problem=9 Special Pythagorean triplet A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product a*b*c. References: - https://en.wikipedia.org/wiki/Pythagorean_triple """ def solution(n: int = 1000) -> int: """ Return the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a < b < c 2. a**2 + b**2 = c**2 3. a + b + c = n >>> solution(36) 1620 >>> solution(126) 66780 """ product = -1 candidate = 0 for a in range(1, n // 3): # Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c b = (n * n - 2 * a * n) // (2 * n - 2 * a) c = n - a - b if c * c == (a * a + b * b): candidate = a * b * c product = max(product, candidate) return product if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_009/sol4.py
project_euler/problem_009/sol4.py
""" Project Euler Problem 9: https://projecteuler.net/problem=9 Special Pythagorean triplet A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2. For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. References: - https://en.wikipedia.org/wiki/Pythagorean_triple """ def get_squares(n: int) -> list[int]: """ >>> get_squares(0) [] >>> get_squares(1) [0] >>> get_squares(2) [0, 1] >>> get_squares(3) [0, 1, 4] >>> get_squares(4) [0, 1, 4, 9] """ return [number * number for number in range(n)] def solution(n: int = 1000) -> int: """ Precomputing squares and checking if a^2 + b^2 is the square by set look-up. >>> solution(12) 60 >>> solution(36) 1620 """ squares = get_squares(n) squares_set = set(squares) for a in range(1, n // 3): for b in range(a + 1, (n - a) // 2 + 1): if ( squares[a] + squares[b] in squares_set and squares[n - a - b] == squares[a] + squares[b] ): return a * b * (n - a - b) return -1 if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_009/sol3.py
project_euler/problem_009/sol3.py
""" Project Euler Problem 9: https://projecteuler.net/problem=9 Special Pythagorean triplet A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product a*b*c. References: - https://en.wikipedia.org/wiki/Pythagorean_triple """ def solution() -> int: """ Returns the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a**2 + b**2 = c**2 2. a + b + c = 1000 >>> solution() 31875000 """ return next( iter( [ a * b * (1000 - a - b) for a in range(1, 999) for b in range(a, 999) if (a * a + b * b == (1000 - a - b) ** 2) ] ) ) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_009/sol1.py
project_euler/problem_009/sol1.py
""" Project Euler Problem 9: https://projecteuler.net/problem=9 Special Pythagorean triplet A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product a*b*c. References: - https://en.wikipedia.org/wiki/Pythagorean_triple """ def solution() -> int: """ Returns the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a < b < c 2. a**2 + b**2 = c**2 3. a + b + c = 1000 >>> solution() 31875000 """ for a in range(300): for b in range(a + 1, 400): for c in range(b + 1, 500): if (a + b + c) == 1000 and (a**2) + (b**2) == (c**2): return a * b * c return -1 def solution_fast() -> int: """ Returns the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a < b < c 2. a**2 + b**2 = c**2 3. a + b + c = 1000 >>> solution_fast() 31875000 """ for a in range(300): for b in range(400): c = 1000 - a - b if a < b < c and (a**2) + (b**2) == (c**2): return a * b * c return -1 def benchmark() -> None: """ Benchmark code comparing two different version function. """ import timeit print( timeit.timeit("solution()", setup="from __main__ import solution", number=1000) ) print( timeit.timeit( "solution_fast()", setup="from __main__ import solution_fast", number=1000 ) ) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_009/__init__.py
project_euler/problem_009/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_027/sol1.py
project_euler/problem_027/sol1.py
""" Project Euler Problem 27 https://projecteuler.net/problem=27 Problem Statement: Euler discovered the remarkable quadratic formula: n2 + n + 41 It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39. However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 412 + 41 + 41 is clearly divisible by 41. The incredible formula n2 - 79n + 1601 was discovered, which produces 80 primes for the consecutive values n = 0 to 79. The product of the coefficients, -79 and 1601, is -126479. Considering quadratics of the form: n² + an + b, where |a| &lt; 1000 and |b| &lt; 1000 where |n| is the modulus/absolute value of ne.g. |11| = 11 and |-4| = 4 Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0. """ import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. Returns boolean representing primality of given number num (i.e., if the result is true, then the number is indeed prime else it is not). >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(2999) True >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(-10) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def solution(a_limit: int = 1000, b_limit: int = 1000) -> int: """ >>> solution(1000, 1000) -59231 >>> solution(200, 1000) -59231 >>> solution(200, 200) -4925 >>> solution(-1000, 1000) 0 >>> solution(-1000, -1000) 0 """ longest = [0, 0, 0] # length, a, b for a in range((a_limit * -1) + 1, a_limit): for b in range(2, b_limit): if is_prime(b): count = 0 n = 0 while is_prime((n**2) + (a * n) + b): count += 1 n += 1 if count > longest[0]: longest = [count, a, b] ans = longest[1] * longest[2] return ans if __name__ == "__main__": print(solution(1000, 1000))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_027/__init__.py
project_euler/problem_027/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_123/sol1.py
project_euler/problem_123/sol1.py
""" Problem 123: https://projecteuler.net/problem=123 Name: Prime square remainders Let pn be the nth prime: 2, 3, 5, 7, 11, ..., and let r be the remainder when (pn-1)^n + (pn+1)^n is divided by pn^2. For example, when n = 3, p3 = 5, and 43 + 63 = 280 ≡ 5 mod 25. The least value of n for which the remainder first exceeds 10^9 is 7037. Find the least value of n for which the remainder first exceeds 10^10. Solution: n=1: (p-1) + (p+1) = 2p n=2: (p-1)^2 + (p+1)^2 = p^2 + 1 - 2p + p^2 + 1 + 2p (Using (p+b)^2 = (p^2 + b^2 + 2pb), (p-b)^2 = (p^2 + b^2 - 2pb) and b = 1) = 2p^2 + 2 n=3: (p-1)^3 + (p+1)^3 (Similarly using (p+b)^3 & (p-b)^3 formula and so on) = 2p^3 + 6p n=4: 2p^4 + 12p^2 + 2 n=5: 2p^5 + 20p^3 + 10p As you could see, when the expression is divided by p^2. Except for the last term, the rest will result in the remainder 0. n=1: 2p n=2: 2 n=3: 6p n=4: 2 n=5: 10p So it could be simplified as, r = 2pn when n is odd r = 2 when n is even. """ from __future__ import annotations from collections.abc import Generator def sieve() -> Generator[int]: """ Returns a prime number generator using sieve method. >>> type(sieve()) <class 'generator'> >>> primes = sieve() >>> next(primes) 2 >>> next(primes) 3 >>> next(primes) 5 >>> next(primes) 7 >>> next(primes) 11 >>> next(primes) 13 """ factor_map: dict[int, int] = {} prime = 2 while True: factor = factor_map.pop(prime, None) if factor: x = factor + prime while x in factor_map: x += factor factor_map[x] = factor else: factor_map[prime * prime] = prime yield prime prime += 1 def solution(limit: float = 1e10) -> int: """ Returns the least value of n for which the remainder first exceeds 10^10. >>> solution(1e8) 2371 >>> solution(1e9) 7037 """ primes = sieve() n = 1 while True: prime = next(primes) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(primes) n += 2 if __name__ == "__main__": print(solution())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_123/__init__.py
project_euler/problem_123/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_065/sol1.py
project_euler/problem_065/sol1.py
""" Project Euler Problem 65: https://projecteuler.net/problem=65 The square root of 2 can be written as an infinite continued fraction. sqrt(2) = 1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / (2 + ...)))) The infinite continued fraction can be written, sqrt(2) = [1;(2)], (2) indicates that 2 repeats ad infinitum. In a similar way, sqrt(23) = [4;(1,3,1,8)]. It turns out that the sequence of partial values of continued fractions for square roots provide the best rational approximations. Let us consider the convergents for sqrt(2). 1 + 1 / 2 = 3/2 1 + 1 / (2 + 1 / 2) = 7/5 1 + 1 / (2 + 1 / (2 + 1 / 2)) = 17/12 1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / 2))) = 41/29 Hence the sequence of the first ten convergents for sqrt(2) are: 1, 3/2, 7/5, 17/12, 41/29, 99/70, 239/169, 577/408, 1393/985, 3363/2378, ... What is most surprising is that the important mathematical constant, e = [2;1,2,1,1,4,1,1,6,1,...,1,2k,1,...]. The first ten terms in the sequence of convergents for e are: 2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71, 1264/465, 1457/536, ... The sum of digits in the numerator of the 10th convergent is 1 + 4 + 5 + 7 = 17. Find the sum of the digits in the numerator of the 100th convergent of the continued fraction for e. ----- The solution mostly comes down to finding an equation that will generate the numerator of the continued fraction. For the i-th numerator, the pattern is: n_i = m_i * n_(i-1) + n_(i-2) for m_i = the i-th index of the continued fraction representation of e, n_0 = 1, and n_1 = 2 as the first 2 numbers of the representation. For example: n_9 = 6 * 193 + 106 = 1264 1 + 2 + 6 + 4 = 13 n_10 = 1 * 193 + 1264 = 1457 1 + 4 + 5 + 7 = 17 """ def sum_digits(num: int) -> int: """ Returns the sum of every digit in num. >>> sum_digits(1) 1 >>> sum_digits(12345) 15 >>> sum_digits(999001) 28 """ digit_sum = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def solution(max_n: int = 100) -> int: """ Returns the sum of the digits in the numerator of the max-th convergent of the continued fraction for e. >>> solution(9) 13 >>> solution(10) 17 >>> solution(50) 91 """ pre_numerator = 1 cur_numerator = 2 for i in range(2, max_n + 1): temp = pre_numerator e_cont = 2 * i // 3 if i % 3 == 0 else 1 pre_numerator = cur_numerator cur_numerator = e_cont * pre_numerator + temp return sum_digits(cur_numerator) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_065/__init__.py
project_euler/problem_065/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_114/sol1.py
project_euler/problem_114/sol1.py
""" Project Euler Problem 114: https://projecteuler.net/problem=114 A row measuring seven units in length has red blocks with a minimum length of three units placed on it, such that any two red blocks (which are allowed to be different lengths) are separated by at least one grey square. There are exactly seventeen ways of doing this. |g|g|g|g|g|g|g| |r,r,r|g|g|g|g| |g|r,r,r|g|g|g| |g|g|r,r,r|g|g| |g|g|g|r,r,r|g| |g|g|g|g|r,r,r| |r,r,r|g|r,r,r| |r,r,r,r|g|g|g| |g|r,r,r,r|g|g| |g|g|r,r,r,r|g| |g|g|g|r,r,r,r| |r,r,r,r,r|g|g| |g|r,r,r,r,r|g| |g|g|r,r,r,r,r| |r,r,r,r,r,r|g| |g|r,r,r,r,r,r| |r,r,r,r,r,r,r| How many ways can a row measuring fifty units in length be filled? NOTE: Although the example above does not lend itself to the possibility, in general it is permitted to mix block sizes. For example, on a row measuring eight units in length you could use red (3), grey (1), and red (4). """ def solution(length: int = 50) -> int: """ Returns the number of ways a row of the given length can be filled >>> solution(7) 17 """ ways_number = [1] * (length + 1) for row_length in range(3, length + 1): for block_length in range(3, row_length + 1): for block_start in range(row_length - block_length): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_114/__init__.py
project_euler/problem_114/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_800/sol1.py
project_euler/problem_800/sol1.py
""" Project Euler Problem 800: https://projecteuler.net/problem=800 An integer of the form p^q q^p with prime numbers p != q is called a hybrid-integer. For example, 800 = 2^5 5^2 is a hybrid-integer. We define C(n) to be the number of hybrid-integers less than or equal to n. You are given C(800) = 2 and C(800^800) = 10790 Find C(800800^800800) """ from math import isqrt, log2 def calculate_prime_numbers(max_number: int) -> list[int]: """ Returns prime numbers below max_number >>> calculate_prime_numbers(10) [2, 3, 5, 7] """ is_prime = [True] * max_number for i in range(2, isqrt(max_number - 1) + 1): if is_prime[i]: for j in range(i**2, max_number, i): is_prime[j] = False return [i for i in range(2, max_number) if is_prime[i]] def solution(base: int = 800800, degree: int = 800800) -> int: """ Returns the number of hybrid-integers less than or equal to base^degree >>> solution(800, 1) 2 >>> solution(800, 800) 10790 """ upper_bound = degree * log2(base) max_prime = int(upper_bound) prime_numbers = calculate_prime_numbers(max_prime) hybrid_integers_count = 0 left = 0 right = len(prime_numbers) - 1 while left < right: while ( prime_numbers[right] * log2(prime_numbers[left]) + prime_numbers[left] * log2(prime_numbers[right]) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_800/__init__.py
project_euler/problem_800/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_144/sol1.py
project_euler/problem_144/sol1.py
""" In laser physics, a "white cell" is a mirror system that acts as a delay line for the laser beam. The beam enters the cell, bounces around on the mirrors, and eventually works its way back out. The specific white cell we will be considering is an ellipse with the equation 4x^2 + y^2 = 100 The section corresponding to -0.01 ≤ x ≤ +0.01 at the top is missing, allowing the light to enter and exit through the hole.  The light beam in this problem starts at the point (0.0,10.1) just outside the white cell, and the beam first impacts the mirror at (1.4,-9.6). Each time the laser beam hits the surface of the ellipse, it follows the usual law of reflection "angle of incidence equals angle of reflection." That is, both the incident and reflected beams make the same angle with the normal line at the point of incidence. In the figure on the left, the red line shows the first two points of contact between the laser beam and the wall of the white cell; the blue line shows the line tangent to the ellipse at the point of incidence of the first bounce. The slope m of the tangent line at any point (x,y) of the given ellipse is: m = -4x/y The normal line is perpendicular to this tangent line at the point of incidence. The animation on the right shows the first 10 reflections of the beam. How many times does the beam hit the internal surface of the white cell before exiting? """ from math import isclose, sqrt def next_point( point_x: float, point_y: float, incoming_gradient: float ) -> tuple[float, float, float]: """ Given that a laser beam hits the interior of the white cell at point (point_x, point_y) with gradient incoming_gradient, return a tuple (x,y,m1) where the next point of contact with the interior is (x,y) with gradient m1. >>> next_point(5.0, 0.0, 0.0) (-5.0, 0.0, 0.0) >>> next_point(5.0, 0.0, -2.0) (0.0, -10.0, 2.0) """ # normal_gradient = gradient of line through which the beam is reflected # outgoing_gradient = gradient of reflected line normal_gradient = point_y / 4 / point_x s2 = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) c2 = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) outgoing_gradient = (s2 - c2 * incoming_gradient) / (c2 + s2 * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 quadratic_term = outgoing_gradient**2 + 4 linear_term = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) constant_term = (point_y - outgoing_gradient * point_x) ** 2 - 100 x_minus = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term) ) / (2 * quadratic_term) x_plus = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term) ) / (2 * quadratic_term) # two solutions, one of which is our input point next_x = x_minus if isclose(x_plus, point_x) else x_plus next_y = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def solution(first_x_coord: float = 1.4, first_y_coord: float = -9.6) -> int: """ Return the number of times that the beam hits the interior wall of the cell before exiting. >>> solution(0.00001,-10) 1 >>> solution(5, 0) 287 """ num_reflections: int = 0 point_x: float = first_x_coord point_y: float = first_y_coord gradient: float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): point_x, point_y, gradient = next_point(point_x, point_y, gradient) num_reflections += 1 return num_reflections if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_144/__init__.py
project_euler/problem_144/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_056/sol1.py
project_euler/problem_056/sol1.py
""" Project Euler Problem 56: https://projecteuler.net/problem=56 A googol (10^100) is a massive number: one followed by one-hundred zeros; 100^100 is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1. Considering natural numbers of the form, ab, where a, b < 100, what is the maximum digital sum? """ def solution(a: int = 100, b: int = 100) -> int: """ Considering natural numbers of the form, a**b, where a, b < 100, what is the maximum digital sum? :param a: :param b: :return: >>> solution(10,10) 45 >>> solution(100,100) 972 >>> solution(100,200) 1872 """ # RETURN the MAXIMUM from the list of SUMs of the list of INT converted from STR of # BASE raised to the POWER return max( sum(int(x) for x in str(base**power)) for base in range(a) for power in range(b) ) # Tests 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/project_euler/problem_056/__init__.py
project_euler/problem_056/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_087/sol1.py
project_euler/problem_087/sol1.py
""" Project Euler Problem 87: https://projecteuler.net/problem=87 The smallest number expressible as the sum of a prime square, prime cube, and prime fourth power is 28. In fact, there are exactly four numbers below fifty that can be expressed in such a way: 28 = 22 + 23 + 24 33 = 32 + 23 + 24 49 = 52 + 23 + 24 47 = 22 + 33 + 24 How many numbers below fifty million can be expressed as the sum of a prime square, prime cube, and prime fourth power? """ def solution(limit: int = 50000000) -> int: """ Return the number of integers less than limit which can be expressed as the sum of a prime square, prime cube, and prime fourth power. >>> solution(50) 4 """ ret = set() prime_square_limit = int((limit - 24) ** (1 / 2)) primes = set(range(3, prime_square_limit + 1, 2)) primes.add(2) for p in range(3, prime_square_limit + 1, 2): if p not in primes: continue primes.difference_update(set(range(p * p, prime_square_limit + 1, p))) for prime1 in primes: square = prime1 * prime1 for prime2 in primes: cube = prime2 * prime2 * prime2 if square + cube >= limit - 16: break for prime3 in primes: tetr = prime3 * prime3 * prime3 * prime3 total = square + cube + tetr if total >= limit: break ret.add(total) return len(ret) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_087/__init__.py
project_euler/problem_087/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_033/sol1.py
project_euler/problem_033/sol1.py
""" Problem 33: https://projecteuler.net/problem=33 The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s. We shall consider fractions like, 30/50 = 3/5, to be trivial examples. There are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two digits in the numerator and denominator. If the product of these four fractions is given in its lowest common terms, find the value of the denominator. """ from __future__ import annotations from fractions import Fraction def is_digit_cancelling(num: int, den: int) -> bool: return ( num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den ) def fraction_list(digit_len: int) -> list[str]: """ >>> fraction_list(2) ['16/64', '19/95', '26/65', '49/98'] >>> fraction_list(3) ['16/64', '19/95', '26/65', '49/98'] >>> fraction_list(4) ['16/64', '19/95', '26/65', '49/98'] >>> fraction_list(0) [] >>> fraction_list(5) ['16/64', '19/95', '26/65', '49/98'] """ solutions = [] den = 11 last_digit = int("1" + "0" * digit_len) for num in range(den, last_digit): while den <= 99: if ( (num != den) and (num % 10 == den // 10) and (den % 10 != 0) and is_digit_cancelling(num, den) ): solutions.append(f"{num}/{den}") den += 1 num += 1 den = 10 return solutions def solution(n: int = 2) -> int: """ Return the solution to the problem """ result = 1.0 for fraction in fraction_list(n): frac = Fraction(fraction) result *= frac.denominator / frac.numerator return int(result) if __name__ == "__main__": print(solution())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_033/__init__.py
project_euler/problem_033/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_052/sol1.py
project_euler/problem_052/sol1.py
""" Permuted multiples Problem 52 It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. """ def solution(): """Returns the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. >>> solution() 142857 """ i = 1 while True: if ( sorted(str(i)) == sorted(str(2 * i)) == sorted(str(3 * i)) == sorted(str(4 * i)) == sorted(str(5 * i)) == sorted(str(6 * i)) ): return i i += 1 if __name__ == "__main__": print(solution())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_052/__init__.py
project_euler/problem_052/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_345/sol1.py
project_euler/problem_345/sol1.py
""" Project Euler Problem 345: https://projecteuler.net/problem=345 Matrix Sum We define the Matrix Sum of a matrix as the maximum possible sum of matrix elements such that none of the selected elements share the same row or column. For example, the Matrix Sum of the matrix below equals 3315 ( = 863 + 383 + 343 + 959 + 767): 7 53 183 439 863 497 383 563 79 973 287 63 343 169 583 627 343 773 959 943 767 473 103 699 303 Find the Matrix Sum of: 7 53 183 439 863 497 383 563 79 973 287 63 343 169 583 627 343 773 959 943 767 473 103 699 303 957 703 583 639 913 447 283 463 29 23 487 463 993 119 883 327 493 423 159 743 217 623 3 399 853 407 103 983 89 463 290 516 212 462 350 960 376 682 962 300 780 486 502 912 800 250 346 172 812 350 870 456 192 162 593 473 915 45 989 873 823 965 425 329 803 973 965 905 919 133 673 665 235 509 613 673 815 165 992 326 322 148 972 962 286 255 941 541 265 323 925 281 601 95 973 445 721 11 525 473 65 511 164 138 672 18 428 154 448 848 414 456 310 312 798 104 566 520 302 248 694 976 430 392 198 184 829 373 181 631 101 969 613 840 740 778 458 284 760 390 821 461 843 513 17 901 711 993 293 157 274 94 192 156 574 34 124 4 878 450 476 712 914 838 669 875 299 823 329 699 815 559 813 459 522 788 168 586 966 232 308 833 251 631 107 813 883 451 509 615 77 281 613 459 205 380 274 302 35 805 Brute force solution, with caching intermediate steps to speed up the calculation. """ import numpy as np from numpy.typing import NDArray MATRIX_1 = [ "7 53 183 439 863", "497 383 563 79 973", "287 63 343 169 583", "627 343 773 959 943", "767 473 103 699 303", ] MATRIX_2 = [ "7 53 183 439 863 497 383 563 79 973 287 63 343 169 583", "627 343 773 959 943 767 473 103 699 303 957 703 583 639 913", "447 283 463 29 23 487 463 993 119 883 327 493 423 159 743", "217 623 3 399 853 407 103 983 89 463 290 516 212 462 350", "960 376 682 962 300 780 486 502 912 800 250 346 172 812 350", "870 456 192 162 593 473 915 45 989 873 823 965 425 329 803", "973 965 905 919 133 673 665 235 509 613 673 815 165 992 326", "322 148 972 962 286 255 941 541 265 323 925 281 601 95 973", "445 721 11 525 473 65 511 164 138 672 18 428 154 448 848", "414 456 310 312 798 104 566 520 302 248 694 976 430 392 198", "184 829 373 181 631 101 969 613 840 740 778 458 284 760 390", "821 461 843 513 17 901 711 993 293 157 274 94 192 156 574", "34 124 4 878 450 476 712 914 838 669 875 299 823 329 699", "815 559 813 459 522 788 168 586 966 232 308 833 251 631 107", "813 883 451 509 615 77 281 613 459 205 380 274 302 35 805", ] def solve(arr: NDArray, row: int, cols: set[int], cache: dict[str, int]) -> int: """ Finds the max sum for array `arr` starting with row index `row`, and with columns included in `cols`. `cache` is used for caching intermediate results. >>> solve(arr=np.array([[1, 2], [3, 4]]), row=0, cols={0, 1}, cache={}) 5 """ cache_id = f"{row}, {sorted(cols)}" if cache_id in cache: return cache[cache_id] if row == len(arr): return 0 max_sum = 0 for col in cols: new_cols = cols - {col} max_sum = max( max_sum, int(arr[row, col]) + solve(arr=arr, row=row + 1, cols=new_cols, cache=cache), ) cache[cache_id] = max_sum return max_sum def solution(matrix_str: list[str] = MATRIX_2) -> int: """ Takes list of strings `matrix_str` to parse the matrix and calculates the max sum. >>> solution(["1 2", "3 4"]) 5 >>> solution(MATRIX_1) 3315 """ n = len(matrix_str) arr = np.empty(shape=(n, n), dtype=int) for row, matrix_row_str in enumerate(matrix_str): matrix_row_list_str = matrix_row_str.split() for col, elem_str in enumerate(matrix_row_list_str): arr[row, col] = int(elem_str) cache: dict[str, int] = {} return solve(arr=arr, row=0, cols=set(range(n)), cache=cache) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_345/__init__.py
project_euler/problem_345/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_040/sol1.py
project_euler/problem_040/sol1.py
""" Champernowne's constant Problem 40 An irrational decimal fraction is created by concatenating the positive integers: 0.123456789101112131415161718192021... It can be seen that the 12th digit of the fractional part is 1. If dn represents the nth digit of the fractional part, find the value of the following expression. d1 x d10 x d100 x d1000 x d10000 x d100000 x d1000000 """ def solution(): """Returns >>> solution() 210 """ constant = [] i = 1 while len(constant) < 1e6: constant.append(str(i)) i += 1 constant = "".join(constant) return ( int(constant[0]) * int(constant[9]) * int(constant[99]) * int(constant[999]) * int(constant[9999]) * int(constant[99999]) * int(constant[999999]) ) if __name__ == "__main__": print(solution())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_040/__init__.py
project_euler/problem_040/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_136/sol1.py
project_euler/problem_136/sol1.py
""" Project Euler Problem 136: https://projecteuler.net/problem=136 Singleton Difference The positive integers, x, y, and z, are consecutive terms of an arithmetic progression. Given that n is a positive integer, the equation, x^2 - y^2 - z^2 = n, has exactly one solution when n = 20: 13^2 - 10^2 - 7^2 = 20. In fact there are twenty-five values of n below one hundred for which the equation has a unique solution. How many values of n less than fifty million have exactly one solution? By change of variables x = y + delta z = y - delta The expression can be rewritten: x^2 - y^2 - z^2 = y * (4 * delta - y) = n The algorithm loops over delta and y, which is restricted in upper and lower limits, to count how many solutions each n has. In the end it is counted how many n's have one solution. """ def solution(n_limit: int = 50 * 10**6) -> int: """ Define n count list and loop over delta, y to get the counts, then check which n has count == 1. >>> solution(3) 0 >>> solution(10) 3 >>> solution(100) 25 >>> solution(110) 27 """ n_sol = [0] * n_limit for delta in range(1, (n_limit + 1) // 4 + 1): for y in range(4 * delta - 1, delta, -1): n = y * (4 * delta - y) if n >= n_limit: break n_sol[n] += 1 ans = 0 for i in range(n_limit): if n_sol[i] == 1: ans += 1 return ans if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_136/__init__.py
project_euler/problem_136/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_050/sol1.py
project_euler/problem_050/sol1.py
""" Project Euler Problem 50: https://projecteuler.net/problem=50 Consecutive prime sum The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. Which prime, below one-million, can be written as the sum of the most consecutive primes? """ from __future__ import annotations def prime_sieve(limit: int) -> list[int]: """ Sieve of Erotosthenes Function to return all the prime numbers up to a number 'limit' https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes >>> prime_sieve(3) [2] >>> prime_sieve(50) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] """ is_prime = [True] * limit is_prime[0] = False is_prime[1] = False is_prime[2] = True for i in range(3, int(limit**0.5 + 1), 2): index = i * 2 while index < limit: is_prime[index] = False index = index + i primes = [2] for i in range(3, limit, 2): if is_prime[i]: primes.append(i) return primes def solution(ceiling: int = 1_000_000) -> int: """ Returns the biggest prime, below the celing, that can be written as the sum of consecutive the most consecutive primes. >>> solution(500) 499 >>> solution(1_000) 953 >>> solution(10_000) 9521 """ primes = prime_sieve(ceiling) length = 0 largest = 0 for i in range(len(primes)): for j in range(i + length, len(primes)): sol = sum(primes[i:j]) if sol >= ceiling: break if sol in primes: length = j - i largest = sol return largest if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_050/__init__.py
project_euler/problem_050/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_063/sol1.py
project_euler/problem_063/sol1.py
""" The 5-digit number, 16807=75, is also a fifth power. Similarly, the 9-digit number, 134217728=89, is a ninth power. How many n-digit positive integers exist which are also an nth power? """ """ The maximum base can be 9 because all n-digit numbers < 10^n. Now 9**23 has 22 digits so the maximum power can be 22. Using these conclusions, we will calculate the result. """ def solution(max_base: int = 10, max_power: int = 22) -> int: """ Returns the count of all n-digit numbers which are nth power >>> solution(10, 22) 49 >>> solution(0, 0) 0 >>> solution(1, 1) 0 >>> solution(-1, -1) 0 """ bases = range(1, max_base) powers = range(1, max_power) return sum( 1 for power in powers for base in bases if len(str(base**power)) == power ) if __name__ == "__main__": print(f"{solution(10, 22) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_063/__init__.py
project_euler/problem_063/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_173/sol1.py
project_euler/problem_173/sol1.py
""" Project Euler Problem 173: https://projecteuler.net/problem=173 We shall define a square lamina to be a square outline with a square "hole" so that the shape possesses vertical and horizontal symmetry. For example, using exactly thirty-two square tiles we can form two different square laminae: With one-hundred tiles, and not necessarily using all of the tiles at one time, it is possible to form forty-one different square laminae. Using up to one million tiles how many different square laminae can be formed? """ from math import ceil, sqrt def solution(limit: int = 1000000) -> int: """ Return the number of different square laminae that can be formed using up to one million tiles. >>> solution(100) 41 """ answer = 0 for outer_width in range(3, (limit // 4) + 2): if outer_width**2 > limit: hole_width_lower_bound = max(ceil(sqrt(outer_width**2 - limit)), 1) else: hole_width_lower_bound = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_173/__init__.py
project_euler/problem_173/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_207/sol1.py
project_euler/problem_207/sol1.py
""" Project Euler Problem 207: https://projecteuler.net/problem=207 Problem Statement: For some positive integers k, there exists an integer partition of the form 4**t = 2**t + k, where 4**t, 2**t, and k are all positive integers and t is a real number. The first two such partitions are 4**1 = 2**1 + 2 and 4**1.5849625... = 2**1.5849625... + 6. Partitions where t is also an integer are called perfect. For any m ≥ 1 let P(m) be the proportion of such partitions that are perfect with k ≤ m. Thus P(6) = 1/2. In the following table are listed some values of P(m) P(5) = 1/1 P(10) = 1/2 P(15) = 2/3 P(20) = 1/2 P(25) = 1/2 P(30) = 2/5 ... P(180) = 1/4 P(185) = 3/13 Find the smallest m for which P(m) < 1/12345 Solution: Equation 4**t = 2**t + k solved for t gives: t = log2(sqrt(4*k+1)/2 + 1/2) For t to be real valued, sqrt(4*k+1) must be an integer which is implemented in function check_t_real(k). For a perfect partition t must be an integer. To speed up significantly the search for partitions, instead of incrementing k by one per iteration, the next valid k is found by k = (i**2 - 1) / 4 with an integer i and k has to be a positive integer. If this is the case a partition is found. The partition is perfect if t os an integer. The integer i is increased with increment 1 until the proportion perfect partitions / total partitions drops under the given value. """ import math def check_partition_perfect(positive_integer: int) -> bool: """ Check if t = f(positive_integer) = log2(sqrt(4*positive_integer+1)/2 + 1/2) is a real number. >>> check_partition_perfect(2) True >>> check_partition_perfect(6) False """ exponent = math.log2(math.sqrt(4 * positive_integer + 1) / 2 + 1 / 2) return exponent == int(exponent) def solution(max_proportion: float = 1 / 12345) -> int: """ Find m for which the proportion of perfect partitions to total partitions is lower than max_proportion >>> solution(1) > 5 True >>> solution(1/2) > 10 True >>> solution(3 / 13) > 185 True """ total_partitions = 0 perfect_partitions = 0 integer = 3 while True: partition_candidate = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(partition_candidate): partition_candidate = int(partition_candidate) total_partitions += 1 if check_partition_perfect(partition_candidate): perfect_partitions += 1 if ( perfect_partitions > 0 and perfect_partitions / total_partitions < max_proportion ): return int(partition_candidate) integer += 1 if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_207/__init__.py
project_euler/problem_207/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_174/sol1.py
project_euler/problem_174/sol1.py
""" Project Euler Problem 174: https://projecteuler.net/problem=174 We shall define a square lamina to be a square outline with a square "hole" so that the shape possesses vertical and horizontal symmetry. Given eight tiles it is possible to form a lamina in only one way: 3x3 square with a 1x1 hole in the middle. However, using thirty-two tiles it is possible to form two distinct laminae. If t represents the number of tiles used, we shall say that t = 8 is type L(1) and t = 32 is type L(2). Let N(n) be the number of t ≤ 1000000 such that t is type L(n); for example, N(15) = 832. What is sum N(n) for 1 ≤ n ≤ 10? """ from collections import defaultdict from math import ceil, sqrt def solution(t_limit: int = 1000000, n_limit: int = 10) -> int: """ Return the sum of N(n) for 1 <= n <= n_limit. >>> solution(1000,5) 222 >>> solution(1000,10) 249 >>> solution(10000,10) 2383 """ count: defaultdict = defaultdict(int) for outer_width in range(3, (t_limit // 4) + 2): if outer_width * outer_width > t_limit: hole_width_lower_bound = max( ceil(sqrt(outer_width * outer_width - t_limit)), 1 ) else: hole_width_lower_bound = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(hole_width_lower_bound, outer_width - 1, 2): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= n_limit) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_174/__init__.py
project_euler/problem_174/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_115/sol1.py
project_euler/problem_115/sol1.py
""" Project Euler Problem 115: https://projecteuler.net/problem=115 NOTE: This is a more difficult version of Problem 114 (https://projecteuler.net/problem=114). A row measuring n units in length has red blocks with a minimum length of m units placed on it, such that any two red blocks (which are allowed to be different lengths) are separated by at least one black square. Let the fill-count function, F(m, n), represent the number of ways that a row can be filled. For example, F(3, 29) = 673135 and F(3, 30) = 1089155. That is, for m = 3, it can be seen that n = 30 is the smallest value for which the fill-count function first exceeds one million. In the same way, for m = 10, it can be verified that F(10, 56) = 880711 and F(10, 57) = 1148904, so n = 57 is the least value for which the fill-count function first exceeds one million. For m = 50, find the least value of n for which the fill-count function first exceeds one million. """ from itertools import count def solution(min_block_length: int = 50) -> int: """ Returns for given minimum block length the least value of n for which the fill-count function first exceeds one million >>> solution(3) 30 >>> solution(10) 57 """ fill_count_functions = [1] * min_block_length for n in count(min_block_length): fill_count_functions.append(1) for block_length in range(min_block_length, n + 1): for block_start in range(n - block_length): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_000_000: break return n if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_115/__init__.py
project_euler/problem_115/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_008/sol2.py
project_euler/problem_008/sol2.py
""" Project Euler Problem 8: https://projecteuler.net/problem=8 Largest product in a series The four adjacent digits in the 1000-digit number that have the greatest product are 9 x 9 x 8 x 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? """ from functools import reduce N = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def solution(n: str = N) -> int: """ Find the thirteen adjacent digits in the 1000-digit number n that have the greatest product and returns it. >>> solution("13978431290823798458352374") 609638400 >>> solution("13978431295823798458352374") 2612736000 >>> solution("1397843129582379841238352374") 209018880 """ return max( # mypy cannot properly interpret reduce int(reduce(lambda x, y: str(int(x) * int(y)), n[i : i + 13])) for i in range(len(n) - 12) ) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_008/sol3.py
project_euler/problem_008/sol3.py
""" Project Euler Problem 8: https://projecteuler.net/problem=8 Largest product in a series The four adjacent digits in the 1000-digit number that have the greatest product are 9 x 9 x 8 x 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? """ import sys N = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def str_eval(s: str) -> int: """ Returns product of digits in given string n >>> str_eval("987654321") 362880 >>> str_eval("22222222") 256 """ product = 1 for digit in s: product *= int(digit) return product def solution(n: str = N) -> int: """ Find the thirteen adjacent digits in the 1000-digit number n that have the greatest product and returns it. """ largest_product = -sys.maxsize - 1 substr = n[:13] cur_index = 13 while cur_index < len(n) - 13: if int(n[cur_index]) >= int(substr[0]): substr = substr[1:] + n[cur_index] cur_index += 1 else: largest_product = max(largest_product, str_eval(substr)) substr = n[cur_index : cur_index + 13] cur_index += 13 return largest_product if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_008/sol1.py
project_euler/problem_008/sol1.py
""" Project Euler Problem 8: https://projecteuler.net/problem=8 Largest product in a series The four adjacent digits in the 1000-digit number that have the greatest product are 9 x 9 x 8 x 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? """ import sys N = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def solution(n: str = N) -> int: """ Find the thirteen adjacent digits in the 1000-digit number n that have the greatest product and returns it. >>> solution("13978431290823798458352374") 609638400 >>> solution("13978431295823798458352374") 2612736000 >>> solution("1397843129582379841238352374") 209018880 """ largest_product = -sys.maxsize - 1 for i in range(len(n) - 12): product = 1 for j in range(13): product *= int(n[i + j]) largest_product = max(largest_product, product) return largest_product if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_008/__init__.py
project_euler/problem_008/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/electronics/resistor_color_code.py
electronics/resistor_color_code.py
""" Title : Calculating the resistance of a n band resistor using the color codes Description : Resistors resist the flow of electrical current.Each one has a value that tells how strongly it resists current flow.This value's unit is the ohm, often noted with the Greek letter omega: Ω. The colored bands on a resistor can tell you everything you need to know about its value and tolerance, as long as you understand how to read them. The order in which the colors are arranged is very important, and each value of resistor has its own unique combination. The color coding for resistors is an international standard that is defined in IEC 60062. The number of bands present in a resistor varies from three to six. These represent significant figures, multiplier, tolerance, reliability, and temperature coefficient Each color used for a type of band has a value assigned to it. It is read from left to right. All resistors will have significant figures and multiplier bands. In a three band resistor first two bands from the left represent significant figures and the third represents the multiplier band. Significant figures - The number of significant figures band in a resistor can vary from two to three. Colors and values associated with significant figure bands - (Black = 0, Brown = 1, Red = 2, Orange = 3, Yellow = 4, Green = 5, Blue = 6, Violet = 7, Grey = 8, White = 9) Multiplier - There will be one multiplier band in a resistor. It is multiplied with the significant figures obtained from previous bands. Colors and values associated with multiplier band - (Black = 100, Brown = 10^1, Red = 10^2, Orange = 10^3, Yellow = 10^4, Green = 10^5, Blue = 10^6, Violet = 10^7, Grey = 10^8, White = 10^9, Gold = 10^-1, Silver = 10^-2) Note that multiplier bands use Gold and Silver which are not used for significant figure bands. Tolerance - The tolerance band is not always present. It can be seen in four band resistors and above. This is a percentage by which the resistor value can vary. Colors and values associated with tolerance band - (Brown = 1%, Red = 2%, Orange = 0.05%, Yellow = 0.02%, Green = 0.5%,Blue = 0.25%, Violet = 0.1%, Grey = 0.01%, Gold = 5%, Silver = 10%) If no color is mentioned then by default tolerance is 20% Note that tolerance band does not use Black and White colors. Temperature Coeffecient - Indicates the change in resistance of the component as a function of ambient temperature in terms of ppm/K. It is present in six band resistors. Colors and values associated with Temperature coeffecient - (Black = 250 ppm/K, Brown = 100 ppm/K, Red = 50 ppm/K, Orange = 15 ppm/K, Yellow = 25 ppm/K, Green = 20 ppm/K, Blue = 10 ppm/K, Violet = 5 ppm/K, Grey = 1 ppm/K) Note that temperature coeffecient band does not use White, Gold, Silver colors. Sources : https://www.calculator.net/resistor-calculator.html https://learn.parallax.com/support/reference/resistor-color-codes https://byjus.com/physics/resistor-colour-codes/ """ valid_colors: list = [ "Black", "Brown", "Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Grey", "White", "Gold", "Silver", ] significant_figures_color_values: dict[str, int] = { "Black": 0, "Brown": 1, "Red": 2, "Orange": 3, "Yellow": 4, "Green": 5, "Blue": 6, "Violet": 7, "Grey": 8, "White": 9, } multiplier_color_values: dict[str, float] = { "Black": 10**0, "Brown": 10**1, "Red": 10**2, "Orange": 10**3, "Yellow": 10**4, "Green": 10**5, "Blue": 10**6, "Violet": 10**7, "Grey": 10**8, "White": 10**9, "Gold": 10**-1, "Silver": 10**-2, } tolerance_color_values: dict[str, float] = { "Brown": 1, "Red": 2, "Orange": 0.05, "Yellow": 0.02, "Green": 0.5, "Blue": 0.25, "Violet": 0.1, "Grey": 0.01, "Gold": 5, "Silver": 10, } temperature_coeffecient_color_values: dict[str, int] = { "Black": 250, "Brown": 100, "Red": 50, "Orange": 15, "Yellow": 25, "Green": 20, "Blue": 10, "Violet": 5, "Grey": 1, } band_types: dict[int, dict[str, int]] = { 3: {"significant": 2, "multiplier": 1}, 4: {"significant": 2, "multiplier": 1, "tolerance": 1}, 5: {"significant": 3, "multiplier": 1, "tolerance": 1}, 6: {"significant": 3, "multiplier": 1, "tolerance": 1, "temp_coeffecient": 1}, } def get_significant_digits(colors: list) -> str: """ Function returns the digit associated with the color. Function takes a list containing colors as input and returns digits as string >>> get_significant_digits(['Black','Blue']) '06' >>> get_significant_digits(['Aqua','Blue']) Traceback (most recent call last): ... ValueError: Aqua is not a valid color for significant figure bands """ digit = "" for color in colors: if color not in significant_figures_color_values: msg = f"{color} is not a valid color for significant figure bands" raise ValueError(msg) digit = digit + str(significant_figures_color_values[color]) return str(digit) def get_multiplier(color: str) -> float: """ Function returns the multiplier value associated with the color. Function takes color as input and returns multiplier value >>> get_multiplier('Gold') 0.1 >>> get_multiplier('Ivory') Traceback (most recent call last): ... ValueError: Ivory is not a valid color for multiplier band """ if color not in multiplier_color_values: msg = f"{color} is not a valid color for multiplier band" raise ValueError(msg) return multiplier_color_values[color] def get_tolerance(color: str) -> float: """ Function returns the tolerance value associated with the color. Function takes color as input and returns tolerance value. >>> get_tolerance('Green') 0.5 >>> get_tolerance('Indigo') Traceback (most recent call last): ... ValueError: Indigo is not a valid color for tolerance band """ if color not in tolerance_color_values: msg = f"{color} is not a valid color for tolerance band" raise ValueError(msg) return tolerance_color_values[color] def get_temperature_coeffecient(color: str) -> int: """ Function returns the temperature coeffecient value associated with the color. Function takes color as input and returns temperature coeffecient value. >>> get_temperature_coeffecient('Yellow') 25 >>> get_temperature_coeffecient('Cyan') Traceback (most recent call last): ... ValueError: Cyan is not a valid color for temperature coeffecient band """ if color not in temperature_coeffecient_color_values: msg = f"{color} is not a valid color for temperature coeffecient band" raise ValueError(msg) return temperature_coeffecient_color_values[color] def get_band_type_count(total_number_of_bands: int, type_of_band: str) -> int: """ Function returns the number of bands of a given type in a resistor with n bands Function takes total_number_of_bands and type_of_band as input and returns number of bands belonging to that type in the given resistor >>> get_band_type_count(3,'significant') 2 >>> get_band_type_count(2,'significant') Traceback (most recent call last): ... ValueError: 2 is not a valid number of bands >>> get_band_type_count(3,'sign') Traceback (most recent call last): ... ValueError: sign is not valid for a 3 band resistor >>> get_band_type_count(3,'tolerance') Traceback (most recent call last): ... ValueError: tolerance is not valid for a 3 band resistor >>> get_band_type_count(5,'temp_coeffecient') Traceback (most recent call last): ... ValueError: temp_coeffecient is not valid for a 5 band resistor """ if total_number_of_bands not in band_types: msg = f"{total_number_of_bands} is not a valid number of bands" raise ValueError(msg) if type_of_band not in band_types[total_number_of_bands]: msg = f"{type_of_band} is not valid for a {total_number_of_bands} band resistor" raise ValueError(msg) return band_types[total_number_of_bands][type_of_band] def check_validity(number_of_bands: int, colors: list) -> bool: """ Function checks if the input provided is valid or not. Function takes number_of_bands and colors as input and returns True if it is valid >>> check_validity(3, ["Black","Blue","Orange"]) True >>> check_validity(4, ["Black","Blue","Orange"]) Traceback (most recent call last): ... ValueError: Expecting 4 colors, provided 3 colors >>> check_validity(3, ["Cyan","Red","Yellow"]) Traceback (most recent call last): ... ValueError: Cyan is not a valid color """ if number_of_bands >= 3 and number_of_bands <= 6: if number_of_bands == len(colors): for color in colors: if color not in valid_colors: msg = f"{color} is not a valid color" raise ValueError(msg) return True else: msg = f"Expecting {number_of_bands} colors, provided {len(colors)} colors" raise ValueError(msg) else: msg = "Invalid number of bands. Resistor bands must be 3 to 6" raise ValueError(msg) def calculate_resistance(number_of_bands: int, color_code_list: list) -> dict: """ Function calculates the total resistance of the resistor using the color codes. Function takes number_of_bands, color_code_list as input and returns resistance >>> calculate_resistance(3, ["Black","Blue","Orange"]) {'resistance': '6000Ω ±20% '} >>> calculate_resistance(4, ["Orange","Green","Blue","Gold"]) {'resistance': '35000000Ω ±5% '} >>> calculate_resistance(5, ["Violet","Brown","Grey","Silver","Green"]) {'resistance': '7.18Ω ±0.5% '} >>> calculate_resistance(6, ["Red","Green","Blue","Yellow","Orange","Grey"]) {'resistance': '2560000Ω ±0.05% 1 ppm/K'} >>> calculate_resistance(0, ["Violet","Brown","Grey","Silver","Green"]) Traceback (most recent call last): ... ValueError: Invalid number of bands. Resistor bands must be 3 to 6 >>> calculate_resistance(4, ["Violet","Brown","Grey","Silver","Green"]) Traceback (most recent call last): ... ValueError: Expecting 4 colors, provided 5 colors >>> calculate_resistance(4, ["Violet","Silver","Brown","Grey"]) Traceback (most recent call last): ... ValueError: Silver is not a valid color for significant figure bands >>> calculate_resistance(4, ["Violet","Blue","Lime","Grey"]) Traceback (most recent call last): ... ValueError: Lime is not a valid color """ is_valid = check_validity(number_of_bands, color_code_list) if is_valid: number_of_significant_bands = get_band_type_count( number_of_bands, "significant" ) significant_colors = color_code_list[:number_of_significant_bands] significant_digits = int(get_significant_digits(significant_colors)) multiplier_color = color_code_list[number_of_significant_bands] multiplier = get_multiplier(multiplier_color) if number_of_bands == 3: tolerance_color = None else: tolerance_color = color_code_list[number_of_significant_bands + 1] tolerance = ( 20 if tolerance_color is None else get_tolerance(str(tolerance_color)) ) if number_of_bands != 6: temperature_coeffecient_color = None else: temperature_coeffecient_color = color_code_list[ number_of_significant_bands + 2 ] temperature_coeffecient = ( 0 if temperature_coeffecient_color is None else get_temperature_coeffecient(str(temperature_coeffecient_color)) ) resisitance = significant_digits * multiplier if temperature_coeffecient == 0: answer = f"{resisitance}Ω ±{tolerance}% " else: answer = f"{resisitance}Ω ±{tolerance}% {temperature_coeffecient} ppm/K" return {"resistance": answer} else: raise ValueError("Input is invalid") 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/electronics/charging_inductor.py
electronics/charging_inductor.py
# source - The ARRL Handbook for Radio Communications # https://en.wikipedia.org/wiki/RL_circuit """ Description ----------- Inductor is a passive electronic device which stores energy but unlike capacitor, it stores energy in its 'magnetic field' or 'magnetostatic field'. When inductor is connected to 'DC' current source nothing happens it just works like a wire because it's real effect cannot be seen while 'DC' is connected, its not even going to store energy. Inductor stores energy only when it is working on 'AC' current. Connecting a inductor in series with a resistor(when R = 0) to a 'AC' potential source, from zero to a finite value causes a sudden voltage to induced in inductor which opposes the current. which results in initially slowly current rise. However it would cease if there is no further changes in current. With resistance zero current will never stop rising. 'Resistance(ohms) / Inductance(henrys)' is known as RL-timeconstant. It also represents as τ (tau). While the charging of a inductor with a resistor results in a exponential function. when inductor is connected across 'AC' potential source. It starts to store the energy in its 'magnetic field'.with the help 'RL-time-constant' we can find current at any time in inductor while it is charging. """ from math import exp # value of exp = 2.718281828459… def charging_inductor( source_voltage: float, # source_voltage should be in volts. resistance: float, # resistance should be in ohms. inductance: float, # inductance should be in henrys. time: float, # time should in seconds. ) -> float: """ Find inductor current at any nth second after initiating its charging. Examples -------- >>> charging_inductor(source_voltage=5.8,resistance=1.5,inductance=2.3,time=2) 2.817 >>> charging_inductor(source_voltage=8,resistance=5,inductance=3,time=2) 1.543 >>> charging_inductor(source_voltage=8,resistance=5*pow(10,2),inductance=3,time=2) 0.016 >>> charging_inductor(source_voltage=-8,resistance=100,inductance=15,time=12) Traceback (most recent call last): ... ValueError: Source voltage must be positive. >>> charging_inductor(source_voltage=80,resistance=-15,inductance=100,time=5) Traceback (most recent call last): ... ValueError: Resistance must be positive. >>> charging_inductor(source_voltage=12,resistance=200,inductance=-20,time=5) Traceback (most recent call last): ... ValueError: Inductance must be positive. >>> charging_inductor(source_voltage=0,resistance=200,inductance=20,time=5) Traceback (most recent call last): ... ValueError: Source voltage must be positive. >>> charging_inductor(source_voltage=10,resistance=0,inductance=20,time=5) Traceback (most recent call last): ... ValueError: Resistance must be positive. >>> charging_inductor(source_voltage=15, resistance=25, inductance=0, time=5) Traceback (most recent call last): ... ValueError: Inductance must be positive. """ if source_voltage <= 0: raise ValueError("Source voltage must be positive.") if resistance <= 0: raise ValueError("Resistance must be positive.") if inductance <= 0: raise ValueError("Inductance must be positive.") return round( source_voltage / resistance * (1 - exp((-time * resistance) / inductance)), 3 ) 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/electronics/electric_power.py
electronics/electric_power.py
# https://en.m.wikipedia.org/wiki/Electric_power from __future__ import annotations from typing import NamedTuple class Result(NamedTuple): name: str value: float def electric_power(voltage: float, current: float, power: float) -> tuple: """ This function can calculate any one of the three (voltage, current, power), fundamental value of electrical system. examples are below: >>> electric_power(voltage=0, current=2, power=5) Result(name='voltage', value=2.5) >>> electric_power(voltage=2, current=2, power=0) Result(name='power', value=4.0) >>> electric_power(voltage=-2, current=3, power=0) Result(name='power', value=6.0) >>> electric_power(voltage=2, current=4, power=2) Traceback (most recent call last): ... ValueError: Exactly one argument must be 0 >>> electric_power(voltage=0, current=0, power=2) Traceback (most recent call last): ... ValueError: Exactly one argument must be 0 >>> electric_power(voltage=0, current=2, power=-4) Traceback (most recent call last): ... ValueError: Power cannot be negative in any electrical/electronics system >>> electric_power(voltage=2.2, current=2.2, power=0) Result(name='power', value=4.84) >>> electric_power(current=0, power=6, voltage=2) Result(name='current', value=3.0) """ if (voltage, current, power).count(0) != 1: raise ValueError("Exactly one argument must be 0") elif power < 0: raise ValueError( "Power cannot be negative in any electrical/electronics system" ) elif voltage == 0: return Result("voltage", power / current) elif current == 0: return Result("current", power / voltage) elif power == 0: return Result("power", float(round(abs(voltage * current), 2))) else: raise AssertionError 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/electronics/apparent_power.py
electronics/apparent_power.py
import cmath import math def apparent_power( voltage: float, current: float, voltage_angle: float, current_angle: float ) -> complex: """ Calculate the apparent power in a single-phase AC circuit. Reference: https://en.wikipedia.org/wiki/AC_power#Apparent_power >>> apparent_power(100, 5, 0, 0) (500+0j) >>> apparent_power(100, 5, 90, 0) (3.061616997868383e-14+500j) >>> apparent_power(100, 5, -45, -60) (-129.40952255126027-482.9629131445341j) >>> apparent_power(200, 10, -30, -90) (-999.9999999999998-1732.0508075688776j) """ # Convert angles from degrees to radians voltage_angle_rad = math.radians(voltage_angle) current_angle_rad = math.radians(current_angle) # Convert voltage and current to rectangular form voltage_rect = cmath.rect(voltage, voltage_angle_rad) current_rect = cmath.rect(current, current_angle_rad) # Calculate apparent power return voltage_rect * current_rect 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/electronics/real_and_reactive_power.py
electronics/real_and_reactive_power.py
import math def real_power(apparent_power: float, power_factor: float) -> float: """ Calculate real power from apparent power and power factor. Examples: >>> real_power(100, 0.9) 90.0 >>> real_power(0, 0.8) 0.0 >>> real_power(100, -0.9) -90.0 """ if ( not isinstance(power_factor, (int, float)) or power_factor < -1 or power_factor > 1 ): raise ValueError("power_factor must be a valid float value between -1 and 1.") return apparent_power * power_factor def reactive_power(apparent_power: float, power_factor: float) -> float: """ Calculate reactive power from apparent power and power factor. Examples: >>> reactive_power(100, 0.9) 43.58898943540673 >>> reactive_power(0, 0.8) 0.0 >>> reactive_power(100, -0.9) 43.58898943540673 """ if ( not isinstance(power_factor, (int, float)) or power_factor < -1 or power_factor > 1 ): raise ValueError("power_factor must be a valid float value between -1 and 1.") return apparent_power * math.sqrt(1 - power_factor**2) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/electronics/capacitor_equivalence.py
electronics/capacitor_equivalence.py
# https://farside.ph.utexas.edu/teaching/316/lectures/node46.html from __future__ import annotations def capacitor_parallel(capacitors: list[float]) -> float: """ Ceq = C1 + C2 + ... + Cn Calculate the equivalent resistance for any number of capacitors in parallel. >>> capacitor_parallel([5.71389, 12, 3]) 20.71389 >>> capacitor_parallel([5.71389, 12, -3]) Traceback (most recent call last): ... ValueError: Capacitor at index 2 has a negative value! """ sum_c = 0.0 for index, capacitor in enumerate(capacitors): if capacitor < 0: msg = f"Capacitor at index {index} has a negative value!" raise ValueError(msg) sum_c += capacitor return sum_c def capacitor_series(capacitors: list[float]) -> float: """ Ceq = 1/ (1/C1 + 1/C2 + ... + 1/Cn) >>> capacitor_series([5.71389, 12, 3]) 1.6901062252507735 >>> capacitor_series([5.71389, 12, -3]) Traceback (most recent call last): ... ValueError: Capacitor at index 2 has a negative or zero value! >>> capacitor_series([5.71389, 12, 0.000]) Traceback (most recent call last): ... ValueError: Capacitor at index 2 has a negative or zero value! """ first_sum = 0.0 for index, capacitor in enumerate(capacitors): if capacitor <= 0: msg = f"Capacitor at index {index} has a negative or zero value!" raise ValueError(msg) first_sum += 1 / capacitor return 1 / first_sum 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/electronics/wheatstone_bridge.py
electronics/wheatstone_bridge.py
# https://en.wikipedia.org/wiki/Wheatstone_bridge from __future__ import annotations def wheatstone_solver( resistance_1: float, resistance_2: float, resistance_3: float ) -> float: """ This function can calculate the unknown resistance in an wheatstone network, given that the three other resistances in the network are known. The formula to calculate the same is: --------------- |Rx=(R2/R1)*R3| --------------- Usage examples: >>> wheatstone_solver(resistance_1=2, resistance_2=4, resistance_3=5) 10.0 >>> wheatstone_solver(resistance_1=356, resistance_2=234, resistance_3=976) 641.5280898876405 >>> wheatstone_solver(resistance_1=2, resistance_2=-1, resistance_3=2) Traceback (most recent call last): ... ValueError: All resistance values must be positive >>> wheatstone_solver(resistance_1=0, resistance_2=0, resistance_3=2) Traceback (most recent call last): ... ValueError: All resistance values must be positive """ if resistance_1 <= 0 or resistance_2 <= 0 or resistance_3 <= 0: raise ValueError("All resistance values must be positive") else: return float((resistance_2 / resistance_1) * resistance_3) 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/electronics/ic_555_timer.py
electronics/ic_555_timer.py
from __future__ import annotations """ Calculate the frequency and/or duty cycle of an astable 555 timer. * https://en.wikipedia.org/wiki/555_timer_IC#Astable These functions take in the value of the external resistances (in ohms) and capacitance (in Microfarad), and calculates the following: ------------------------------------- | Freq = 1.44 /[( R1+ 2 x R2) x C1] | ... in Hz ------------------------------------- where Freq is the frequency, R1 is the first resistance in ohms, R2 is the second resistance in ohms, C1 is the capacitance in Microfarads. ------------------------------------------------ | Duty Cycle = (R1 + R2) / (R1 + 2 x R2) x 100 | ... in % ------------------------------------------------ where R1 is the first resistance in ohms, R2 is the second resistance in ohms. """ def astable_frequency( resistance_1: float, resistance_2: float, capacitance: float ) -> float: """ Usage examples: >>> astable_frequency(resistance_1=45, resistance_2=45, capacitance=7) 1523.8095238095239 >>> astable_frequency(resistance_1=356, resistance_2=234, capacitance=976) 1.7905459175553078 >>> astable_frequency(resistance_1=2, resistance_2=-1, capacitance=2) Traceback (most recent call last): ... ValueError: All values must be positive >>> astable_frequency(resistance_1=45, resistance_2=45, capacitance=0) Traceback (most recent call last): ... ValueError: All values must be positive """ if resistance_1 <= 0 or resistance_2 <= 0 or capacitance <= 0: raise ValueError("All values must be positive") return (1.44 / ((resistance_1 + 2 * resistance_2) * capacitance)) * 10**6 def astable_duty_cycle(resistance_1: float, resistance_2: float) -> float: """ Usage examples: >>> astable_duty_cycle(resistance_1=45, resistance_2=45) 66.66666666666666 >>> astable_duty_cycle(resistance_1=356, resistance_2=234) 71.60194174757282 >>> astable_duty_cycle(resistance_1=2, resistance_2=-1) Traceback (most recent call last): ... ValueError: All values must be positive >>> astable_duty_cycle(resistance_1=0, resistance_2=0) Traceback (most recent call last): ... ValueError: All values must be positive """ if resistance_1 <= 0 or resistance_2 <= 0: raise ValueError("All values must be positive") return (resistance_1 + resistance_2) / (resistance_1 + 2 * resistance_2) * 100 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/electronics/circular_convolution.py
electronics/circular_convolution.py
# https://en.wikipedia.org/wiki/Circular_convolution """ Circular convolution, also known as cyclic convolution, is a special case of periodic convolution, which is the convolution of two periodic functions that have the same period. Periodic convolution arises, for example, in the context of the discrete-time Fourier transform (DTFT). In particular, the DTFT of the product of two discrete sequences is the periodic convolution of the DTFTs of the individual sequences. And each DTFT is a periodic summation of a continuous Fourier transform function. Source: https://en.wikipedia.org/wiki/Circular_convolution """ import doctest from collections import deque import numpy as np class CircularConvolution: """ This class stores the first and second signal and performs the circular convolution """ def __init__(self) -> None: """ First signal and second signal are stored as 1-D array """ self.first_signal = [2, 1, 2, -1] self.second_signal = [1, 2, 3, 4] def circular_convolution(self) -> list[float]: """ This function performs the circular convolution of the first and second signal using matrix method Usage: >>> convolution = CircularConvolution() >>> convolution.circular_convolution() [10.0, 10.0, 6.0, 14.0] >>> convolution.first_signal = [0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6] >>> convolution.second_signal = [0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5] >>> convolution.circular_convolution() [5.2, 6.0, 6.48, 6.64, 6.48, 6.0, 5.2, 4.08] >>> convolution.first_signal = [-1, 1, 2, -2] >>> convolution.second_signal = [0.5, 1, -1, 2, 0.75] >>> convolution.circular_convolution() [6.25, -3.0, 1.5, -2.0, -2.75] >>> convolution.first_signal = [1, -1, 2, 3, -1] >>> convolution.second_signal = [1, 2, 3] >>> convolution.circular_convolution() [8.0, -2.0, 3.0, 4.0, 11.0] """ length_first_signal = len(self.first_signal) length_second_signal = len(self.second_signal) max_length = max(length_first_signal, length_second_signal) # create a zero matrix of max_length x max_length matrix = [[0] * max_length for i in range(max_length)] # fills the smaller signal with zeros to make both signals of same length if length_first_signal < length_second_signal: self.first_signal += [0] * (max_length - length_first_signal) elif length_first_signal > length_second_signal: self.second_signal += [0] * (max_length - length_second_signal) """ Fills the matrix in the following way assuming 'x' is the signal of length 4 [ [x[0], x[3], x[2], x[1]], [x[1], x[0], x[3], x[2]], [x[2], x[1], x[0], x[3]], [x[3], x[2], x[1], x[0]] ] """ for i in range(max_length): rotated_signal = deque(self.second_signal) rotated_signal.rotate(i) for j, item in enumerate(rotated_signal): matrix[i][j] += item # multiply the matrix with the first signal final_signal = np.matmul(np.transpose(matrix), np.transpose(self.first_signal)) # rounding-off to two decimal places return [float(round(i, 2)) for i in final_signal] if __name__ == "__main__": doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/electronics/carrier_concentration.py
electronics/carrier_concentration.py
# https://en.wikipedia.org/wiki/Charge_carrier_density # https://www.pveducation.org/pvcdrom/pn-junctions/equilibrium-carrier-concentration # http://www.ece.utep.edu/courses/ee3329/ee3329/Studyguide/ToC/Fundamentals/Carriers/concentrations.html from __future__ import annotations def carrier_concentration( electron_conc: float, hole_conc: float, intrinsic_conc: float, ) -> tuple: """ This function can calculate any one of the three - 1. Electron Concentration 2, Hole Concentration 3. Intrinsic Concentration given the other two. Examples - >>> carrier_concentration(electron_conc=25, hole_conc=100, intrinsic_conc=0) ('intrinsic_conc', 50.0) >>> carrier_concentration(electron_conc=0, hole_conc=1600, intrinsic_conc=200) ('electron_conc', 25.0) >>> carrier_concentration(electron_conc=1000, hole_conc=0, intrinsic_conc=1200) ('hole_conc', 1440.0) >>> carrier_concentration(electron_conc=1000, hole_conc=400, intrinsic_conc=1200) Traceback (most recent call last): ... ValueError: You cannot supply more or less than 2 values >>> carrier_concentration(electron_conc=-1000, hole_conc=0, intrinsic_conc=1200) Traceback (most recent call last): ... ValueError: Electron concentration cannot be negative in a semiconductor >>> carrier_concentration(electron_conc=0, hole_conc=-400, intrinsic_conc=1200) Traceback (most recent call last): ... ValueError: Hole concentration cannot be negative in a semiconductor >>> carrier_concentration(electron_conc=0, hole_conc=400, intrinsic_conc=-1200) Traceback (most recent call last): ... ValueError: Intrinsic concentration cannot be negative in a semiconductor """ if (electron_conc, hole_conc, intrinsic_conc).count(0) != 1: raise ValueError("You cannot supply more or less than 2 values") elif electron_conc < 0: raise ValueError("Electron concentration cannot be negative in a semiconductor") elif hole_conc < 0: raise ValueError("Hole concentration cannot be negative in a semiconductor") elif intrinsic_conc < 0: raise ValueError( "Intrinsic concentration cannot be negative in a semiconductor" ) elif electron_conc == 0: return ( "electron_conc", intrinsic_conc**2 / hole_conc, ) elif hole_conc == 0: return ( "hole_conc", intrinsic_conc**2 / electron_conc, ) elif intrinsic_conc == 0: return ( "intrinsic_conc", (electron_conc * hole_conc) ** 0.5, ) else: return (-1, -1) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/electronics/ind_reactance.py
electronics/ind_reactance.py
# https://en.wikipedia.org/wiki/Electrical_reactance#Inductive_reactance from __future__ import annotations from math import pi def ind_reactance( inductance: float, frequency: float, reactance: float ) -> dict[str, float]: """ Calculate inductive reactance, frequency or inductance from two given electrical properties then return name/value pair of the zero value in a Python dict. Parameters ---------- inductance : float with units in Henries frequency : float with units in Hertz reactance : float with units in Ohms >>> ind_reactance(-35e-6, 1e3, 0) Traceback (most recent call last): ... ValueError: Inductance cannot be negative >>> ind_reactance(35e-6, -1e3, 0) Traceback (most recent call last): ... ValueError: Frequency cannot be negative >>> ind_reactance(35e-6, 0, -1) Traceback (most recent call last): ... ValueError: Inductive reactance cannot be negative >>> ind_reactance(0, 10e3, 50) {'inductance': 0.0007957747154594767} >>> ind_reactance(35e-3, 0, 50) {'frequency': 227.36420441699332} >>> ind_reactance(35e-6, 1e3, 0) {'reactance': 0.2199114857512855} """ if (inductance, frequency, reactance).count(0) != 1: raise ValueError("One and only one argument must be 0") if inductance < 0: raise ValueError("Inductance cannot be negative") if frequency < 0: raise ValueError("Frequency cannot be negative") if reactance < 0: raise ValueError("Inductive reactance cannot be negative") if inductance == 0: return {"inductance": reactance / (2 * pi * frequency)} elif frequency == 0: return {"frequency": reactance / (2 * pi * inductance)} elif reactance == 0: return {"reactance": 2 * pi * frequency * inductance} else: raise ValueError("Exactly one argument must be 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/electronics/resistor_equivalence.py
electronics/resistor_equivalence.py
# https://byjus.com/equivalent-resistance-formula/ from __future__ import annotations def resistor_parallel(resistors: list[float]) -> float: """ Req = 1/ (1/R1 + 1/R2 + ... + 1/Rn) >>> resistor_parallel([3.21389, 2, 3]) 0.8737571620498019 >>> resistor_parallel([3.21389, 2, -3]) Traceback (most recent call last): ... ValueError: Resistor at index 2 has a negative or zero value! >>> resistor_parallel([3.21389, 2, 0.000]) Traceback (most recent call last): ... ValueError: Resistor at index 2 has a negative or zero value! """ first_sum = 0.00 for index, resistor in enumerate(resistors): if resistor <= 0: msg = f"Resistor at index {index} has a negative or zero value!" raise ValueError(msg) first_sum += 1 / float(resistor) return 1 / first_sum def resistor_series(resistors: list[float]) -> float: """ Req = R1 + R2 + ... + Rn Calculate the equivalent resistance for any number of resistors in parallel. >>> resistor_series([3.21389, 2, 3]) 8.21389 >>> resistor_series([3.21389, 2, -3]) Traceback (most recent call last): ... ValueError: Resistor at index 2 has a negative value! """ sum_r = 0.00 for index, resistor in enumerate(resistors): sum_r += resistor if resistor < 0: msg = f"Resistor at index {index} has a negative value!" raise ValueError(msg) return sum_r 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/electronics/__init__.py
electronics/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/electronics/builtin_voltage.py
electronics/builtin_voltage.py
from math import log from scipy.constants import Boltzmann, physical_constants T = 300 # TEMPERATURE (unit = K) def builtin_voltage( donor_conc: float, # donor concentration acceptor_conc: float, # acceptor concentration intrinsic_conc: float, # intrinsic concentration ) -> float: """ This function can calculate the Builtin Voltage of a pn junction diode. This is calculated from the given three values. Examples - >>> builtin_voltage(donor_conc=1e17, acceptor_conc=1e17, intrinsic_conc=1e10) 0.833370010652644 >>> builtin_voltage(donor_conc=0, acceptor_conc=1600, intrinsic_conc=200) Traceback (most recent call last): ... ValueError: Donor concentration should be positive >>> builtin_voltage(donor_conc=1000, acceptor_conc=0, intrinsic_conc=1200) Traceback (most recent call last): ... ValueError: Acceptor concentration should be positive >>> builtin_voltage(donor_conc=1000, acceptor_conc=1000, intrinsic_conc=0) Traceback (most recent call last): ... ValueError: Intrinsic concentration should be positive >>> builtin_voltage(donor_conc=1000, acceptor_conc=3000, intrinsic_conc=2000) Traceback (most recent call last): ... ValueError: Donor concentration should be greater than intrinsic concentration >>> builtin_voltage(donor_conc=3000, acceptor_conc=1000, intrinsic_conc=2000) Traceback (most recent call last): ... ValueError: Acceptor concentration should be greater than intrinsic concentration """ if donor_conc <= 0: raise ValueError("Donor concentration should be positive") elif acceptor_conc <= 0: raise ValueError("Acceptor concentration should be positive") elif intrinsic_conc <= 0: raise ValueError("Intrinsic concentration should be positive") elif donor_conc <= intrinsic_conc: raise ValueError( "Donor concentration should be greater than intrinsic concentration" ) elif acceptor_conc <= intrinsic_conc: raise ValueError( "Acceptor concentration should be greater than intrinsic concentration" ) else: return ( Boltzmann * T * log((donor_conc * acceptor_conc) / intrinsic_conc**2) / physical_constants["electron volt"][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/electronics/ohms_law.py
electronics/ohms_law.py
# https://en.wikipedia.org/wiki/Ohm%27s_law from __future__ import annotations def ohms_law(voltage: float, current: float, resistance: float) -> dict[str, float]: """ Apply Ohm's Law, on any two given electrical values, which can be voltage, current, and resistance, and then in a Python dict return name/value pair of the zero value. >>> ohms_law(voltage=10, resistance=5, current=0) {'current': 2.0} >>> ohms_law(voltage=0, current=0, resistance=10) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 >>> ohms_law(voltage=0, current=1, resistance=-2) Traceback (most recent call last): ... ValueError: Resistance cannot be negative >>> ohms_law(resistance=0, voltage=-10, current=1) {'resistance': -10.0} >>> ohms_law(voltage=0, current=-1.5, resistance=2) {'voltage': -3.0} """ if (voltage, current, resistance).count(0) != 1: raise ValueError("One and only one argument must be 0") if resistance < 0: raise ValueError("Resistance cannot be negative") if voltage == 0: return {"voltage": float(current * resistance)} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("Exactly one argument must be 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/electronics/resonant_frequency.py
electronics/resonant_frequency.py
# https://en.wikipedia.org/wiki/LC_circuit """An LC circuit, also called a resonant circuit, tank circuit, or tuned circuit, is an electric circuit consisting of an inductor, represented by the letter L, and a capacitor, represented by the letter C, connected together. The circuit can act as an electrical resonator, an electrical analogue of a tuning fork, storing energy oscillating at the circuit's resonant frequency. Source: https://en.wikipedia.org/wiki/LC_circuit """ from __future__ import annotations from math import pi, sqrt def resonant_frequency(inductance: float, capacitance: float) -> tuple: """ This function can calculate the resonant frequency of LC circuit, for the given value of inductance and capacitnace. Examples are given below: >>> resonant_frequency(inductance=10, capacitance=5) ('Resonant frequency', 0.022507907903927652) >>> resonant_frequency(inductance=0, capacitance=5) Traceback (most recent call last): ... ValueError: Inductance cannot be 0 or negative >>> resonant_frequency(inductance=10, capacitance=0) Traceback (most recent call last): ... ValueError: Capacitance cannot be 0 or negative """ if inductance <= 0: raise ValueError("Inductance cannot be 0 or negative") elif capacitance <= 0: raise ValueError("Capacitance cannot be 0 or negative") else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance)))), ) 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/electronics/charging_capacitor.py
electronics/charging_capacitor.py
# source - The ARRL Handbook for Radio Communications # https://en.wikipedia.org/wiki/RC_time_constant """ Description ----------- When a capacitor is connected with a potential source (AC or DC). It starts to charge at a general speed but when a resistor is connected in the circuit with in series to a capacitor then the capacitor charges slowly means it will take more time than usual. while the capacitor is being charged, the voltage is in exponential function with time. 'resistance(ohms) * capacitance(farads)' is called RC-timeconstant which may also be represented as τ (tau). By using this RC-timeconstant we can find the voltage at any time 't' from the initiation of charging a capacitor with the help of the exponential function containing RC. Both at charging and discharging of a capacitor. """ from math import exp # value of exp = 2.718281828459… def charging_capacitor( source_voltage: float, # voltage in volts. resistance: float, # resistance in ohms. capacitance: float, # capacitance in farads. time_sec: float, # time in seconds after charging initiation of capacitor. ) -> float: """ Find capacitor voltage at any nth second after initiating its charging. Examples -------- >>> charging_capacitor(source_voltage=.2,resistance=.9,capacitance=8.4,time_sec=.5) 0.013 >>> charging_capacitor(source_voltage=2.2,resistance=3.5,capacitance=2.4,time_sec=9) 1.446 >>> charging_capacitor(source_voltage=15,resistance=200,capacitance=20,time_sec=2) 0.007 >>> charging_capacitor(20, 2000, 30*pow(10,-5), 4) 19.975 >>> charging_capacitor(source_voltage=0,resistance=10.0,capacitance=.30,time_sec=3) Traceback (most recent call last): ... ValueError: Source voltage must be positive. >>> charging_capacitor(source_voltage=20,resistance=-2000,capacitance=30,time_sec=4) Traceback (most recent call last): ... ValueError: Resistance must be positive. >>> charging_capacitor(source_voltage=30,resistance=1500,capacitance=0,time_sec=4) Traceback (most recent call last): ... ValueError: Capacitance must be positive. """ if source_voltage <= 0: raise ValueError("Source voltage must be positive.") if resistance <= 0: raise ValueError("Resistance must be positive.") if capacitance <= 0: raise ValueError("Capacitance must be positive.") return round(source_voltage * (1 - exp(-time_sec / (resistance * capacitance))), 3) 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/electronics/electric_conductivity.py
electronics/electric_conductivity.py
from __future__ import annotations ELECTRON_CHARGE = 1.6021e-19 # units = C def electric_conductivity( conductivity: float, electron_conc: float, mobility: float, ) -> tuple[str, float]: """ This function can calculate any one of the three - 1. Conductivity 2. Electron Concentration 3. Electron Mobility This is calculated from the other two provided values Examples - >>> electric_conductivity(conductivity=25, electron_conc=100, mobility=0) ('mobility', 1.5604519068722301e+18) >>> electric_conductivity(conductivity=0, electron_conc=1600, mobility=200) ('conductivity', 5.12672e-14) >>> electric_conductivity(conductivity=1000, electron_conc=0, mobility=1200) ('electron_conc', 5.201506356240767e+18) >>> electric_conductivity(conductivity=-10, electron_conc=100, mobility=0) Traceback (most recent call last): ... ValueError: Conductivity cannot be negative >>> electric_conductivity(conductivity=50, electron_conc=-10, mobility=0) Traceback (most recent call last): ... ValueError: Electron concentration cannot be negative >>> electric_conductivity(conductivity=50, electron_conc=0, mobility=-10) Traceback (most recent call last): ... ValueError: mobility cannot be negative >>> electric_conductivity(conductivity=50, electron_conc=0, mobility=0) Traceback (most recent call last): ... ValueError: You cannot supply more or less than 2 values >>> electric_conductivity(conductivity=50, electron_conc=200, mobility=300) Traceback (most recent call last): ... ValueError: You cannot supply more or less than 2 values """ if (conductivity, electron_conc, mobility).count(0) != 1: raise ValueError("You cannot supply more or less than 2 values") elif conductivity < 0: raise ValueError("Conductivity cannot be negative") elif electron_conc < 0: raise ValueError("Electron concentration cannot be negative") elif mobility < 0: raise ValueError("mobility cannot be negative") elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) 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/electronics/coulombs_law.py
electronics/coulombs_law.py
# https://en.wikipedia.org/wiki/Coulomb%27s_law from __future__ import annotations COULOMBS_CONSTANT = 8.988e9 # units = N * m^s * C^-2 def couloumbs_law( force: float, charge1: float, charge2: float, distance: float ) -> dict[str, float]: """ Apply Coulomb's Law on any three given values. These can be force, charge1, charge2, or distance, and then in a Python dict return name/value pair of the zero value. Coulomb's Law states that the magnitude of the electrostatic force of attraction or repulsion between two point charges is directly proportional to the product of the magnitudes of charges and inversely proportional to the square of the distance between them. Reference ---------- Coulomb (1785) "Premier mémoire sur l'électricité et le magnétisme," Histoire de l'Académie Royale des Sciences, pp. 569-577. Parameters ---------- force : float with units in Newtons charge1 : float with units in Coulombs charge2 : float with units in Coulombs distance : float with units in meters Returns ------- result : dict name/value pair of the zero value >>> couloumbs_law(force=0, charge1=3, charge2=5, distance=2000) {'force': 33705.0} >>> couloumbs_law(force=10, charge1=3, charge2=5, distance=0) {'distance': 116112.01488218177} >>> couloumbs_law(force=10, charge1=0, charge2=5, distance=2000) {'charge1': 0.0008900756564307966} >>> couloumbs_law(force=0, charge1=0, charge2=5, distance=2000) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 >>> couloumbs_law(force=0, charge1=3, charge2=5, distance=-2000) Traceback (most recent call last): ... ValueError: Distance cannot be negative """ charge_product = abs(charge1 * charge2) if (force, charge1, charge2, distance).count(0) != 1: raise ValueError("One and only one argument must be 0") if distance < 0: raise ValueError("Distance cannot be negative") if force == 0: force = COULOMBS_CONSTANT * charge_product / (distance**2) return {"force": force} elif charge1 == 0: charge1 = abs(force) * (distance**2) / (COULOMBS_CONSTANT * charge2) return {"charge1": charge1} elif charge2 == 0: charge2 = abs(force) * (distance**2) / (COULOMBS_CONSTANT * charge1) return {"charge2": charge2} elif distance == 0: distance = (COULOMBS_CONSTANT * charge_product / abs(force)) ** 0.5 return {"distance": distance} raise ValueError("Exactly one argument must be 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/electronics/electrical_impedance.py
electronics/electrical_impedance.py
"""Electrical impedance is the measure of the opposition that a circuit presents to a current when a voltage is applied. Impedance extends the concept of resistance to alternating current (AC) circuits. Source: https://en.wikipedia.org/wiki/Electrical_impedance """ from __future__ import annotations from math import pow, sqrt # noqa: A004 def electrical_impedance( resistance: float, reactance: float, impedance: float ) -> dict[str, float]: """ Apply Electrical Impedance formula, on any two given electrical values, which can be resistance, reactance, and impedance, and then in a Python dict return name/value pair of the zero value. >>> electrical_impedance(3,4,0) {'impedance': 5.0} >>> electrical_impedance(0,4,5) {'resistance': 3.0} >>> electrical_impedance(3,0,5) {'reactance': 4.0} >>> electrical_impedance(3,4,5) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 """ if (resistance, reactance, impedance).count(0) != 1: raise ValueError("One and only one argument must be 0") if resistance == 0: return {"resistance": sqrt(pow(impedance, 2) - pow(reactance, 2))} elif reactance == 0: return {"reactance": sqrt(pow(impedance, 2) - pow(resistance, 2))} elif impedance == 0: return {"impedance": sqrt(pow(resistance, 2) + pow(reactance, 2))} else: raise ValueError("Exactly one argument must be 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/cellular_automata/wa_tor.py
cellular_automata/wa_tor.py
""" Wa-Tor algorithm (1984) | @ https://en.wikipedia.org/wiki/Wa-Tor | @ https://beltoforion.de/en/wator/ | @ https://beltoforion.de/en/wator/images/wator_medium.webm This solution aims to completely remove any systematic approach to the Wa-Tor planet, and utilise fully random methods. The constants are a working set that allows the Wa-Tor planet to result in one of the three possible results. """ from collections.abc import Callable from random import randint, shuffle from time import sleep from typing import Literal WIDTH = 50 # Width of the Wa-Tor planet HEIGHT = 50 # Height of the Wa-Tor planet PREY_INITIAL_COUNT = 30 # The initial number of prey entities PREY_REPRODUCTION_TIME = 5 # The chronons before reproducing PREDATOR_INITIAL_COUNT = 50 # The initial number of predator entities # The initial energy value of predator entities PREDATOR_INITIAL_ENERGY_VALUE = 15 # The energy value provided when consuming prey PREDATOR_FOOD_VALUE = 5 PREDATOR_REPRODUCTION_TIME = 20 # The chronons before reproducing MAX_ENTITIES = 500 # The max number of organisms on the board # The number of entities to delete from the unbalanced side DELETE_UNBALANCED_ENTITIES = 50 class Entity: """ Represents an entity (either prey or predator). >>> e = Entity(True, coords=(0, 0)) >>> e.prey True >>> e.coords (0, 0) >>> e.alive True """ def __init__(self, prey: bool, coords: tuple[int, int]) -> None: self.prey = prey # The (row, col) pos of the entity self.coords = coords self.remaining_reproduction_time = ( PREY_REPRODUCTION_TIME if prey else PREDATOR_REPRODUCTION_TIME ) self.energy_value = None if prey is True else PREDATOR_INITIAL_ENERGY_VALUE self.alive = True def reset_reproduction_time(self) -> None: """ >>> e = Entity(True, coords=(0, 0)) >>> e.reset_reproduction_time() >>> e.remaining_reproduction_time == PREY_REPRODUCTION_TIME True >>> e = Entity(False, coords=(0, 0)) >>> e.reset_reproduction_time() >>> e.remaining_reproduction_time == PREDATOR_REPRODUCTION_TIME True """ self.remaining_reproduction_time = ( PREY_REPRODUCTION_TIME if self.prey is True else PREDATOR_REPRODUCTION_TIME ) def __repr__(self) -> str: """ >>> Entity(prey=True, coords=(1, 1)) Entity(prey=True, coords=(1, 1), remaining_reproduction_time=5) >>> Entity(prey=False, coords=(2, 1)) # doctest: +NORMALIZE_WHITESPACE Entity(prey=False, coords=(2, 1), remaining_reproduction_time=20, energy_value=15) """ repr_ = ( f"Entity(prey={self.prey}, coords={self.coords}, " f"remaining_reproduction_time={self.remaining_reproduction_time}" ) if self.energy_value is not None: repr_ += f", energy_value={self.energy_value}" return f"{repr_})" class WaTor: """ Represents the main Wa-Tor algorithm. :attr time_passed: A function that is called every time time passes (a chronon) in order to visually display the new Wa-Tor planet. The `time_passed` function can block using ``time.sleep`` to slow the algorithm progression. >>> wt = WaTor(10, 15) >>> wt.width 10 >>> wt.height 15 >>> len(wt.planet) 15 >>> len(wt.planet[0]) 10 >>> len(wt.get_entities()) == PREDATOR_INITIAL_COUNT + PREY_INITIAL_COUNT True """ time_passed: Callable[["WaTor", int], None] | None def __init__(self, width: int, height: int) -> None: self.width = width self.height = height self.time_passed = None self.planet: list[list[Entity | None]] = [[None] * width for _ in range(height)] # Populate planet with predators and prey randomly for _ in range(PREY_INITIAL_COUNT): self.add_entity(prey=True) for _ in range(PREDATOR_INITIAL_COUNT): self.add_entity(prey=False) self.set_planet(self.planet) def set_planet(self, planet: list[list[Entity | None]]) -> None: """ Ease of access for testing >>> wt = WaTor(WIDTH, HEIGHT) >>> planet = [ ... [None, None, None], ... [None, Entity(True, coords=(1, 1)), None] ... ] >>> wt.set_planet(planet) >>> wt.planet == planet True >>> wt.width 3 >>> wt.height 2 """ self.planet = planet self.width = len(planet[0]) self.height = len(planet) def add_entity(self, prey: bool) -> None: """ Adds an entity, making sure the entity does not override another entity >>> wt = WaTor(WIDTH, HEIGHT) >>> wt.set_planet([[None, None], [None, None]]) >>> wt.add_entity(True) >>> len(wt.get_entities()) 1 >>> wt.add_entity(False) >>> len(wt.get_entities()) 2 """ while True: row, col = randint(0, self.height - 1), randint(0, self.width - 1) if self.planet[row][col] is None: self.planet[row][col] = Entity(prey=prey, coords=(row, col)) return def get_entities(self) -> list[Entity]: """ Returns a list of all the entities within the planet. >>> wt = WaTor(WIDTH, HEIGHT) >>> len(wt.get_entities()) == PREDATOR_INITIAL_COUNT + PREY_INITIAL_COUNT True """ return [entity for column in self.planet for entity in column if entity] def balance_predators_and_prey(self) -> None: """ Balances predators and preys so that prey can not dominate the predators, blocking up space for them to reproduce. >>> wt = WaTor(WIDTH, HEIGHT) >>> for i in range(2000): ... row, col = i // HEIGHT, i % WIDTH ... wt.planet[row][col] = Entity(True, coords=(row, col)) >>> entities = len(wt.get_entities()) >>> wt.balance_predators_and_prey() >>> len(wt.get_entities()) == entities False """ entities = self.get_entities() shuffle(entities) if len(entities) >= MAX_ENTITIES - MAX_ENTITIES / 10: prey = [entity for entity in entities if entity.prey] predators = [entity for entity in entities if not entity.prey] prey_count, predator_count = len(prey), len(predators) entities_to_purge = ( prey[:DELETE_UNBALANCED_ENTITIES] if prey_count > predator_count else predators[:DELETE_UNBALANCED_ENTITIES] ) for entity in entities_to_purge: self.planet[entity.coords[0]][entity.coords[1]] = None def get_surrounding_prey(self, entity: Entity) -> list[Entity]: """ Returns all the prey entities around (N, S, E, W) a predator entity. Subtly different to the `move_and_reproduce`. >>> wt = WaTor(WIDTH, HEIGHT) >>> wt.set_planet([ ... [None, Entity(True, (0, 1)), None], ... [None, Entity(False, (1, 1)), None], ... [None, Entity(True, (2, 1)), None]]) >>> wt.get_surrounding_prey( ... Entity(False, (1, 1))) # doctest: +NORMALIZE_WHITESPACE [Entity(prey=True, coords=(0, 1), remaining_reproduction_time=5), Entity(prey=True, coords=(2, 1), remaining_reproduction_time=5)] >>> wt.set_planet([[Entity(False, (0, 0))]]) >>> wt.get_surrounding_prey(Entity(False, (0, 0))) [] >>> wt.set_planet([ ... [Entity(True, (0, 0)), Entity(False, (1, 0)), Entity(False, (2, 0))], ... [None, Entity(False, (1, 1)), Entity(True, (2, 1))], ... [None, None, None]]) >>> wt.get_surrounding_prey(Entity(False, (1, 0))) [Entity(prey=True, coords=(0, 0), remaining_reproduction_time=5)] """ row, col = entity.coords adjacent: list[tuple[int, int]] = [ (row - 1, col), # North (row + 1, col), # South (row, col - 1), # West (row, col + 1), # East ] return [ ent for r, c in adjacent if 0 <= r < self.height and 0 <= c < self.width and (ent := self.planet[r][c]) is not None and ent.prey ] def move_and_reproduce( self, entity: Entity, direction_orders: list[Literal["N", "E", "S", "W"]] ) -> None: """ Attempts to move to an unoccupied neighbouring square in either of the four directions (North, South, East, West). If the move was successful and the `remaining_reproduction_time` is equal to 0, then a new prey or predator can also be created in the previous square. :param direction_orders: Ordered list (like priority queue) depicting order to attempt to move. Removes any systematic approach of checking neighbouring squares. >>> planet = [ ... [None, None, None], ... [None, Entity(True, coords=(1, 1)), None], ... [None, None, None] ... ] >>> wt = WaTor(WIDTH, HEIGHT) >>> wt.set_planet(planet) >>> wt.move_and_reproduce(Entity(True, coords=(1, 1)), direction_orders=["N"]) >>> wt.planet # doctest: +NORMALIZE_WHITESPACE [[None, Entity(prey=True, coords=(0, 1), remaining_reproduction_time=4), None], [None, None, None], [None, None, None]] >>> wt.planet[0][0] = Entity(True, coords=(0, 0)) >>> wt.move_and_reproduce(Entity(True, coords=(0, 1)), ... direction_orders=["N", "W", "E", "S"]) >>> wt.planet # doctest: +NORMALIZE_WHITESPACE [[Entity(prey=True, coords=(0, 0), remaining_reproduction_time=5), None, Entity(prey=True, coords=(0, 2), remaining_reproduction_time=4)], [None, None, None], [None, None, None]] >>> wt.planet[0][1] = wt.planet[0][2] >>> wt.planet[0][2] = None >>> wt.move_and_reproduce(Entity(True, coords=(0, 1)), ... direction_orders=["N", "W", "S", "E"]) >>> wt.planet # doctest: +NORMALIZE_WHITESPACE [[Entity(prey=True, coords=(0, 0), remaining_reproduction_time=5), None, None], [None, Entity(prey=True, coords=(1, 1), remaining_reproduction_time=4), None], [None, None, None]] >>> wt = WaTor(WIDTH, HEIGHT) >>> reproducable_entity = Entity(False, coords=(0, 1)) >>> reproducable_entity.remaining_reproduction_time = 0 >>> wt.planet = [[None, reproducable_entity]] >>> wt.move_and_reproduce(reproducable_entity, ... direction_orders=["N", "W", "S", "E"]) >>> wt.planet # doctest: +NORMALIZE_WHITESPACE [[Entity(prey=False, coords=(0, 0), remaining_reproduction_time=20, energy_value=15), Entity(prey=False, coords=(0, 1), remaining_reproduction_time=20, energy_value=15)]] """ row, col = coords = entity.coords adjacent_squares: dict[Literal["N", "E", "S", "W"], tuple[int, int]] = { "N": (row - 1, col), # North "S": (row + 1, col), # South "W": (row, col - 1), # West "E": (row, col + 1), # East } # Weight adjacent locations adjacent: list[tuple[int, int]] = [] for order in direction_orders: adjacent.append(adjacent_squares[order]) for r, c in adjacent: if ( 0 <= r < self.height and 0 <= c < self.width and self.planet[r][c] is None ): # Move entity to empty adjacent square self.planet[r][c] = entity self.planet[row][col] = None entity.coords = (r, c) break # (2.) See if it possible to reproduce in previous square if coords != entity.coords and entity.remaining_reproduction_time <= 0: # Check if the entities on the planet is less than the max limit if len(self.get_entities()) < MAX_ENTITIES: # Reproduce in previous square self.planet[row][col] = Entity(prey=entity.prey, coords=coords) entity.reset_reproduction_time() else: entity.remaining_reproduction_time -= 1 def perform_prey_actions( self, entity: Entity, direction_orders: list[Literal["N", "E", "S", "W"]] ) -> None: """ Performs the actions for a prey entity For prey the rules are: 1. At each chronon, a prey moves randomly to one of the adjacent unoccupied squares. If there are no free squares, no movement takes place. 2. Once a prey has survived a certain number of chronons it may reproduce. This is done as it moves to a neighbouring square, leaving behind a new prey in its old position. Its reproduction time is also reset to zero. >>> wt = WaTor(WIDTH, HEIGHT) >>> reproducable_entity = Entity(True, coords=(0, 1)) >>> reproducable_entity.remaining_reproduction_time = 0 >>> wt.planet = [[None, reproducable_entity]] >>> wt.perform_prey_actions(reproducable_entity, ... direction_orders=["N", "W", "S", "E"]) >>> wt.planet # doctest: +NORMALIZE_WHITESPACE [[Entity(prey=True, coords=(0, 0), remaining_reproduction_time=5), Entity(prey=True, coords=(0, 1), remaining_reproduction_time=5)]] """ self.move_and_reproduce(entity, direction_orders) def perform_predator_actions( self, entity: Entity, occupied_by_prey_coords: tuple[int, int] | None, direction_orders: list[Literal["N", "E", "S", "W"]], ) -> None: """ Performs the actions for a predator entity :param occupied_by_prey_coords: Move to this location if there is prey there For predators the rules are: 1. At each chronon, a predator moves randomly to an adjacent square occupied by a prey. If there is none, the predator moves to a random adjacent unoccupied square. If there are no free squares, no movement takes place. 2. At each chronon, each predator is deprived of a unit of energy. 3. Upon reaching zero energy, a predator dies. 4. If a predator moves to a square occupied by a prey, it eats the prey and earns a certain amount of energy. 5. Once a predator has survived a certain number of chronons it may reproduce in exactly the same way as the prey. >>> wt = WaTor(WIDTH, HEIGHT) >>> wt.set_planet([[Entity(True, coords=(0, 0)), Entity(False, coords=(0, 1))]]) >>> wt.perform_predator_actions(Entity(False, coords=(0, 1)), (0, 0), []) >>> wt.planet # doctest: +NORMALIZE_WHITESPACE [[Entity(prey=False, coords=(0, 0), remaining_reproduction_time=20, energy_value=19), None]] """ assert entity.energy_value is not None # [type checking] # (3.) If the entity has 0 energy, it will die if entity.energy_value == 0: self.planet[entity.coords[0]][entity.coords[1]] = None return # (1.) Move to entity if possible if occupied_by_prey_coords is not None: # Kill the prey prey = self.planet[occupied_by_prey_coords[0]][occupied_by_prey_coords[1]] assert prey is not None prey.alive = False # Move onto prey self.planet[occupied_by_prey_coords[0]][occupied_by_prey_coords[1]] = entity self.planet[entity.coords[0]][entity.coords[1]] = None entity.coords = occupied_by_prey_coords # (4.) Eats the prey and earns energy entity.energy_value += PREDATOR_FOOD_VALUE else: # (5.) If it has survived the certain number of chronons it will also # reproduce in this function self.move_and_reproduce(entity, direction_orders) # (2.) Each chronon, the predator is deprived of a unit of energy entity.energy_value -= 1 def run(self, *, iteration_count: int) -> None: """ Emulate time passing by looping `iteration_count` times >>> wt = WaTor(WIDTH, HEIGHT) >>> wt.run(iteration_count=PREDATOR_INITIAL_ENERGY_VALUE - 1) >>> len(list(filter(lambda entity: entity.prey is False, ... wt.get_entities()))) >= PREDATOR_INITIAL_COUNT True """ for iter_num in range(iteration_count): # Generate list of all entities in order to randomly # pop an entity at a time to simulate true randomness # This removes the systematic approach of iterating # through each entity width by height all_entities = self.get_entities() for __ in range(len(all_entities)): entity = all_entities.pop(randint(0, len(all_entities) - 1)) if entity.alive is False: continue directions: list[Literal["N", "E", "S", "W"]] = ["N", "E", "S", "W"] shuffle(directions) # Randomly shuffle directions if entity.prey: self.perform_prey_actions(entity, directions) else: # Create list of surrounding prey surrounding_prey = self.get_surrounding_prey(entity) surrounding_prey_coords = None if surrounding_prey: # Again, randomly shuffle directions shuffle(surrounding_prey) surrounding_prey_coords = surrounding_prey[0].coords self.perform_predator_actions( entity, surrounding_prey_coords, directions ) # Balance out the predators and prey self.balance_predators_and_prey() if self.time_passed is not None: # Call time_passed function for Wa-Tor planet # visualisation in a terminal or a graph. self.time_passed(self, iter_num) def visualise(wt: WaTor, iter_number: int, *, colour: bool = True) -> None: """ Visually displays the Wa-Tor planet using an ascii code in terminal to clear and re-print the Wa-Tor planet at intervals. Uses ascii colour codes to colourfully display the predators and prey: * (0x60f197) Prey = ``#`` * (0xfffff) Predator = ``x`` >>> wt = WaTor(30, 30) >>> wt.set_planet([ ... [Entity(True, coords=(0, 0)), Entity(False, coords=(0, 1)), None], ... [Entity(False, coords=(1, 0)), None, Entity(False, coords=(1, 2))], ... [None, Entity(True, coords=(2, 1)), None] ... ]) >>> visualise(wt, 0, colour=False) # doctest: +NORMALIZE_WHITESPACE # x . x . x . # . <BLANKLINE> Iteration: 0 | Prey count: 2 | Predator count: 3 | """ if colour: __import__("os").system("") print("\x1b[0;0H\x1b[2J\x1b[?25l") reprint = "\x1b[0;0H" if colour else "" ansi_colour_end = "\x1b[0m " if colour else " " planet = wt.planet output = "" # Iterate over every entity in the planet for row in planet: for entity in row: if entity is None: output += " . " else: if colour is True: output += ( "\x1b[38;2;96;241;151m" if entity.prey else "\x1b[38;2;255;255;15m" ) output += f" {'#' if entity.prey else 'x'}{ansi_colour_end}" output += "\n" entities = wt.get_entities() prey_count = sum(entity.prey for entity in entities) print( f"{output}\n Iteration: {iter_number} | Prey count: {prey_count} | " f"Predator count: {len(entities) - prey_count} | {reprint}" ) # Block the thread to be able to visualise seeing the algorithm sleep(0.05) if __name__ == "__main__": import doctest doctest.testmod() wt = WaTor(WIDTH, HEIGHT) wt.time_passed = visualise wt.run(iteration_count=100_000)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/cellular_automata/game_of_life.py
cellular_automata/game_of_life.py
"""Conway's Game Of Life, Author Anurag Kumar(mailto:anuragkumarak95@gmail.com) Requirements: - numpy - random - time - matplotlib Python: - 3.5 Usage: - $python3 game_of_life <canvas_size:int> Game-Of-Life Rules: 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. 2. Any live cell with two or three live neighbours lives on to the next generation. 3. Any live cell with more than three live neighbours dies, as if by over-population. 4. Any dead cell with exactly three live neighbours be- comes a live cell, as if by reproduction. """ import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap usage_doc = "Usage of script: script_name <size_of_canvas:int>" choice = [0] * 100 + [1] * 10 random.shuffle(choice) def create_canvas(size: int) -> list[list[bool]]: canvas = [[False for i in range(size)] for j in range(size)] return canvas def seed(canvas: list[list[bool]]) -> None: for i, row in enumerate(canvas): for j, _ in enumerate(row): canvas[i][j] = bool(random.getrandbits(1)) def run(canvas: list[list[bool]]) -> list[list[bool]]: """ This function runs the rules of game through all points, and changes their status accordingly.(in the same canvas) @Args: -- canvas : canvas of population to run the rules on. @returns: -- canvas of population after one step """ current_canvas = np.array(canvas) next_gen_canvas = np.array(create_canvas(current_canvas.shape[0])) for r, row in enumerate(current_canvas): for c, pt in enumerate(row): next_gen_canvas[r][c] = __judge_point( pt, current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) return next_gen_canvas.tolist() def __judge_point(pt: bool, neighbours: list[list[bool]]) -> bool: dead = 0 alive = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. state = pt if pt: if alive < 2: state = False elif alive in {2, 3}: state = True elif alive > 3: state = False elif alive == 3: state = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) canvas_size = int(sys.argv[1]) # main working structure of this module. c = create_canvas(canvas_size) seed(c) fig, ax = plt.subplots() fig.show() cmap = ListedColormap(["w", "k"]) try: while True: c = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/cellular_automata/langtons_ant.py
cellular_automata/langtons_ant.py
""" Langton's ant @ https://en.wikipedia.org/wiki/Langton%27s_ant @ https://upload.wikimedia.org/wikipedia/commons/0/09/LangtonsAntAnimated.gif """ from functools import partial from matplotlib import pyplot as plt from matplotlib.animation import FuncAnimation WIDTH = 80 HEIGHT = 80 class LangtonsAnt: """ Represents the main LangonsAnt algorithm. >>> la = LangtonsAnt(2, 2) >>> la.board [[True, True], [True, True]] >>> la.ant_position (1, 1) """ def __init__(self, width: int, height: int) -> None: # Each square is either True or False where True is white and False is black self.board = [[True] * width for _ in range(height)] self.ant_position: tuple[int, int] = (width // 2, height // 2) # Initially pointing left (similar to the wikipedia image) # (0 = 0° | 1 = 90° | 2 = 180 ° | 3 = 270°) self.ant_direction: int = 3 def move_ant(self, axes: plt.Axes | None, display: bool, _frame: int) -> None: """ Performs three tasks: 1. The ant turns either clockwise or anti-clockwise according to the colour of the square that it is currently on. If the square is white, the ant turns clockwise, and if the square is black the ant turns anti-clockwise 2. The ant moves one square in the direction that it is currently facing 3. The square the ant was previously on is inverted (White -> Black and Black -> White) If display is True, the board will also be displayed on the axes >>> la = LangtonsAnt(2, 2) >>> la.move_ant(None, True, 0) >>> la.board [[True, True], [True, False]] >>> la.move_ant(None, True, 0) >>> la.board [[True, False], [True, False]] """ directions = { 0: (-1, 0), # 0° 1: (0, 1), # 90° 2: (1, 0), # 180° 3: (0, -1), # 270° } x, y = self.ant_position # Turn clockwise or anti-clockwise according to colour of square if self.board[x][y] is True: # The square is white so turn 90° clockwise self.ant_direction = (self.ant_direction + 1) % 4 else: # The square is black so turn 90° anti-clockwise self.ant_direction = (self.ant_direction - 1) % 4 # Move ant move_x, move_y = directions[self.ant_direction] self.ant_position = (x + move_x, y + move_y) # Flip colour of square self.board[x][y] = not self.board[x][y] if display and axes: # Display the board on the axes axes.get_xaxis().set_ticks([]) axes.get_yaxis().set_ticks([]) axes.imshow(self.board, cmap="gray", interpolation="nearest") def display(self, frames: int = 100_000) -> None: """ Displays the board without delay in a matplotlib plot to visually understand and track the ant. >>> _ = LangtonsAnt(WIDTH, HEIGHT) """ fig, ax = plt.subplots() # Assign animation to a variable to prevent it from getting garbage collected self.animation = FuncAnimation( fig, partial(self.move_ant, ax, True), frames=frames, interval=1 ) plt.show() if __name__ == "__main__": import doctest doctest.testmod() LangtonsAnt(WIDTH, HEIGHT).display()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/cellular_automata/conways_game_of_life.py
cellular_automata/conways_game_of_life.py
""" Conway's Game of Life implemented in Python. https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life """ from __future__ import annotations from PIL import Image # Define glider example GLIDER = [ [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], ] # Define blinker example BLINKER = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def new_generation(cells: list[list[int]]) -> list[list[int]]: """ Generates the next generation for a given state of Conway's Game of Life. >>> new_generation(BLINKER) [[0, 0, 0], [1, 1, 1], [0, 0, 0]] """ next_generation = [] for i in range(len(cells)): next_generation_row = [] for j in range(len(cells[i])): # Get the number of live neighbours neighbour_count = 0 if i > 0 and j > 0: neighbour_count += cells[i - 1][j - 1] if i > 0: neighbour_count += cells[i - 1][j] if i > 0 and j < len(cells[i]) - 1: neighbour_count += cells[i - 1][j + 1] if j > 0: neighbour_count += cells[i][j - 1] if j < len(cells[i]) - 1: neighbour_count += cells[i][j + 1] if i < len(cells) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(cells) - 1: neighbour_count += cells[i + 1][j] if i < len(cells) - 1 and j < len(cells[i]) - 1: neighbour_count += cells[i + 1][j + 1] # Rules of the game of life (excerpt from Wikipedia): # 1. Any live cell with two or three live neighbours survives. # 2. Any dead cell with three live neighbours becomes a live cell. # 3. All other live cells die in the next generation. # Similarly, all other dead cells stay dead. alive = cells[i][j] == 1 if (alive and 2 <= neighbour_count <= 3) or ( not alive and neighbour_count == 3 ): next_generation_row.append(1) else: next_generation_row.append(0) next_generation.append(next_generation_row) return next_generation def generate_images(cells: list[list[int]], frames: int) -> list[Image.Image]: """ Generates a list of images of subsequent Game of Life states. """ images = [] for _ in range(frames): # Create output image img = Image.new("RGB", (len(cells[0]), len(cells))) pixels = img.load() # Save cells to image for x in range(len(cells)): for y in range(len(cells[0])): colour = 255 - cells[y][x] * 255 pixels[x, y] = (colour, colour, colour) # Save image images.append(img) cells = new_generation(cells) return images if __name__ == "__main__": images = generate_images(GLIDER, 16) images[0].save("out.gif", save_all=True, append_images=images[1:])
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/cellular_automata/nagel_schrekenberg.py
cellular_automata/nagel_schrekenberg.py
""" Simulate the evolution of a highway with only one road that is a loop. The highway is divided in cells, each cell can have at most one car in it. The highway is a loop so when a car comes to one end, it will come out on the other. Each car is represented by its speed (from 0 to 5). Some information about speed: -1 means that the cell on the highway is empty 0 to 5 are the speed of the cars with 0 being the lowest and 5 the highest highway: list[int] Where every position and speed of every car will be stored probability The probability that a driver will slow down initial_speed The speed of the cars a the start frequency How many cells there are between two cars at the start max_speed The maximum speed a car can go to number_of_cells How many cell are there in the highway number_of_update How many times will the position be updated More information here: https://en.wikipedia.org/wiki/Nagel%E2%80%93Schreckenberg_model Examples for doctest: >>> simulate(construct_highway(6, 3, 0), 2, 0, 2) [[0, -1, -1, 0, -1, -1], [-1, 1, -1, -1, 1, -1], [-1, -1, 1, -1, -1, 1]] >>> simulate(construct_highway(5, 2, -2), 3, 0, 2) [[0, -1, 0, -1, 0], [0, -1, 0, -1, -1], [0, -1, -1, 1, -1], [-1, 1, -1, 0, -1]] """ from random import randint, random def construct_highway( number_of_cells: int, frequency: int, initial_speed: int, random_frequency: bool = False, random_speed: bool = False, max_speed: int = 5, ) -> list: """ Build the highway following the parameters given >>> construct_highway(10, 2, 6) [[6, -1, 6, -1, 6, -1, 6, -1, 6, -1]] >>> construct_highway(10, 10, 2) [[2, -1, -1, -1, -1, -1, -1, -1, -1, -1]] """ highway = [[-1] * number_of_cells] # Create a highway without any car i = 0 initial_speed = max(initial_speed, 0) while i < number_of_cells: highway[0][i] = ( randint(0, max_speed) if random_speed else initial_speed ) # Place the cars i += ( randint(1, max_speed * 2) if random_frequency else frequency ) # Arbitrary number, may need tuning return highway def get_distance(highway_now: list, car_index: int) -> int: """ Get the distance between a car (at index car_index) and the next car >>> get_distance([6, -1, 6, -1, 6], 2) 1 >>> get_distance([2, -1, -1, -1, 3, 1, 0, 1, 3, 2], 0) 3 >>> get_distance([-1, -1, -1, -1, 2, -1, -1, -1, 3], -1) 4 """ distance = 0 cells = highway_now[car_index + 1 :] for cell in range(len(cells)): # May need a better name for this if cells[cell] != -1: # If the cell is not empty then return distance # we have the distance we wanted distance += 1 # Here if the car is near the end of the highway return distance + get_distance(highway_now, -1) def update(highway_now: list, probability: float, max_speed: int) -> list: """ Update the speed of the cars >>> update([-1, -1, -1, -1, -1, 2, -1, -1, -1, -1, 3], 0.0, 5) [-1, -1, -1, -1, -1, 3, -1, -1, -1, -1, 4] >>> update([-1, -1, 2, -1, -1, -1, -1, 3], 0.0, 5) [-1, -1, 3, -1, -1, -1, -1, 1] """ number_of_cells = len(highway_now) # Beforce calculations, the highway is empty next_highway = [-1] * number_of_cells for car_index in range(number_of_cells): if highway_now[car_index] != -1: # Add 1 to the current speed of the car and cap the speed next_highway[car_index] = min(highway_now[car_index] + 1, max_speed) # Number of empty cell before the next car dn = get_distance(highway_now, car_index) - 1 # We can't have the car causing an accident next_highway[car_index] = min(next_highway[car_index], dn) if random() < probability: # Randomly, a driver will slow down next_highway[car_index] = max(next_highway[car_index] - 1, 0) return next_highway def simulate( highway: list, number_of_update: int, probability: float, max_speed: int ) -> list: """ The main function, it will simulate the evolution of the highway >>> simulate([[-1, 2, -1, -1, -1, 3]], 2, 0.0, 3) [[-1, 2, -1, -1, -1, 3], [-1, -1, -1, 2, -1, 0], [1, -1, -1, 0, -1, -1]] >>> simulate([[-1, 2, -1, 3]], 4, 0.0, 3) [[-1, 2, -1, 3], [-1, 0, -1, 0], [-1, 0, -1, 0], [-1, 0, -1, 0], [-1, 0, -1, 0]] """ number_of_cells = len(highway[0]) for i in range(number_of_update): next_speeds_calculated = update(highway[i], probability, max_speed) real_next_speeds = [-1] * number_of_cells for car_index in range(number_of_cells): speed = next_speeds_calculated[car_index] if speed != -1: # Change the position based on the speed (with % to create the loop) index = (car_index + speed) % number_of_cells # Commit the change of position real_next_speeds[index] = speed highway.append(real_next_speeds) return highway 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/cellular_automata/__init__.py
cellular_automata/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/cellular_automata/one_dimensional.py
cellular_automata/one_dimensional.py
""" Return an image of 16 generations of one-dimensional cellular automata based on a given ruleset number https://mathworld.wolfram.com/ElementaryCellularAutomaton.html """ from __future__ import annotations from PIL import Image # Define the first generation of cells # fmt: off CELLS = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] # fmt: on def format_ruleset(ruleset: int) -> list[int]: """ >>> format_ruleset(11100) [0, 0, 0, 1, 1, 1, 0, 0] >>> format_ruleset(0) [0, 0, 0, 0, 0, 0, 0, 0] >>> format_ruleset(11111111) [1, 1, 1, 1, 1, 1, 1, 1] """ return [int(c) for c in f"{ruleset:08}"[:8]] def new_generation(cells: list[list[int]], rule: list[int], time: int) -> list[int]: population = len(cells[0]) # 31 next_generation = [] for i in range(population): # Get the neighbors of each cell # Handle neighbours outside bounds by using 0 as their value left_neighbor = 0 if i == 0 else cells[time][i - 1] right_neighbor = 0 if i == population - 1 else cells[time][i + 1] # Define a new cell and add it to the new generation situation = 7 - int(f"{left_neighbor}{cells[time][i]}{right_neighbor}", 2) next_generation.append(rule[situation]) return next_generation def generate_image(cells: list[list[int]]) -> Image.Image: """ Convert the cells into a greyscale PIL.Image.Image and return it to the caller. >>> from random import random >>> cells = [[random() for w in range(31)] for h in range(16)] >>> img = generate_image(cells) >>> isinstance(img, Image.Image) True >>> img.width, img.height (31, 16) """ # Create the output image img = Image.new("RGB", (len(cells[0]), len(cells))) pixels = img.load() # Generates image for w in range(img.width): for h in range(img.height): color = 255 - int(255 * cells[h][w]) pixels[w, h] = (color, color, color) return img if __name__ == "__main__": rule_num = bin(int(input("Rule:\n").strip()))[2:] rule = format_ruleset(int(rule_num)) for time in range(16): CELLS.append(new_generation(CELLS, rule, time)) img = generate_image(CELLS) # Uncomment to save the image # img.save(f"rule_{rule_num}.png") img.show()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/scheduling/job_sequencing_with_deadline.py
scheduling/job_sequencing_with_deadline.py
def job_sequencing_with_deadlines(jobs: list) -> list: """ Function to find the maximum profit by doing jobs in a given time frame Args: jobs [list]: A list of tuples of (job_id, deadline, profit) Returns: max_profit [int]: Maximum profit that can be earned by doing jobs in a given time frame Examples: >>> job_sequencing_with_deadlines( ... [(1, 4, 20), (2, 1, 10), (3, 1, 40), (4, 1, 30)]) [2, 60] >>> job_sequencing_with_deadlines( ... [(1, 2, 100), (2, 1, 19), (3, 2, 27), (4, 1, 25), (5, 1, 15)]) [2, 127] """ # Sort the jobs in descending order of profit jobs = sorted(jobs, key=lambda value: value[2], reverse=True) # Create a list of size equal to the maximum deadline # and initialize it with -1 max_deadline = max(jobs, key=lambda value: value[1])[1] time_slots = [-1] * max_deadline # Finding the maximum profit and the count of jobs count = 0 max_profit = 0 for job in jobs: # Find a free time slot for this job # (Note that we start from the last possible slot) for i in range(job[1] - 1, -1, -1): if time_slots[i] == -1: time_slots[i] = job[0] count += 1 max_profit += job[2] break return [count, max_profit] if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false