text stringlengths 2 4.68M | id stringlengths 14 185 | metadata dict | __index_level_0__ int64 0 1.49k |
|---|---|---|---|
from __future__ import annotations
class IIRFilter:
r"""
N-Order IIR filter
Assumes working with float samples normalized on [-1, 1]
---
Implementation details:
Based on the 2nd-order function from
https://en.wikipedia.org/wiki/Digital_biquad_filter,
this generalized N-order function was made.
Using the following transfer function
H(z)=\frac{b_{0}+b_{1}z^{-1}+b_{2}z^{-2}+...+b_{k}z^{-k}}{a_{0}+a_{1}z^{-1}+a_{2}z^{-2}+...+a_{k}z^{-k}}
we can rewrite this to
y[n]={\frac{1}{a_{0}}}\left(\left(b_{0}x[n]+b_{1}x[n-1]+b_{2}x[n-2]+...+b_{k}x[n-k]\right)-\left(a_{1}y[n-1]+a_{2}y[n-2]+...+a_{k}y[n-k]\right)\right)
"""
def __init__(self, order: int) -> None:
self.order = order
# a_{0} ... a_{k}
self.a_coeffs = [1.0] + [0.0] * order
# b_{0} ... b_{k}
self.b_coeffs = [1.0] + [0.0] * order
# x[n-1] ... x[n-k]
self.input_history = [0.0] * self.order
# y[n-1] ... y[n-k]
self.output_history = [0.0] * self.order
def set_coefficients(self, a_coeffs: list[float], b_coeffs: list[float]) -> None:
"""
Set the coefficients for the IIR filter. These should both be of size order + 1.
a_0 may be left out, and it will use 1.0 as default value.
This method works well with scipy's filter design functions
>>> # Make a 2nd-order 1000Hz butterworth lowpass filter
>>> import scipy.signal
>>> b_coeffs, a_coeffs = scipy.signal.butter(2, 1000,
... btype='lowpass',
... fs=48000)
>>> filt = IIRFilter(2)
>>> filt.set_coefficients(a_coeffs, b_coeffs)
"""
if len(a_coeffs) < self.order:
a_coeffs = [1.0, *a_coeffs]
if len(a_coeffs) != self.order + 1:
msg = (
f"Expected a_coeffs to have {self.order + 1} elements "
f"for {self.order}-order filter, got {len(a_coeffs)}"
)
raise ValueError(msg)
if len(b_coeffs) != self.order + 1:
msg = (
f"Expected b_coeffs to have {self.order + 1} elements "
f"for {self.order}-order filter, got {len(a_coeffs)}"
)
raise ValueError(msg)
self.a_coeffs = a_coeffs
self.b_coeffs = b_coeffs
def process(self, sample: float) -> float:
"""
Calculate y[n]
>>> filt = IIRFilter(2)
>>> filt.process(0)
0.0
"""
result = 0.0
# Start at index 1 and do index 0 at the end.
for i in range(1, self.order + 1):
result += (
self.b_coeffs[i] * self.input_history[i - 1]
- self.a_coeffs[i] * self.output_history[i - 1]
)
result = (result + self.b_coeffs[0] * sample) / self.a_coeffs[0]
self.input_history[1:] = self.input_history[:-1]
self.output_history[1:] = self.output_history[:-1]
self.input_history[0] = sample
self.output_history[0] = result
return result
| Python/audio_filters/iir_filter.py/0 | {
"file_path": "Python/audio_filters/iir_filter.py",
"repo_id": "Python",
"token_count": 1692
} | 0 |
"""
The nqueens problem is of placing N queens on a N * N
chess board such that no queen can attack any other queens placed
on that chess board.
This means that one queen cannot have any other queen on its horizontal, vertical and
diagonal lines.
"""
from __future__ import annotations
solution = []
def is_safe(board: list[list[int]], row: int, column: int) -> bool:
"""
This function returns a boolean value True if it is safe to place a queen there
considering the current state of the board.
Parameters:
board (2D matrix): The chessboard
row, column: Coordinates of the cell on the board
Returns:
Boolean Value
>>> is_safe([[0, 0, 0], [0, 0, 0], [0, 0, 0]], 1, 1)
True
>>> is_safe([[1, 0, 0], [0, 0, 0], [0, 0, 0]], 1, 1)
False
"""
n = len(board) # Size of the board
# Check if there is any queen in the same row, column,
# left upper diagonal, and right upper diagonal
return (
all(board[i][j] != 1 for i, j in zip(range(row, -1, -1), range(column, n)))
and all(
board[i][j] != 1 for i, j in zip(range(row, -1, -1), range(column, -1, -1))
)
and all(board[i][j] != 1 for i, j in zip(range(row, n), range(column, n)))
and all(board[i][j] != 1 for i, j in zip(range(row, n), range(column, -1, -1)))
)
def solve(board: list[list[int]], row: int) -> bool:
"""
This function creates a state space tree and calls the safe function until it
receives a False Boolean and terminates that branch and backtracks to the next
possible solution branch.
"""
if row >= len(board):
"""
If the row number exceeds N, we have a board with a successful combination
and that combination is appended to the solution list and the board is printed.
"""
solution.append(board)
printboard(board)
print()
return True
for i in range(len(board)):
"""
For every row, it iterates through each column to check if it is feasible to
place a queen there.
If all the combinations for that particular branch are successful, the board is
reinitialized for the next possible combination.
"""
if is_safe(board, row, i):
board[row][i] = 1
solve(board, row + 1)
board[row][i] = 0
return False
def printboard(board: list[list[int]]) -> None:
"""
Prints the boards that have a successful combination.
"""
for i in range(len(board)):
for j in range(len(board)):
if board[i][j] == 1:
print("Q", end=" ") # Queen is present
else:
print(".", end=" ") # Empty cell
print()
# Number of queens (e.g., n=8 for an 8x8 board)
n = 8
board = [[0 for i in range(n)] for j in range(n)]
solve(board, 0)
print("The total number of solutions are:", len(solution))
| Python/backtracking/n_queens.py/0 | {
"file_path": "Python/backtracking/n_queens.py",
"repo_id": "Python",
"token_count": 1156
} | 1 |
# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm
def binary_xor(a: int, b: int) -> str:
"""
Take in 2 integers, convert them to binary,
return a binary number that is the
result of a binary xor operation on the integers provided.
>>> binary_xor(25, 32)
'0b111001'
>>> binary_xor(37, 50)
'0b010111'
>>> binary_xor(21, 30)
'0b01011'
>>> binary_xor(58, 73)
'0b1110011'
>>> binary_xor(0, 255)
'0b11111111'
>>> binary_xor(256, 256)
'0b000000000'
>>> binary_xor(0, -1)
Traceback (most recent call last):
...
ValueError: the value of both inputs must be positive
>>> binary_xor(0, 1.1)
Traceback (most recent call last):
...
TypeError: 'float' object cannot be interpreted as an integer
>>> binary_xor("0", "1")
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
"""
if a < 0 or b < 0:
raise ValueError("the value of both inputs must be positive")
a_binary = str(bin(a))[2:] # remove the leading "0b"
b_binary = str(bin(b))[2:] # remove the leading "0b"
max_len = max(len(a_binary), len(b_binary))
return "0b" + "".join(
str(int(char_a != char_b))
for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len))
)
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python/bit_manipulation/binary_xor_operator.py/0 | {
"file_path": "Python/bit_manipulation/binary_xor_operator.py",
"repo_id": "Python",
"token_count": 621
} | 2 |
#!/usr/bin/env python3
"""Provide the functionality to manipulate a single bit."""
def set_bit(number: int, position: int) -> int:
"""
Set the bit at position to 1.
Details: perform bitwise or for given number and X.
Where X is a number with all the bits โ zeroes and bit on given
position โ one.
>>> set_bit(0b1101, 1) # 0b1111
15
>>> set_bit(0b0, 5) # 0b100000
32
>>> set_bit(0b1111, 1) # 0b1111
15
"""
return number | (1 << position)
def clear_bit(number: int, position: int) -> int:
"""
Set the bit at position to 0.
Details: perform bitwise and for given number and X.
Where X is a number with all the bits โ ones and bit on given
position โ zero.
>>> clear_bit(0b10010, 1) # 0b10000
16
>>> clear_bit(0b0, 5) # 0b0
0
"""
return number & ~(1 << position)
def flip_bit(number: int, position: int) -> int:
"""
Flip the bit at position.
Details: perform bitwise xor for given number and X.
Where X is a number with all the bits โ zeroes and bit on given
position โ one.
>>> flip_bit(0b101, 1) # 0b111
7
>>> flip_bit(0b101, 0) # 0b100
4
"""
return number ^ (1 << position)
def is_bit_set(number: int, position: int) -> bool:
"""
Is the bit at position set?
Details: Shift the bit at position to be the first (smallest) bit.
Then check if the first bit is set by anding the shifted number with 1.
>>> is_bit_set(0b1010, 0)
False
>>> is_bit_set(0b1010, 1)
True
>>> is_bit_set(0b1010, 2)
False
>>> is_bit_set(0b1010, 3)
True
>>> is_bit_set(0b0, 17)
False
"""
return ((number >> position) & 1) == 1
def get_bit(number: int, position: int) -> int:
"""
Get the bit at the given position
Details: perform bitwise and for the given number and X,
Where X is a number with all the bits โ zeroes and bit on given position โ one.
If the result is not equal to 0, then the bit on the given position is 1, else 0.
>>> get_bit(0b1010, 0)
0
>>> get_bit(0b1010, 1)
1
>>> get_bit(0b1010, 2)
0
>>> get_bit(0b1010, 3)
1
"""
return int((number & (1 << position)) != 0)
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python/bit_manipulation/single_bit_manipulation_operations.py/0 | {
"file_path": "Python/bit_manipulation/single_bit_manipulation_operations.py",
"repo_id": "Python",
"token_count": 933
} | 3 |
from __future__ import annotations
from collections.abc import Sequence
from typing import Literal
def compare_string(string1: str, string2: str) -> str | Literal[False]:
"""
>>> compare_string('0010','0110')
'0_10'
>>> compare_string('0110','1101')
False
"""
list1 = list(string1)
list2 = list(string2)
count = 0
for i in range(len(list1)):
if list1[i] != list2[i]:
count += 1
list1[i] = "_"
if count > 1:
return False
else:
return "".join(list1)
def check(binary: list[str]) -> list[str]:
"""
>>> check(['0.00.01.5'])
['0.00.01.5']
"""
pi = []
while True:
check1 = ["$"] * len(binary)
temp = []
for i in range(len(binary)):
for j in range(i + 1, len(binary)):
k = compare_string(binary[i], binary[j])
if k is False:
check1[i] = "*"
check1[j] = "*"
temp.append("X")
for i in range(len(binary)):
if check1[i] == "$":
pi.append(binary[i])
if len(temp) == 0:
return pi
binary = list(set(temp))
def decimal_to_binary(no_of_variable: int, minterms: Sequence[float]) -> list[str]:
"""
>>> decimal_to_binary(3,[1.5])
['0.00.01.5']
"""
temp = []
for minterm in minterms:
string = ""
for _ in range(no_of_variable):
string = str(minterm % 2) + string
minterm //= 2
temp.append(string)
return temp
def is_for_table(string1: str, string2: str, count: int) -> bool:
"""
>>> is_for_table('__1','011',2)
True
>>> is_for_table('01_','001',1)
False
"""
list1 = list(string1)
list2 = list(string2)
count_n = sum(item1 != item2 for item1, item2 in zip(list1, list2))
return count_n == count
def selection(chart: list[list[int]], prime_implicants: list[str]) -> list[str]:
"""
>>> selection([[1]],['0.00.01.5'])
['0.00.01.5']
>>> selection([[1]],['0.00.01.5'])
['0.00.01.5']
"""
temp = []
select = [0] * len(chart)
for i in range(len(chart[0])):
count = sum(row[i] == 1 for row in chart)
if count == 1:
rem = max(j for j, row in enumerate(chart) if row[i] == 1)
select[rem] = 1
for i, item in enumerate(select):
if item != 1:
continue
for j in range(len(chart[0])):
if chart[i][j] != 1:
continue
for row in chart:
row[j] = 0
temp.append(prime_implicants[i])
while True:
counts = [chart[i].count(1) for i in range(len(chart))]
max_n = max(counts)
rem = counts.index(max_n)
if max_n == 0:
return temp
temp.append(prime_implicants[rem])
for j in range(len(chart[0])):
if chart[rem][j] != 1:
continue
for i in range(len(chart)):
chart[i][j] = 0
def prime_implicant_chart(
prime_implicants: list[str], binary: list[str]
) -> list[list[int]]:
"""
>>> prime_implicant_chart(['0.00.01.5'],['0.00.01.5'])
[[1]]
"""
chart = [[0 for x in range(len(binary))] for x in range(len(prime_implicants))]
for i in range(len(prime_implicants)):
count = prime_implicants[i].count("_")
for j in range(len(binary)):
if is_for_table(prime_implicants[i], binary[j], count):
chart[i][j] = 1
return chart
def main() -> None:
no_of_variable = int(input("Enter the no. of variables\n"))
minterms = [
float(x)
for x in input(
"Enter the decimal representation of Minterms 'Spaces Separated'\n"
).split()
]
binary = decimal_to_binary(no_of_variable, minterms)
prime_implicants = check(binary)
print("Prime Implicants are:")
print(prime_implicants)
chart = prime_implicant_chart(prime_implicants, binary)
essential_prime_implicants = selection(chart, prime_implicants)
print("Essential Prime Implicants are:")
print(essential_prime_implicants)
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| Python/boolean_algebra/quine_mc_cluskey.py/0 | {
"file_path": "Python/boolean_algebra/quine_mc_cluskey.py",
"repo_id": "Python",
"token_count": 2090
} | 4 |
"""
https://en.wikipedia.org/wiki/Autokey_cipher
An autokey cipher (also known as the autoclave cipher) is a cipher that
incorporates the message (the plaintext) into the key.
The key is generated from the message in some automated fashion,
sometimes by selecting certain letters from the text or, more commonly,
by adding a short primer key to the front of the message.
"""
def encrypt(plaintext: str, key: str) -> str:
"""
Encrypt a given plaintext (string) and key (string), returning the
encrypted ciphertext.
>>> encrypt("hello world", "coffee")
'jsqqs avvwo'
>>> encrypt("coffee is good as python", "TheAlgorithms")
'vvjfpk wj ohvp su ddylsv'
>>> encrypt("coffee is good as python", 2)
Traceback (most recent call last):
...
TypeError: key must be a string
>>> encrypt("", "TheAlgorithms")
Traceback (most recent call last):
...
ValueError: plaintext is empty
"""
if not isinstance(plaintext, str):
raise TypeError("plaintext must be a string")
if not isinstance(key, str):
raise TypeError("key must be a string")
if not plaintext:
raise ValueError("plaintext is empty")
if not key:
raise ValueError("key is empty")
key += plaintext
plaintext = plaintext.lower()
key = key.lower()
plaintext_iterator = 0
key_iterator = 0
ciphertext = ""
while plaintext_iterator < len(plaintext):
if (
ord(plaintext[plaintext_iterator]) < 97
or ord(plaintext[plaintext_iterator]) > 122
):
ciphertext += plaintext[plaintext_iterator]
plaintext_iterator += 1
elif ord(key[key_iterator]) < 97 or ord(key[key_iterator]) > 122:
key_iterator += 1
else:
ciphertext += chr(
(
(ord(plaintext[plaintext_iterator]) - 97 + ord(key[key_iterator]))
- 97
)
% 26
+ 97
)
key_iterator += 1
plaintext_iterator += 1
return ciphertext
def decrypt(ciphertext: str, key: str) -> str:
"""
Decrypt a given ciphertext (string) and key (string), returning the decrypted
ciphertext.
>>> decrypt("jsqqs avvwo", "coffee")
'hello world'
>>> decrypt("vvjfpk wj ohvp su ddylsv", "TheAlgorithms")
'coffee is good as python'
>>> decrypt("vvjfpk wj ohvp su ddylsv", "")
Traceback (most recent call last):
...
ValueError: key is empty
>>> decrypt(527.26, "TheAlgorithms")
Traceback (most recent call last):
...
TypeError: ciphertext must be a string
"""
if not isinstance(ciphertext, str):
raise TypeError("ciphertext must be a string")
if not isinstance(key, str):
raise TypeError("key must be a string")
if not ciphertext:
raise ValueError("ciphertext is empty")
if not key:
raise ValueError("key is empty")
key = key.lower()
ciphertext_iterator = 0
key_iterator = 0
plaintext = ""
while ciphertext_iterator < len(ciphertext):
if (
ord(ciphertext[ciphertext_iterator]) < 97
or ord(ciphertext[ciphertext_iterator]) > 122
):
plaintext += ciphertext[ciphertext_iterator]
else:
plaintext += chr(
(ord(ciphertext[ciphertext_iterator]) - ord(key[key_iterator])) % 26
+ 97
)
key += chr(
(ord(ciphertext[ciphertext_iterator]) - ord(key[key_iterator])) % 26
+ 97
)
key_iterator += 1
ciphertext_iterator += 1
return plaintext
if __name__ == "__main__":
import doctest
doctest.testmod()
operation = int(input("Type 1 to encrypt or 2 to decrypt:"))
if operation == 1:
plaintext = input("Typeplaintext to be encrypted:\n")
key = input("Type the key:\n")
print(encrypt(plaintext, key))
elif operation == 2:
ciphertext = input("Type the ciphertext to be decrypted:\n")
key = input("Type the key:\n")
print(decrypt(ciphertext, key))
decrypt("jsqqs avvwo", "coffee")
| Python/ciphers/autokey.py/0 | {
"file_path": "Python/ciphers/autokey.py",
"repo_id": "Python",
"token_count": 1796
} | 5 |
"""
Wikipedia: https://en.wikipedia.org/wiki/Enigma_machine
Video explanation: https://youtu.be/QwQVMqfoB2E
Also check out Numberphile's and Computerphile's videos on this topic
This module contains function 'enigma' which emulates
the famous Enigma machine from WWII.
Module includes:
- enigma function
- showcase of function usage
- 9 randomly generated rotors
- reflector (aka static rotor)
- original alphabet
Created by TrapinchO
"""
from __future__ import annotations
RotorPositionT = tuple[int, int, int]
RotorSelectionT = tuple[str, str, str]
# used alphabet --------------------------
# from string.ascii_uppercase
abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# -------------------------- default selection --------------------------
# rotors --------------------------
rotor1 = "EGZWVONAHDCLFQMSIPJBYUKXTR"
rotor2 = "FOBHMDKEXQNRAULPGSJVTYICZW"
rotor3 = "ZJXESIUQLHAVRMDOYGTNFWPBKC"
# reflector --------------------------
reflector = {
"A": "N",
"N": "A",
"B": "O",
"O": "B",
"C": "P",
"P": "C",
"D": "Q",
"Q": "D",
"E": "R",
"R": "E",
"F": "S",
"S": "F",
"G": "T",
"T": "G",
"H": "U",
"U": "H",
"I": "V",
"V": "I",
"J": "W",
"W": "J",
"K": "X",
"X": "K",
"L": "Y",
"Y": "L",
"M": "Z",
"Z": "M",
}
# -------------------------- extra rotors --------------------------
rotor4 = "RMDJXFUWGISLHVTCQNKYPBEZOA"
rotor5 = "SGLCPQWZHKXAREONTFBVIYJUDM"
rotor6 = "HVSICLTYKQUBXDWAJZOMFGPREN"
rotor7 = "RZWQHFMVDBKICJLNTUXAGYPSOE"
rotor8 = "LFKIJODBEGAMQPXVUHYSTCZRWN"
rotor9 = "KOAEGVDHXPQZMLFTYWJNBRCIUS"
def _validator(
rotpos: RotorPositionT, rotsel: RotorSelectionT, pb: str
) -> tuple[RotorPositionT, RotorSelectionT, dict[str, str]]:
"""
Checks if the values can be used for the 'enigma' function
>>> _validator((1,1,1), (rotor1, rotor2, rotor3), 'POLAND')
((1, 1, 1), ('EGZWVONAHDCLFQMSIPJBYUKXTR', 'FOBHMDKEXQNRAULPGSJVTYICZW', \
'ZJXESIUQLHAVRMDOYGTNFWPBKC'), \
{'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N'})
:param rotpos: rotor_positon
:param rotsel: rotor_selection
:param pb: plugb -> validated and transformed
:return: (rotpos, rotsel, pb)
"""
# Checks if there are 3 unique rotors
if (unique_rotsel := len(set(rotsel))) < 3:
msg = f"Please use 3 unique rotors (not {unique_rotsel})"
raise Exception(msg)
# Checks if rotor positions are valid
rotorpos1, rotorpos2, rotorpos3 = rotpos
if not 0 < rotorpos1 <= len(abc):
msg = f"First rotor position is not within range of 1..26 ({rotorpos1}"
raise ValueError(msg)
if not 0 < rotorpos2 <= len(abc):
msg = f"Second rotor position is not within range of 1..26 ({rotorpos2})"
raise ValueError(msg)
if not 0 < rotorpos3 <= len(abc):
msg = f"Third rotor position is not within range of 1..26 ({rotorpos3})"
raise ValueError(msg)
# Validates string and returns dict
pbdict = _plugboard(pb)
return rotpos, rotsel, pbdict
def _plugboard(pbstring: str) -> dict[str, str]:
"""
https://en.wikipedia.org/wiki/Enigma_machine#Plugboard
>>> _plugboard('PICTURES')
{'P': 'I', 'I': 'P', 'C': 'T', 'T': 'C', 'U': 'R', 'R': 'U', 'E': 'S', 'S': 'E'}
>>> _plugboard('POLAND')
{'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N'}
In the code, 'pb' stands for 'plugboard'
Pairs can be separated by spaces
:param pbstring: string containing plugboard setting for the Enigma machine
:return: dictionary containing converted pairs
"""
# tests the input string if it
# a) is type string
# b) has even length (so pairs can be made)
if not isinstance(pbstring, str):
msg = f"Plugboard setting isn't type string ({type(pbstring)})"
raise TypeError(msg)
elif len(pbstring) % 2 != 0:
msg = f"Odd number of symbols ({len(pbstring)})"
raise Exception(msg)
elif pbstring == "":
return {}
pbstring.replace(" ", "")
# Checks if all characters are unique
tmppbl = set()
for i in pbstring:
if i not in abc:
msg = f"'{i}' not in list of symbols"
raise Exception(msg)
elif i in tmppbl:
msg = f"Duplicate symbol ({i})"
raise Exception(msg)
else:
tmppbl.add(i)
del tmppbl
# Created the dictionary
pb = {}
for j in range(0, len(pbstring) - 1, 2):
pb[pbstring[j]] = pbstring[j + 1]
pb[pbstring[j + 1]] = pbstring[j]
return pb
def enigma(
text: str,
rotor_position: RotorPositionT,
rotor_selection: RotorSelectionT = (rotor1, rotor2, rotor3),
plugb: str = "",
) -> str:
"""
The only difference with real-world enigma is that I allowed string input.
All characters are converted to uppercase. (non-letter symbol are ignored)
How it works:
(for every letter in the message)
- Input letter goes into the plugboard.
If it is connected to another one, switch it.
- Letter goes through 3 rotors.
Each rotor can be represented as 2 sets of symbol, where one is shuffled.
Each symbol from the first set has corresponding symbol in
the second set and vice versa.
example:
| ABCDEFGHIJKLMNOPQRSTUVWXYZ | e.g. F=D and D=F
| VKLEPDBGRNWTFCJOHQAMUZYIXS |
- Symbol then goes through reflector (static rotor).
There it is switched with paired symbol
The reflector can be represented as2 sets, each with half of the alphanet.
There are usually 10 pairs of letters.
Example:
| ABCDEFGHIJKLM | e.g. E is paired to X
| ZYXWVUTSRQPON | so when E goes in X goes out and vice versa
- Letter then goes through the rotors again
- If the letter is connected to plugboard, it is switched.
- Return the letter
>>> enigma('Hello World!', (1, 2, 1), plugb='pictures')
'KORYH JUHHI!'
>>> enigma('KORYH, juhhi!', (1, 2, 1), plugb='pictures')
'HELLO, WORLD!'
>>> enigma('hello world!', (1, 1, 1), plugb='pictures')
'FPNCZ QWOBU!'
>>> enigma('FPNCZ QWOBU', (1, 1, 1), plugb='pictures')
'HELLO WORLD'
:param text: input message
:param rotor_position: tuple with 3 values in range 1..26
:param rotor_selection: tuple with 3 rotors ()
:param plugb: string containing plugboard configuration (default '')
:return: en/decrypted string
"""
text = text.upper()
rotor_position, rotor_selection, plugboard = _validator(
rotor_position, rotor_selection, plugb.upper()
)
rotorpos1, rotorpos2, rotorpos3 = rotor_position
rotor1, rotor2, rotor3 = rotor_selection
rotorpos1 -= 1
rotorpos2 -= 1
rotorpos3 -= 1
result = []
# encryption/decryption process --------------------------
for symbol in text:
if symbol in abc:
# 1st plugboard --------------------------
if symbol in plugboard:
symbol = plugboard[symbol]
# rotor ra --------------------------
index = abc.index(symbol) + rotorpos1
symbol = rotor1[index % len(abc)]
# rotor rb --------------------------
index = abc.index(symbol) + rotorpos2
symbol = rotor2[index % len(abc)]
# rotor rc --------------------------
index = abc.index(symbol) + rotorpos3
symbol = rotor3[index % len(abc)]
# reflector --------------------------
# this is the reason you don't need another machine to decipher
symbol = reflector[symbol]
# 2nd rotors
symbol = abc[rotor3.index(symbol) - rotorpos3]
symbol = abc[rotor2.index(symbol) - rotorpos2]
symbol = abc[rotor1.index(symbol) - rotorpos1]
# 2nd plugboard
if symbol in plugboard:
symbol = plugboard[symbol]
# moves/resets rotor positions
rotorpos1 += 1
if rotorpos1 >= len(abc):
rotorpos1 = 0
rotorpos2 += 1
if rotorpos2 >= len(abc):
rotorpos2 = 0
rotorpos3 += 1
if rotorpos3 >= len(abc):
rotorpos3 = 0
# else:
# pass
# Error could be also raised
# raise ValueError(
# 'Invalid symbol('+repr(symbol)+')')
result.append(symbol)
return "".join(result)
if __name__ == "__main__":
message = "This is my Python script that emulates the Enigma machine from WWII."
rotor_pos = (1, 1, 1)
pb = "pictures"
rotor_sel = (rotor2, rotor4, rotor8)
en = enigma(message, rotor_pos, rotor_sel, pb)
print("Encrypted message:", en)
print("Decrypted message:", enigma(en, rotor_pos, rotor_sel, pb))
| Python/ciphers/enigma_machine2.py/0 | {
"file_path": "Python/ciphers/enigma_machine2.py",
"repo_id": "Python",
"token_count": 3797
} | 6 |
"""
An RSA prime factor algorithm.
The program can efficiently factor RSA prime number given the private key d and
public key e.
Source: on page 3 of https://crypto.stanford.edu/~dabo/papers/RSA-survey.pdf
More readable source: https://www.di-mgt.com.au/rsa_factorize_n.html
large number can take minutes to factor, therefore are not included in doctest.
"""
from __future__ import annotations
import math
import random
def rsafactor(d: int, e: int, n: int) -> list[int]:
"""
This function returns the factors of N, where p*q=N
Return: [p, q]
We call N the RSA modulus, e the encryption exponent, and d the decryption exponent.
The pair (N, e) is the public key. As its name suggests, it is public and is used to
encrypt messages.
The pair (N, d) is the secret key or private key and is known only to the recipient
of encrypted messages.
>>> rsafactor(3, 16971, 25777)
[149, 173]
>>> rsafactor(7331, 11, 27233)
[113, 241]
>>> rsafactor(4021, 13, 17711)
[89, 199]
"""
k = d * e - 1
p = 0
q = 0
while p == 0:
g = random.randint(2, n - 1)
t = k
while True:
if t % 2 == 0:
t = t // 2
x = (g**t) % n
y = math.gcd(x - 1, n)
if x > 1 and y > 1:
p = y
q = n // y
break # find the correct factors
else:
break # t is not divisible by 2, break and choose another g
return sorted([p, q])
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python/ciphers/rsa_factorization.py/0 | {
"file_path": "Python/ciphers/rsa_factorization.py",
"repo_id": "Python",
"token_count": 721
} | 7 |
"""
https://en.wikipedia.org/wiki/Image_texture
https://en.wikipedia.org/wiki/Co-occurrence_matrix#Application_to_image_analysis
"""
import imageio.v2 as imageio
import numpy as np
def root_mean_square_error(original: np.ndarray, reference: np.ndarray) -> float:
"""Simple implementation of Root Mean Squared Error
for two N dimensional numpy arrays.
Examples:
>>> root_mean_square_error(np.array([1, 2, 3]), np.array([1, 2, 3]))
0.0
>>> root_mean_square_error(np.array([1, 2, 3]), np.array([2, 2, 2]))
0.816496580927726
>>> root_mean_square_error(np.array([1, 2, 3]), np.array([6, 4, 2]))
3.1622776601683795
"""
return np.sqrt(((original - reference) ** 2).mean())
def normalize_image(
image: np.ndarray, cap: float = 255.0, data_type: np.dtype = np.uint8
) -> np.ndarray:
"""
Normalizes image in Numpy 2D array format, between ranges 0-cap,
as to fit uint8 type.
Args:
image: 2D numpy array representing image as matrix, with values in any range
cap: Maximum cap amount for normalization
data_type: numpy data type to set output variable to
Returns:
return 2D numpy array of type uint8, corresponding to limited range matrix
Examples:
>>> normalize_image(np.array([[1, 2, 3], [4, 5, 10]]),
... cap=1.0, data_type=np.float64)
array([[0. , 0.11111111, 0.22222222],
[0.33333333, 0.44444444, 1. ]])
>>> normalize_image(np.array([[4, 4, 3], [1, 7, 2]]))
array([[127, 127, 85],
[ 0, 255, 42]], dtype=uint8)
"""
normalized = (image - np.min(image)) / (np.max(image) - np.min(image)) * cap
return normalized.astype(data_type)
def normalize_array(array: np.ndarray, cap: float = 1) -> np.ndarray:
"""Normalizes a 1D array, between ranges 0-cap.
Args:
array: List containing values to be normalized between cap range.
cap: Maximum cap amount for normalization.
Returns:
return 1D numpy array, corresponding to limited range array
Examples:
>>> normalize_array(np.array([2, 3, 5, 7]))
array([0. , 0.2, 0.6, 1. ])
>>> normalize_array(np.array([[5], [7], [11], [13]]))
array([[0. ],
[0.25],
[0.75],
[1. ]])
"""
diff = np.max(array) - np.min(array)
return (array - np.min(array)) / (1 if diff == 0 else diff) * cap
def grayscale(image: np.ndarray) -> np.ndarray:
"""
Uses luminance weights to transform RGB channel to greyscale, by
taking the dot product between the channel and the weights.
Example:
>>> grayscale(np.array([[[108, 201, 72], [255, 11, 127]],
... [[56, 56, 56], [128, 255, 107]]]))
array([[158, 97],
[ 56, 200]], dtype=uint8)
"""
return np.dot(image[:, :, 0:3], [0.299, 0.587, 0.114]).astype(np.uint8)
def binarize(image: np.ndarray, threshold: float = 127.0) -> np.ndarray:
"""
Binarizes a grayscale image based on a given threshold value,
setting values to 1 or 0 accordingly.
Examples:
>>> binarize(np.array([[128, 255], [101, 156]]))
array([[1, 1],
[0, 1]])
>>> binarize(np.array([[0.07, 1], [0.51, 0.3]]), threshold=0.5)
array([[0, 1],
[1, 0]])
"""
return np.where(image > threshold, 1, 0)
def transform(
image: np.ndarray, kind: str, kernel: np.ndarray | None = None
) -> np.ndarray:
"""
Simple image transformation using one of two available filter functions:
Erosion and Dilation.
Args:
image: binarized input image, onto which to apply transformation
kind: Can be either 'erosion', in which case the :func:np.max
function is called, or 'dilation', when :func:np.min is used instead.
kernel: n x n kernel with shape < :attr:image.shape,
to be used when applying convolution to original image
Returns:
returns a numpy array with same shape as input image,
corresponding to applied binary transformation.
Examples:
>>> img = np.array([[1, 0.5], [0.2, 0.7]])
>>> img = binarize(img, threshold=0.5)
>>> transform(img, 'erosion')
array([[1, 1],
[1, 1]], dtype=uint8)
>>> transform(img, 'dilation')
array([[0, 0],
[0, 0]], dtype=uint8)
"""
if kernel is None:
kernel = np.ones((3, 3))
if kind == "erosion":
constant = 1
apply = np.max
else:
constant = 0
apply = np.min
center_x, center_y = (x // 2 for x in kernel.shape)
# Use padded image when applying convolotion
# to not go out of bounds of the original the image
transformed = np.zeros(image.shape, dtype=np.uint8)
padded = np.pad(image, 1, "constant", constant_values=constant)
for x in range(center_x, padded.shape[0] - center_x):
for y in range(center_y, padded.shape[1] - center_y):
center = padded[
x - center_x : x + center_x + 1, y - center_y : y + center_y + 1
]
# Apply transformation method to the centered section of the image
transformed[x - center_x, y - center_y] = apply(center[kernel == 1])
return transformed
def opening_filter(image: np.ndarray, kernel: np.ndarray | None = None) -> np.ndarray:
"""
Opening filter, defined as the sequence of
erosion and then a dilation filter on the same image.
Examples:
>>> img = np.array([[1, 0.5], [0.2, 0.7]])
>>> img = binarize(img, threshold=0.5)
>>> opening_filter(img)
array([[1, 1],
[1, 1]], dtype=uint8)
"""
if kernel is None:
np.ones((3, 3))
return transform(transform(image, "dilation", kernel), "erosion", kernel)
def closing_filter(image: np.ndarray, kernel: np.ndarray | None = None) -> np.ndarray:
"""
Opening filter, defined as the sequence of
dilation and then erosion filter on the same image.
Examples:
>>> img = np.array([[1, 0.5], [0.2, 0.7]])
>>> img = binarize(img, threshold=0.5)
>>> closing_filter(img)
array([[0, 0],
[0, 0]], dtype=uint8)
"""
if kernel is None:
kernel = np.ones((3, 3))
return transform(transform(image, "erosion", kernel), "dilation", kernel)
def binary_mask(
image_gray: np.ndarray, image_map: np.ndarray
) -> tuple[np.ndarray, np.ndarray]:
"""
Apply binary mask, or thresholding based
on bit mask value (mapping mask is binary).
Returns the mapped true value mask and its complementary false value mask.
Example:
>>> img = np.array([[[108, 201, 72], [255, 11, 127]],
... [[56, 56, 56], [128, 255, 107]]])
>>> gray = grayscale(img)
>>> binary = binarize(gray)
>>> morphological = opening_filter(binary)
>>> binary_mask(gray, morphological)
(array([[1, 1],
[1, 1]], dtype=uint8), array([[158, 97],
[ 56, 200]], dtype=uint8))
"""
true_mask, false_mask = image_gray.copy(), image_gray.copy()
true_mask[image_map == 1] = 1
false_mask[image_map == 0] = 0
return true_mask, false_mask
def matrix_concurrency(image: np.ndarray, coordinate: tuple[int, int]) -> np.ndarray:
"""
Calculate sample co-occurrence matrix based on input image
as well as selected coordinates on image.
Implementation is made using basic iteration,
as function to be performed (np.max) is non-linear and therefore
not callable on the frequency domain.
Example:
>>> img = np.array([[[108, 201, 72], [255, 11, 127]],
... [[56, 56, 56], [128, 255, 107]]])
>>> gray = grayscale(img)
>>> binary = binarize(gray)
>>> morphological = opening_filter(binary)
>>> mask_1 = binary_mask(gray, morphological)[0]
>>> matrix_concurrency(mask_1, (0, 1))
array([[0., 0.],
[0., 0.]])
"""
matrix = np.zeros([np.max(image) + 1, np.max(image) + 1])
offset_x, offset_y = coordinate
for x in range(1, image.shape[0] - 1):
for y in range(1, image.shape[1] - 1):
base_pixel = image[x, y]
offset_pixel = image[x + offset_x, y + offset_y]
matrix[base_pixel, offset_pixel] += 1
matrix_sum = np.sum(matrix)
return matrix / (1 if matrix_sum == 0 else matrix_sum)
def haralick_descriptors(matrix: np.ndarray) -> list[float]:
"""Calculates all 8 Haralick descriptors based on co-occurrence input matrix.
All descriptors are as follows:
Maximum probability, Inverse Difference, Homogeneity, Entropy,
Energy, Dissimilarity, Contrast and Correlation
Args:
matrix: Co-occurrence matrix to use as base for calculating descriptors.
Returns:
Reverse ordered list of resulting descriptors
Example:
>>> img = np.array([[[108, 201, 72], [255, 11, 127]],
... [[56, 56, 56], [128, 255, 107]]])
>>> gray = grayscale(img)
>>> binary = binarize(gray)
>>> morphological = opening_filter(binary)
>>> mask_1 = binary_mask(gray, morphological)[0]
>>> concurrency = matrix_concurrency(mask_1, (0, 1))
>>> haralick_descriptors(concurrency)
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
"""
# Function np.indices could be used for bigger input types,
# but np.ogrid works just fine
i, j = np.ogrid[0 : matrix.shape[0], 0 : matrix.shape[1]] # np.indices()
# Pre-calculate frequent multiplication and subtraction
prod = np.multiply(i, j)
sub = np.subtract(i, j)
# Calculate numerical value of Maximum Probability
maximum_prob = np.max(matrix)
# Using the definition for each descriptor individually to calculate its matrix
correlation = prod * matrix
energy = np.power(matrix, 2)
contrast = matrix * np.power(sub, 2)
dissimilarity = matrix * np.abs(sub)
inverse_difference = matrix / (1 + np.abs(sub))
homogeneity = matrix / (1 + np.power(sub, 2))
entropy = -(matrix[matrix > 0] * np.log(matrix[matrix > 0]))
# Sum values for descriptors ranging from the first one to the last,
# as all are their respective origin matrix and not the resulting value yet.
return [
maximum_prob,
correlation.sum(),
energy.sum(),
contrast.sum(),
dissimilarity.sum(),
inverse_difference.sum(),
homogeneity.sum(),
entropy.sum(),
]
def get_descriptors(
masks: tuple[np.ndarray, np.ndarray], coordinate: tuple[int, int]
) -> np.ndarray:
"""
Calculate all Haralick descriptors for a sequence of
different co-occurrence matrices, given input masks and coordinates.
Example:
>>> img = np.array([[[108, 201, 72], [255, 11, 127]],
... [[56, 56, 56], [128, 255, 107]]])
>>> gray = grayscale(img)
>>> binary = binarize(gray)
>>> morphological = opening_filter(binary)
>>> get_descriptors(binary_mask(gray, morphological), (0, 1))
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
"""
descriptors = np.array(
[haralick_descriptors(matrix_concurrency(mask, coordinate)) for mask in masks]
)
# Concatenate each individual descriptor into
# one single list containing sequence of descriptors
return np.concatenate(descriptors, axis=None)
def euclidean(point_1: np.ndarray, point_2: np.ndarray) -> np.float32:
"""
Simple method for calculating the euclidean distance between two points,
with type np.ndarray.
Example:
>>> a = np.array([1, 0, -2])
>>> b = np.array([2, -1, 1])
>>> euclidean(a, b)
3.3166247903554
"""
return np.sqrt(np.sum(np.square(point_1 - point_2)))
def get_distances(descriptors: np.ndarray, base: int) -> list[tuple[int, float]]:
"""
Calculate all Euclidean distances between a selected base descriptor
and all other Haralick descriptors
The resulting comparison is return in decreasing order,
showing which descriptor is the most similar to the selected base.
Args:
descriptors: Haralick descriptors to compare with base index
base: Haralick descriptor index to use as base when calculating respective
euclidean distance to other descriptors.
Returns:
Ordered distances between descriptors
Example:
>>> index = 1
>>> img = np.array([[[108, 201, 72], [255, 11, 127]],
... [[56, 56, 56], [128, 255, 107]]])
>>> gray = grayscale(img)
>>> binary = binarize(gray)
>>> morphological = opening_filter(binary)
>>> get_distances(get_descriptors(
... binary_mask(gray, morphological), (0, 1)),
... index)
[(0, 0.0), (1, 0.0), (2, 0.0), (3, 0.0), (4, 0.0), (5, 0.0), \
(6, 0.0), (7, 0.0), (8, 0.0), (9, 0.0), (10, 0.0), (11, 0.0), (12, 0.0), \
(13, 0.0), (14, 0.0), (15, 0.0)]
"""
distances = np.array(
[euclidean(descriptor, descriptors[base]) for descriptor in descriptors]
)
# Normalize distances between range [0, 1]
normalized_distances: list[float] = normalize_array(distances, 1).tolist()
enum_distances = list(enumerate(normalized_distances))
enum_distances.sort(key=lambda tup: tup[1], reverse=True)
return enum_distances
if __name__ == "__main__":
# Index to compare haralick descriptors to
index = int(input())
q_value_list = [int(value) for value in input().split()]
q_value = (q_value_list[0], q_value_list[1])
# Format is the respective filter to apply,
# can be either 1 for the opening filter or else for the closing
parameters = {"format": int(input()), "threshold": int(input())}
# Number of images to perform methods on
b_number = int(input())
files, descriptors = [], []
for _ in range(b_number):
file = input().rstrip()
files.append(file)
# Open given image and calculate morphological filter,
# respective masks and correspondent Harralick Descriptors.
image = imageio.imread(file).astype(np.float32)
gray = grayscale(image)
threshold = binarize(gray, parameters["threshold"])
morphological = (
opening_filter(threshold)
if parameters["format"] == 1
else closing_filter(threshold)
)
masks = binary_mask(gray, morphological)
descriptors.append(get_descriptors(masks, q_value))
# Transform ordered distances array into a sequence of indexes
# corresponding to original file position
distances = get_distances(np.array(descriptors), index)
indexed_distances = np.array(distances).astype(np.uint8)[:, 0]
# Finally, print distances considering the Haralick descriptions from the base
# file to all other images using the morphology method of choice.
print(f"Query: {files[index]}")
print("Ranking:")
for idx, file_idx in enumerate(indexed_distances):
print(f"({idx}) {files[file_idx]}", end="\n")
| Python/computer_vision/haralick_descriptors.py/0 | {
"file_path": "Python/computer_vision/haralick_descriptors.py",
"repo_id": "Python",
"token_count": 6458
} | 8 |
"""Convert a Decimal Number to an Octal Number."""
import math
# Modified from:
# https://github.com/TheAlgorithms/Javascript/blob/master/Conversions/DecimalToOctal.js
def decimal_to_octal(num: int) -> str:
"""Convert a Decimal Number to an Octal Number.
>>> all(decimal_to_octal(i) == oct(i) for i
... in (0, 2, 8, 64, 65, 216, 255, 256, 512))
True
"""
octal = 0
counter = 0
while num > 0:
remainder = num % 8
octal = octal + (remainder * math.floor(math.pow(10, counter)))
counter += 1
num = math.floor(num / 8) # basically /= 8 without remainder if any
# This formatting removes trailing '.0' from `octal`.
return f"0o{int(octal)}"
def main() -> None:
"""Print octal equivalents of decimal numbers."""
print("\n2 in octal is:")
print(decimal_to_octal(2)) # = 2
print("\n8 in octal is:")
print(decimal_to_octal(8)) # = 10
print("\n65 in octal is:")
print(decimal_to_octal(65)) # = 101
print("\n216 in octal is:")
print(decimal_to_octal(216)) # = 330
print("\n512 in octal is:")
print(decimal_to_octal(512)) # = 1000
print("\n")
if __name__ == "__main__":
main()
| Python/conversions/decimal_to_octal.py/0 | {
"file_path": "Python/conversions/decimal_to_octal.py",
"repo_id": "Python",
"token_count": 522
} | 9 |
ROMAN = [
(1000, "M"),
(900, "CM"),
(500, "D"),
(400, "CD"),
(100, "C"),
(90, "XC"),
(50, "L"),
(40, "XL"),
(10, "X"),
(9, "IX"),
(5, "V"),
(4, "IV"),
(1, "I"),
]
def roman_to_int(roman: str) -> int:
"""
LeetCode No. 13 Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
https://en.wikipedia.org/wiki/Roman_numerals
>>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999}
>>> all(roman_to_int(key) == value for key, value in tests.items())
True
"""
vals = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
total = 0
place = 0
while place < len(roman):
if (place + 1 < len(roman)) and (vals[roman[place]] < vals[roman[place + 1]]):
total += vals[roman[place + 1]] - vals[roman[place]]
place += 2
else:
total += vals[roman[place]]
place += 1
return total
def int_to_roman(number: int) -> str:
"""
Given a integer, convert it to an roman numeral.
https://en.wikipedia.org/wiki/Roman_numerals
>>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999}
>>> all(int_to_roman(value) == key for key, value in tests.items())
True
"""
result = []
for arabic, roman in ROMAN:
(factor, number) = divmod(number, arabic)
result.append(roman * factor)
if number == 0:
break
return "".join(result)
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python/conversions/roman_numerals.py/0 | {
"file_path": "Python/conversions/roman_numerals.py",
"repo_id": "Python",
"token_count": 767
} | 10 |
"""
Calculate the Product Sum from a Special Array.
reference: https://dev.to/sfrasica/algorithms-product-sum-from-an-array-dc6
Python doctests can be run with the following command:
python -m doctest -v product_sum.py
Calculate the product sum of a "special" array which can contain integers or nested
arrays. The product sum is obtained by adding all elements and multiplying by their
respective depths.
For example, in the array [x, y], the product sum is (x + y). In the array [x, [y, z]],
the product sum is x + 2 * (y + z). In the array [x, [y, [z]]],
the product sum is x + 2 * (y + 3z).
Example Input:
[5, 2, [-7, 1], 3, [6, [-13, 8], 4]]
Output: 12
"""
def product_sum(arr: list[int | list], depth: int) -> int:
"""
Recursively calculates the product sum of an array.
The product sum of an array is defined as the sum of its elements multiplied by
their respective depths. If an element is a list, its product sum is calculated
recursively by multiplying the sum of its elements with its depth plus one.
Args:
arr: The array of integers and nested lists.
depth: The current depth level.
Returns:
int: The product sum of the array.
Examples:
>>> product_sum([1, 2, 3], 1)
6
>>> product_sum([-1, 2, [-3, 4]], 2)
8
>>> product_sum([1, 2, 3], -1)
-6
>>> product_sum([1, 2, 3], 0)
0
>>> product_sum([1, 2, 3], 7)
42
>>> product_sum((1, 2, 3), 7)
42
>>> product_sum({1, 2, 3}, 7)
42
>>> product_sum([1, -1], 1)
0
>>> product_sum([1, -2], 1)
-1
>>> product_sum([-3.5, [1, [0.5]]], 1)
1.5
"""
total_sum = 0
for ele in arr:
total_sum += product_sum(ele, depth + 1) if isinstance(ele, list) else ele
return total_sum * depth
def product_sum_array(array: list[int | list]) -> int:
"""
Calculates the product sum of an array.
Args:
array (List[Union[int, List]]): The array of integers and nested lists.
Returns:
int: The product sum of the array.
Examples:
>>> product_sum_array([1, 2, 3])
6
>>> product_sum_array([1, [2, 3]])
11
>>> product_sum_array([1, [2, [3, 4]]])
47
>>> product_sum_array([0])
0
>>> product_sum_array([-3.5, [1, [0.5]]])
1.5
>>> product_sum_array([1, -2])
-1
"""
return product_sum(array, 1)
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python/data_structures/arrays/product_sum.py/0 | {
"file_path": "Python/data_structures/arrays/product_sum.py",
"repo_id": "Python",
"token_count": 1116
} | 11 |
from copy import deepcopy
class FenwickTree:
"""
Fenwick Tree
More info: https://en.wikipedia.org/wiki/Fenwick_tree
"""
def __init__(self, arr: list[int] | None = None, size: int | None = None) -> None:
"""
Constructor for the Fenwick tree
Parameters:
arr (list): list of elements to initialize the tree with (optional)
size (int): size of the Fenwick tree (if arr is None)
"""
if arr is None and size is not None:
self.size = size
self.tree = [0] * size
elif arr is not None:
self.init(arr)
else:
raise ValueError("Either arr or size must be specified")
def init(self, arr: list[int]) -> None:
"""
Initialize the Fenwick tree with arr in O(N)
Parameters:
arr (list): list of elements to initialize the tree with
Returns:
None
>>> a = [1, 2, 3, 4, 5]
>>> f1 = FenwickTree(a)
>>> f2 = FenwickTree(size=len(a))
>>> for index, value in enumerate(a):
... f2.add(index, value)
>>> f1.tree == f2.tree
True
"""
self.size = len(arr)
self.tree = deepcopy(arr)
for i in range(1, self.size):
j = self.next_(i)
if j < self.size:
self.tree[j] += self.tree[i]
def get_array(self) -> list[int]:
"""
Get the Normal Array of the Fenwick tree in O(N)
Returns:
list: Normal Array of the Fenwick tree
>>> a = [i for i in range(128)]
>>> f = FenwickTree(a)
>>> f.get_array() == a
True
"""
arr = self.tree[:]
for i in range(self.size - 1, 0, -1):
j = self.next_(i)
if j < self.size:
arr[j] -= arr[i]
return arr
@staticmethod
def next_(index: int) -> int:
return index + (index & (-index))
@staticmethod
def prev(index: int) -> int:
return index - (index & (-index))
def add(self, index: int, value: int) -> None:
"""
Add a value to index in O(lg N)
Parameters:
index (int): index to add value to
value (int): value to add to index
Returns:
None
>>> f = FenwickTree([1, 2, 3, 4, 5])
>>> f.add(0, 1)
>>> f.add(1, 2)
>>> f.add(2, 3)
>>> f.add(3, 4)
>>> f.add(4, 5)
>>> f.get_array()
[2, 4, 6, 8, 10]
"""
if index == 0:
self.tree[0] += value
return
while index < self.size:
self.tree[index] += value
index = self.next_(index)
def update(self, index: int, value: int) -> None:
"""
Set the value of index in O(lg N)
Parameters:
index (int): index to set value to
value (int): value to set in index
Returns:
None
>>> f = FenwickTree([5, 4, 3, 2, 1])
>>> f.update(0, 1)
>>> f.update(1, 2)
>>> f.update(2, 3)
>>> f.update(3, 4)
>>> f.update(4, 5)
>>> f.get_array()
[1, 2, 3, 4, 5]
"""
self.add(index, value - self.get(index))
def prefix(self, right: int) -> int:
"""
Prefix sum of all elements in [0, right) in O(lg N)
Parameters:
right (int): right bound of the query (exclusive)
Returns:
int: sum of all elements in [0, right)
>>> a = [i for i in range(128)]
>>> f = FenwickTree(a)
>>> res = True
>>> for i in range(len(a)):
... res = res and f.prefix(i) == sum(a[:i])
>>> res
True
"""
if right == 0:
return 0
result = self.tree[0]
right -= 1 # make right inclusive
while right > 0:
result += self.tree[right]
right = self.prev(right)
return result
def query(self, left: int, right: int) -> int:
"""
Query the sum of all elements in [left, right) in O(lg N)
Parameters:
left (int): left bound of the query (inclusive)
right (int): right bound of the query (exclusive)
Returns:
int: sum of all elements in [left, right)
>>> a = [i for i in range(128)]
>>> f = FenwickTree(a)
>>> res = True
>>> for i in range(len(a)):
... for j in range(i + 1, len(a)):
... res = res and f.query(i, j) == sum(a[i:j])
>>> res
True
"""
return self.prefix(right) - self.prefix(left)
def get(self, index: int) -> int:
"""
Get value at index in O(lg N)
Parameters:
index (int): index to get the value
Returns:
int: Value of element at index
>>> a = [i for i in range(128)]
>>> f = FenwickTree(a)
>>> res = True
>>> for i in range(len(a)):
... res = res and f.get(i) == a[i]
>>> res
True
"""
return self.query(index, index + 1)
def rank_query(self, value: int) -> int:
"""
Find the largest index with prefix(i) <= value in O(lg N)
NOTE: Requires that all values are non-negative!
Parameters:
value (int): value to find the largest index of
Returns:
-1: if value is smaller than all elements in prefix sum
int: largest index with prefix(i) <= value
>>> f = FenwickTree([1, 2, 0, 3, 0, 5])
>>> f.rank_query(0)
-1
>>> f.rank_query(2)
0
>>> f.rank_query(1)
0
>>> f.rank_query(3)
2
>>> f.rank_query(5)
2
>>> f.rank_query(6)
4
>>> f.rank_query(11)
5
"""
value -= self.tree[0]
if value < 0:
return -1
j = 1 # Largest power of 2 <= size
while j * 2 < self.size:
j *= 2
i = 0
while j > 0:
if i + j < self.size and self.tree[i + j] <= value:
value -= self.tree[i + j]
i += j
j //= 2
return i
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python/data_structures/binary_tree/fenwick_tree.py/0 | {
"file_path": "Python/data_structures/binary_tree/fenwick_tree.py",
"repo_id": "Python",
"token_count": 3270
} | 12 |
from __future__ import annotations
from collections.abc import Iterator
from dataclasses import dataclass
@dataclass
class TreeNode:
"""
A binary tree node has a value, left child, and right child.
Props:
value: The value of the node.
left: The left child of the node.
right: The right child of the node.
"""
value: int = 0
left: TreeNode | None = None
right: TreeNode | None = None
def __post_init__(self):
if not isinstance(self.value, int):
raise TypeError("Value must be an integer.")
def __iter__(self) -> Iterator[TreeNode]:
"""
Iterate through the tree in preorder.
Returns:
An iterator of the tree nodes.
>>> list(TreeNode(1))
[1,null,null]
>>> tuple(TreeNode(1, TreeNode(2), TreeNode(3)))
(1,2,null,null,3,null,null, 2,null,null, 3,null,null)
"""
yield self
yield from self.left or ()
yield from self.right or ()
def __len__(self) -> int:
"""
Count the number of nodes in the tree.
Returns:
The number of nodes in the tree.
>>> len(TreeNode(1))
1
>>> len(TreeNode(1, TreeNode(2), TreeNode(3)))
3
"""
return sum(1 for _ in self)
def __repr__(self) -> str:
"""
Represent the tree as a string.
Returns:
A string representation of the tree.
>>> repr(TreeNode(1))
'1,null,null'
>>> repr(TreeNode(1, TreeNode(2), TreeNode(3)))
'1,2,null,null,3,null,null'
>>> repr(TreeNode(1, TreeNode(2), TreeNode(3, TreeNode(4), TreeNode(5))))
'1,2,null,null,3,4,null,null,5,null,null'
"""
return f"{self.value},{self.left!r},{self.right!r}".replace("None", "null")
@classmethod
def five_tree(cls) -> TreeNode:
"""
>>> repr(TreeNode.five_tree())
'1,2,null,null,3,4,null,null,5,null,null'
"""
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.right.left = TreeNode(4)
root.right.right = TreeNode(5)
return root
def deserialize(data: str) -> TreeNode | None:
"""
Deserialize a string to a binary tree.
Args:
data(str): The serialized string.
Returns:
The root of the binary tree.
>>> root = TreeNode.five_tree()
>>> serialzed_data = repr(root)
>>> deserialized = deserialize(serialzed_data)
>>> root == deserialized
True
>>> root is deserialized # two separate trees
False
>>> root.right.right.value = 6
>>> root == deserialized
False
>>> serialzed_data = repr(root)
>>> deserialized = deserialize(serialzed_data)
>>> root == deserialized
True
>>> deserialize("")
Traceback (most recent call last):
...
ValueError: Data cannot be empty.
"""
if not data:
raise ValueError("Data cannot be empty.")
# Split the serialized string by a comma to get node values
nodes = data.split(",")
def build_tree() -> TreeNode | None:
# Get the next value from the list
value = nodes.pop(0)
if value == "null":
return None
node = TreeNode(int(value))
node.left = build_tree() # Recursively build left subtree
node.right = build_tree() # Recursively build right subtree
return node
return build_tree()
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python/data_structures/binary_tree/serialize_deserialize_binary_tree.py/0 | {
"file_path": "Python/data_structures/binary_tree/serialize_deserialize_binary_tree.py",
"repo_id": "Python",
"token_count": 1558
} | 13 |
from operator import delitem, getitem, setitem
import pytest
from data_structures.hashing.hash_map import HashMap
def _get(k):
return getitem, k
def _set(k, v):
return setitem, k, v
def _del(k):
return delitem, k
def _run_operation(obj, fun, *args):
try:
return fun(obj, *args), None
except Exception as e:
return None, e
_add_items = (
_set("key_a", "val_a"),
_set("key_b", "val_b"),
)
_overwrite_items = [
_set("key_a", "val_a"),
_set("key_a", "val_b"),
]
_delete_items = [
_set("key_a", "val_a"),
_set("key_b", "val_b"),
_del("key_a"),
_del("key_b"),
_set("key_a", "val_a"),
_del("key_a"),
]
_access_absent_items = [
_get("key_a"),
_del("key_a"),
_set("key_a", "val_a"),
_del("key_a"),
_del("key_a"),
_get("key_a"),
]
_add_with_resize_up = [
*[_set(x, x) for x in range(5)], # guaranteed upsize
]
_add_with_resize_down = [
*[_set(x, x) for x in range(5)], # guaranteed upsize
*[_del(x) for x in range(5)],
_set("key_a", "val_b"),
]
@pytest.mark.parametrize(
"operations",
[
pytest.param(_add_items, id="add items"),
pytest.param(_overwrite_items, id="overwrite items"),
pytest.param(_delete_items, id="delete items"),
pytest.param(_access_absent_items, id="access absent items"),
pytest.param(_add_with_resize_up, id="add with resize up"),
pytest.param(_add_with_resize_down, id="add with resize down"),
],
)
def test_hash_map_is_the_same_as_dict(operations):
my = HashMap(initial_block_size=4)
py = {}
for _, (fun, *args) in enumerate(operations):
my_res, my_exc = _run_operation(my, fun, *args)
py_res, py_exc = _run_operation(py, fun, *args)
assert my_res == py_res
assert str(my_exc) == str(py_exc)
assert set(py) == set(my)
assert len(py) == len(my)
assert set(my.items()) == set(py.items())
def test_no_new_methods_was_added_to_api():
def is_public(name: str) -> bool:
return not name.startswith("_")
dict_public_names = {name for name in dir({}) if is_public(name)}
hash_public_names = {name for name in dir(HashMap()) if is_public(name)}
assert dict_public_names > hash_public_names
| Python/data_structures/hashing/tests/test_hash_map.py/0 | {
"file_path": "Python/data_structures/hashing/tests/test_hash_map.py",
"repo_id": "Python",
"token_count": 1046
} | 14 |
from __future__ import annotations
from typing import Any
class ContainsLoopError(Exception):
pass
class Node:
def __init__(self, data: Any) -> None:
self.data: Any = data
self.next_node: Node | None = None
def __iter__(self):
node = self
visited = []
while node:
if node in visited:
raise ContainsLoopError
visited.append(node)
yield node.data
node = node.next_node
@property
def has_loop(self) -> bool:
"""
A loop is when the exact same Node appears more than once in a linked list.
>>> root_node = Node(1)
>>> root_node.next_node = Node(2)
>>> root_node.next_node.next_node = Node(3)
>>> root_node.next_node.next_node.next_node = Node(4)
>>> root_node.has_loop
False
>>> root_node.next_node.next_node.next_node = root_node.next_node
>>> root_node.has_loop
True
"""
try:
list(self)
return False
except ContainsLoopError:
return True
if __name__ == "__main__":
root_node = Node(1)
root_node.next_node = Node(2)
root_node.next_node.next_node = Node(3)
root_node.next_node.next_node.next_node = Node(4)
print(root_node.has_loop) # False
root_node.next_node.next_node.next_node = root_node.next_node
print(root_node.has_loop) # True
root_node = Node(5)
root_node.next_node = Node(6)
root_node.next_node.next_node = Node(5)
root_node.next_node.next_node.next_node = Node(6)
print(root_node.has_loop) # False
root_node = Node(1)
print(root_node.has_loop) # False
| Python/data_structures/linked_list/has_loop.py/0 | {
"file_path": "Python/data_structures/linked_list/has_loop.py",
"repo_id": "Python",
"token_count": 785
} | 15 |
"""Queue represented by a Python list"""
from collections.abc import Iterable
from typing import Generic, TypeVar
_T = TypeVar("_T")
class QueueByList(Generic[_T]):
def __init__(self, iterable: Iterable[_T] | None = None) -> None:
"""
>>> QueueByList()
Queue(())
>>> QueueByList([10, 20, 30])
Queue((10, 20, 30))
>>> QueueByList((i**2 for i in range(1, 4)))
Queue((1, 4, 9))
"""
self.entries: list[_T] = list(iterable or [])
def __len__(self) -> int:
"""
>>> len(QueueByList())
0
>>> from string import ascii_lowercase
>>> len(QueueByList(ascii_lowercase))
26
>>> queue = QueueByList()
>>> for i in range(1, 11):
... queue.put(i)
>>> len(queue)
10
>>> for i in range(2):
... queue.get()
1
2
>>> len(queue)
8
"""
return len(self.entries)
def __repr__(self) -> str:
"""
>>> queue = QueueByList()
>>> queue
Queue(())
>>> str(queue)
'Queue(())'
>>> queue.put(10)
>>> queue
Queue((10,))
>>> queue.put(20)
>>> queue.put(30)
>>> queue
Queue((10, 20, 30))
"""
return f"Queue({tuple(self.entries)})"
def put(self, item: _T) -> None:
"""Put `item` to the Queue
>>> queue = QueueByList()
>>> queue.put(10)
>>> queue.put(20)
>>> len(queue)
2
>>> queue
Queue((10, 20))
"""
self.entries.append(item)
def get(self) -> _T:
"""
Get `item` from the Queue
>>> queue = QueueByList((10, 20, 30))
>>> queue.get()
10
>>> queue.put(40)
>>> queue.get()
20
>>> queue.get()
30
>>> len(queue)
1
>>> queue.get()
40
>>> queue.get()
Traceback (most recent call last):
...
IndexError: Queue is empty
"""
if not self.entries:
raise IndexError("Queue is empty")
return self.entries.pop(0)
def rotate(self, rotation: int) -> None:
"""Rotate the items of the Queue `rotation` times
>>> queue = QueueByList([10, 20, 30, 40])
>>> queue
Queue((10, 20, 30, 40))
>>> queue.rotate(1)
>>> queue
Queue((20, 30, 40, 10))
>>> queue.rotate(2)
>>> queue
Queue((40, 10, 20, 30))
"""
put = self.entries.append
get = self.entries.pop
for _ in range(rotation):
put(get(0))
def get_front(self) -> _T:
"""Get the front item from the Queue
>>> queue = QueueByList((10, 20, 30))
>>> queue.get_front()
10
>>> queue
Queue((10, 20, 30))
>>> queue.get()
10
>>> queue.get_front()
20
"""
return self.entries[0]
if __name__ == "__main__":
from doctest import testmod
testmod()
| Python/data_structures/queue/queue_by_list.py/0 | {
"file_path": "Python/data_structures/queue/queue_by_list.py",
"repo_id": "Python",
"token_count": 1626
} | 16 |
# @Author : ojas-wani
# @File : laplacian_filter.py
# @Date : 10/04/2023
import numpy as np
from cv2 import (
BORDER_DEFAULT,
COLOR_BGR2GRAY,
CV_64F,
cvtColor,
filter2D,
imread,
imshow,
waitKey,
)
from digital_image_processing.filters.gaussian_filter import gaussian_filter
def my_laplacian(src: np.ndarray, ksize: int) -> np.ndarray:
"""
:param src: the source image, which should be a grayscale or color image.
:param ksize: the size of the kernel used to compute the Laplacian filter,
which can be 1, 3, 5, or 7.
>>> my_laplacian(src=np.array([]), ksize=0)
Traceback (most recent call last):
...
ValueError: ksize must be in (1, 3, 5, 7)
"""
kernels = {
1: np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]]),
3: np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]),
5: np.array(
[
[0, 0, -1, 0, 0],
[0, -1, -2, -1, 0],
[-1, -2, 16, -2, -1],
[0, -1, -2, -1, 0],
[0, 0, -1, 0, 0],
]
),
7: np.array(
[
[0, 0, 0, -1, 0, 0, 0],
[0, 0, -2, -3, -2, 0, 0],
[0, -2, -7, -10, -7, -2, 0],
[-1, -3, -10, 68, -10, -3, -1],
[0, -2, -7, -10, -7, -2, 0],
[0, 0, -2, -3, -2, 0, 0],
[0, 0, 0, -1, 0, 0, 0],
]
),
}
if ksize not in kernels:
msg = f"ksize must be in {tuple(kernels)}"
raise ValueError(msg)
# Apply the Laplacian kernel using convolution
return filter2D(
src, CV_64F, kernels[ksize], 0, borderType=BORDER_DEFAULT, anchor=(0, 0)
)
if __name__ == "__main__":
# read original image
img = imread(r"../image_data/lena.jpg")
# turn image in gray scale value
gray = cvtColor(img, COLOR_BGR2GRAY)
# Applying gaussian filter
blur_image = gaussian_filter(gray, 3, sigma=1)
# Apply multiple Kernel to detect edges
laplacian_image = my_laplacian(ksize=3, src=blur_image)
imshow("Original image", img)
imshow("Detected edges using laplacian filter", laplacian_image)
waitKey(0)
| Python/digital_image_processing/filters/laplacian_filter.py/0 | {
"file_path": "Python/digital_image_processing/filters/laplacian_filter.py",
"repo_id": "Python",
"token_count": 1210
} | 17 |
"""
Finding the peak of a unimodal list using divide and conquer.
A unimodal array is defined as follows: array is increasing up to index p,
then decreasing afterwards. (for p >= 1)
An obvious solution can be performed in O(n),
to find the maximum of the array.
(From Kleinberg and Tardos. Algorithm Design.
Addison Wesley 2006: Chapter 5 Solved Exercise 1)
"""
from __future__ import annotations
def peak(lst: list[int]) -> int:
"""
Return the peak value of `lst`.
>>> peak([1, 2, 3, 4, 5, 4, 3, 2, 1])
5
>>> peak([1, 10, 9, 8, 7, 6, 5, 4])
10
>>> peak([1, 9, 8, 7])
9
>>> peak([1, 2, 3, 4, 5, 6, 7, 0])
7
>>> peak([1, 2, 3, 4, 3, 2, 1, 0, -1, -2])
4
"""
# middle index
m = len(lst) // 2
# choose the middle 3 elements
three = lst[m - 1 : m + 2]
# if middle element is peak
if three[1] > three[0] and three[1] > three[2]:
return three[1]
# if increasing, recurse on right
elif three[0] < three[2]:
if len(lst[:m]) == 2:
m -= 1
return peak(lst[m:])
# decreasing
else:
if len(lst[:m]) == 2:
m += 1
return peak(lst[:m])
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python/divide_and_conquer/peak.py/0 | {
"file_path": "Python/divide_and_conquer/peak.py",
"repo_id": "Python",
"token_count": 549
} | 18 |
"""
The number of partitions of a number n into at least k parts equals the number of
partitions into exactly k parts plus the number of partitions into at least k-1 parts.
Subtracting 1 from each part of a partition of n into k parts gives a partition of n-k
into k parts. These two facts together are used for this algorithm.
* https://en.wikipedia.org/wiki/Partition_(number_theory)
* https://en.wikipedia.org/wiki/Partition_function_(number_theory)
"""
def partition(m: int) -> int:
"""
>>> partition(5)
7
>>> partition(7)
15
>>> partition(100)
190569292
>>> partition(1_000)
24061467864032622473692149727991
>>> partition(-7)
Traceback (most recent call last):
...
IndexError: list index out of range
>>> partition(0)
Traceback (most recent call last):
...
IndexError: list assignment index out of range
>>> partition(7.8)
Traceback (most recent call last):
...
TypeError: 'float' object cannot be interpreted as an integer
"""
memo: list[list[int]] = [[0 for _ in range(m)] for _ in range(m + 1)]
for i in range(m + 1):
memo[i][0] = 1
for n in range(m + 1):
for k in range(1, m):
memo[n][k] += memo[n][k - 1]
if n - k > 0:
memo[n][k] += memo[n - k - 1][k]
return memo[m][m - 1]
if __name__ == "__main__":
import sys
if len(sys.argv) == 1:
try:
n = int(input("Enter a number: ").strip())
print(partition(n))
except ValueError:
print("Please enter a number.")
else:
try:
n = int(sys.argv[1])
print(partition(n))
except ValueError:
print("Please pass a number.")
| Python/dynamic_programming/integer_partition.py/0 | {
"file_path": "Python/dynamic_programming/integer_partition.py",
"repo_id": "Python",
"token_count": 742
} | 19 |
"""
You have m types of coins available in infinite quantities
where the value of each coins is given in the array S=[S0,... Sm-1]
Can you determine number of ways of making change for n units using
the given types of coins?
https://www.hackerrank.com/challenges/coin-change/problem
"""
def dp_count(s, n):
"""
>>> dp_count([1, 2, 3], 4)
4
>>> dp_count([1, 2, 3], 7)
8
>>> dp_count([2, 5, 3, 6], 10)
5
>>> dp_count([10], 99)
0
>>> dp_count([4, 5, 6], 0)
1
>>> dp_count([1, 2, 3], -5)
0
"""
if n < 0:
return 0
# table[i] represents the number of ways to get to amount i
table = [0] * (n + 1)
# There is exactly 1 way to get to zero(You pick no coins).
table[0] = 1
# Pick all coins one by one and update table[] values
# after the index greater than or equal to the value of the
# picked coin
for coin_val in s:
for j in range(coin_val, n + 1):
table[j] += table[j - coin_val]
return table[n]
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python/dynamic_programming/minimum_coin_change.py/0 | {
"file_path": "Python/dynamic_programming/minimum_coin_change.py",
"repo_id": "Python",
"token_count": 453
} | 20 |
from typing import Any
def viterbi(
observations_space: list,
states_space: list,
initial_probabilities: dict,
transition_probabilities: dict,
emission_probabilities: dict,
) -> list:
"""
Viterbi Algorithm, to find the most likely path of
states from the start and the expected output.
https://en.wikipedia.org/wiki/Viterbi_algorithm
sdafads
Wikipedia example
>>> observations = ["normal", "cold", "dizzy"]
>>> states = ["Healthy", "Fever"]
>>> start_p = {"Healthy": 0.6, "Fever": 0.4}
>>> trans_p = {
... "Healthy": {"Healthy": 0.7, "Fever": 0.3},
... "Fever": {"Healthy": 0.4, "Fever": 0.6},
... }
>>> emit_p = {
... "Healthy": {"normal": 0.5, "cold": 0.4, "dizzy": 0.1},
... "Fever": {"normal": 0.1, "cold": 0.3, "dizzy": 0.6},
... }
>>> viterbi(observations, states, start_p, trans_p, emit_p)
['Healthy', 'Healthy', 'Fever']
>>> viterbi((), states, start_p, trans_p, emit_p)
Traceback (most recent call last):
...
ValueError: There's an empty parameter
>>> viterbi(observations, (), start_p, trans_p, emit_p)
Traceback (most recent call last):
...
ValueError: There's an empty parameter
>>> viterbi(observations, states, {}, trans_p, emit_p)
Traceback (most recent call last):
...
ValueError: There's an empty parameter
>>> viterbi(observations, states, start_p, {}, emit_p)
Traceback (most recent call last):
...
ValueError: There's an empty parameter
>>> viterbi(observations, states, start_p, trans_p, {})
Traceback (most recent call last):
...
ValueError: There's an empty parameter
>>> viterbi("invalid", states, start_p, trans_p, emit_p)
Traceback (most recent call last):
...
ValueError: observations_space must be a list
>>> viterbi(["valid", 123], states, start_p, trans_p, emit_p)
Traceback (most recent call last):
...
ValueError: observations_space must be a list of strings
>>> viterbi(observations, "invalid", start_p, trans_p, emit_p)
Traceback (most recent call last):
...
ValueError: states_space must be a list
>>> viterbi(observations, ["valid", 123], start_p, trans_p, emit_p)
Traceback (most recent call last):
...
ValueError: states_space must be a list of strings
>>> viterbi(observations, states, "invalid", trans_p, emit_p)
Traceback (most recent call last):
...
ValueError: initial_probabilities must be a dict
>>> viterbi(observations, states, {2:2}, trans_p, emit_p)
Traceback (most recent call last):
...
ValueError: initial_probabilities all keys must be strings
>>> viterbi(observations, states, {"a":2}, trans_p, emit_p)
Traceback (most recent call last):
...
ValueError: initial_probabilities all values must be float
>>> viterbi(observations, states, start_p, "invalid", emit_p)
Traceback (most recent call last):
...
ValueError: transition_probabilities must be a dict
>>> viterbi(observations, states, start_p, {"a":2}, emit_p)
Traceback (most recent call last):
...
ValueError: transition_probabilities all values must be dict
>>> viterbi(observations, states, start_p, {2:{2:2}}, emit_p)
Traceback (most recent call last):
...
ValueError: transition_probabilities all keys must be strings
>>> viterbi(observations, states, start_p, {"a":{2:2}}, emit_p)
Traceback (most recent call last):
...
ValueError: transition_probabilities all keys must be strings
>>> viterbi(observations, states, start_p, {"a":{"b":2}}, emit_p)
Traceback (most recent call last):
...
ValueError: transition_probabilities nested dictionary all values must be float
>>> viterbi(observations, states, start_p, trans_p, "invalid")
Traceback (most recent call last):
...
ValueError: emission_probabilities must be a dict
>>> viterbi(observations, states, start_p, trans_p, None)
Traceback (most recent call last):
...
ValueError: There's an empty parameter
"""
_validation(
observations_space,
states_space,
initial_probabilities,
transition_probabilities,
emission_probabilities,
)
# Creates data structures and fill initial step
probabilities: dict = {}
pointers: dict = {}
for state in states_space:
observation = observations_space[0]
probabilities[(state, observation)] = (
initial_probabilities[state] * emission_probabilities[state][observation]
)
pointers[(state, observation)] = None
# Fills the data structure with the probabilities of
# different transitions and pointers to previous states
for o in range(1, len(observations_space)):
observation = observations_space[o]
prior_observation = observations_space[o - 1]
for state in states_space:
# Calculates the argmax for probability function
arg_max = ""
max_probability = -1
for k_state in states_space:
probability = (
probabilities[(k_state, prior_observation)]
* transition_probabilities[k_state][state]
* emission_probabilities[state][observation]
)
if probability > max_probability:
max_probability = probability
arg_max = k_state
# Update probabilities and pointers dicts
probabilities[(state, observation)] = (
probabilities[(arg_max, prior_observation)]
* transition_probabilities[arg_max][state]
* emission_probabilities[state][observation]
)
pointers[(state, observation)] = arg_max
# The final observation
final_observation = observations_space[len(observations_space) - 1]
# argmax for given final observation
arg_max = ""
max_probability = -1
for k_state in states_space:
probability = probabilities[(k_state, final_observation)]
if probability > max_probability:
max_probability = probability
arg_max = k_state
last_state = arg_max
# Process pointers backwards
previous = last_state
result = []
for o in range(len(observations_space) - 1, -1, -1):
result.append(previous)
previous = pointers[previous, observations_space[o]]
result.reverse()
return result
def _validation(
observations_space: Any,
states_space: Any,
initial_probabilities: Any,
transition_probabilities: Any,
emission_probabilities: Any,
) -> None:
"""
>>> observations = ["normal", "cold", "dizzy"]
>>> states = ["Healthy", "Fever"]
>>> start_p = {"Healthy": 0.6, "Fever": 0.4}
>>> trans_p = {
... "Healthy": {"Healthy": 0.7, "Fever": 0.3},
... "Fever": {"Healthy": 0.4, "Fever": 0.6},
... }
>>> emit_p = {
... "Healthy": {"normal": 0.5, "cold": 0.4, "dizzy": 0.1},
... "Fever": {"normal": 0.1, "cold": 0.3, "dizzy": 0.6},
... }
>>> _validation(observations, states, start_p, trans_p, emit_p)
>>> _validation([], states, start_p, trans_p, emit_p)
Traceback (most recent call last):
...
ValueError: There's an empty parameter
"""
_validate_not_empty(
observations_space,
states_space,
initial_probabilities,
transition_probabilities,
emission_probabilities,
)
_validate_lists(observations_space, states_space)
_validate_dicts(
initial_probabilities, transition_probabilities, emission_probabilities
)
def _validate_not_empty(
observations_space: Any,
states_space: Any,
initial_probabilities: Any,
transition_probabilities: Any,
emission_probabilities: Any,
) -> None:
"""
>>> _validate_not_empty(["a"], ["b"], {"c":0.5},
... {"d": {"e": 0.6}}, {"f": {"g": 0.7}})
>>> _validate_not_empty(["a"], ["b"], {"c":0.5}, {}, {"f": {"g": 0.7}})
Traceback (most recent call last):
...
ValueError: There's an empty parameter
>>> _validate_not_empty(["a"], ["b"], None, {"d": {"e": 0.6}}, {"f": {"g": 0.7}})
Traceback (most recent call last):
...
ValueError: There's an empty parameter
"""
if not all(
[
observations_space,
states_space,
initial_probabilities,
transition_probabilities,
emission_probabilities,
]
):
raise ValueError("There's an empty parameter")
def _validate_lists(observations_space: Any, states_space: Any) -> None:
"""
>>> _validate_lists(["a"], ["b"])
>>> _validate_lists(1234, ["b"])
Traceback (most recent call last):
...
ValueError: observations_space must be a list
>>> _validate_lists(["a"], [3])
Traceback (most recent call last):
...
ValueError: states_space must be a list of strings
"""
_validate_list(observations_space, "observations_space")
_validate_list(states_space, "states_space")
def _validate_list(_object: Any, var_name: str) -> None:
"""
>>> _validate_list(["a"], "mock_name")
>>> _validate_list("a", "mock_name")
Traceback (most recent call last):
...
ValueError: mock_name must be a list
>>> _validate_list([0.5], "mock_name")
Traceback (most recent call last):
...
ValueError: mock_name must be a list of strings
"""
if not isinstance(_object, list):
msg = f"{var_name} must be a list"
raise ValueError(msg)
else:
for x in _object:
if not isinstance(x, str):
msg = f"{var_name} must be a list of strings"
raise ValueError(msg)
def _validate_dicts(
initial_probabilities: Any,
transition_probabilities: Any,
emission_probabilities: Any,
) -> None:
"""
>>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {"g": 0.7}})
>>> _validate_dicts("invalid", {"d": {"e": 0.6}}, {"f": {"g": 0.7}})
Traceback (most recent call last):
...
ValueError: initial_probabilities must be a dict
>>> _validate_dicts({"c":0.5}, {2: {"e": 0.6}}, {"f": {"g": 0.7}})
Traceback (most recent call last):
...
ValueError: transition_probabilities all keys must be strings
>>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {2: 0.7}})
Traceback (most recent call last):
...
ValueError: emission_probabilities all keys must be strings
>>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {"g": "h"}})
Traceback (most recent call last):
...
ValueError: emission_probabilities nested dictionary all values must be float
"""
_validate_dict(initial_probabilities, "initial_probabilities", float)
_validate_nested_dict(transition_probabilities, "transition_probabilities")
_validate_nested_dict(emission_probabilities, "emission_probabilities")
def _validate_nested_dict(_object: Any, var_name: str) -> None:
"""
>>> _validate_nested_dict({"a":{"b": 0.5}}, "mock_name")
>>> _validate_nested_dict("invalid", "mock_name")
Traceback (most recent call last):
...
ValueError: mock_name must be a dict
>>> _validate_nested_dict({"a": 8}, "mock_name")
Traceback (most recent call last):
...
ValueError: mock_name all values must be dict
>>> _validate_nested_dict({"a":{2: 0.5}}, "mock_name")
Traceback (most recent call last):
...
ValueError: mock_name all keys must be strings
>>> _validate_nested_dict({"a":{"b": 4}}, "mock_name")
Traceback (most recent call last):
...
ValueError: mock_name nested dictionary all values must be float
"""
_validate_dict(_object, var_name, dict)
for x in _object.values():
_validate_dict(x, var_name, float, True)
def _validate_dict(
_object: Any, var_name: str, value_type: type, nested: bool = False
) -> None:
"""
>>> _validate_dict({"b": 0.5}, "mock_name", float)
>>> _validate_dict("invalid", "mock_name", float)
Traceback (most recent call last):
...
ValueError: mock_name must be a dict
>>> _validate_dict({"a": 8}, "mock_name", dict)
Traceback (most recent call last):
...
ValueError: mock_name all values must be dict
>>> _validate_dict({2: 0.5}, "mock_name",float, True)
Traceback (most recent call last):
...
ValueError: mock_name all keys must be strings
>>> _validate_dict({"b": 4}, "mock_name", float,True)
Traceback (most recent call last):
...
ValueError: mock_name nested dictionary all values must be float
"""
if not isinstance(_object, dict):
msg = f"{var_name} must be a dict"
raise ValueError(msg)
if not all(isinstance(x, str) for x in _object):
msg = f"{var_name} all keys must be strings"
raise ValueError(msg)
if not all(isinstance(x, value_type) for x in _object.values()):
nested_text = "nested dictionary " if nested else ""
msg = f"{var_name} {nested_text}all values must be {value_type.__name__}"
raise ValueError(msg)
if __name__ == "__main__":
from doctest import testmod
testmod()
| Python/dynamic_programming/viterbi.py/0 | {
"file_path": "Python/dynamic_programming/viterbi.py",
"repo_id": "Python",
"token_count": 5966
} | 21 |
# 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/electronics/ohms_law.py/0 | {
"file_path": "Python/electronics/ohms_law.py",
"repo_id": "Python",
"token_count": 535
} | 22 |
# https://www.investopedia.com
from __future__ import annotations
def simple_interest(
principal: float, daily_interest_rate: float, days_between_payments: float
) -> float:
"""
>>> simple_interest(18000.0, 0.06, 3)
3240.0
>>> simple_interest(0.5, 0.06, 3)
0.09
>>> simple_interest(18000.0, 0.01, 10)
1800.0
>>> simple_interest(18000.0, 0.0, 3)
0.0
>>> simple_interest(5500.0, 0.01, 100)
5500.0
>>> simple_interest(10000.0, -0.06, 3)
Traceback (most recent call last):
...
ValueError: daily_interest_rate must be >= 0
>>> simple_interest(-10000.0, 0.06, 3)
Traceback (most recent call last):
...
ValueError: principal must be > 0
>>> simple_interest(5500.0, 0.01, -5)
Traceback (most recent call last):
...
ValueError: days_between_payments must be > 0
"""
if days_between_payments <= 0:
raise ValueError("days_between_payments must be > 0")
if daily_interest_rate < 0:
raise ValueError("daily_interest_rate must be >= 0")
if principal <= 0:
raise ValueError("principal must be > 0")
return principal * daily_interest_rate * days_between_payments
def compound_interest(
principal: float,
nominal_annual_interest_rate_percentage: float,
number_of_compounding_periods: float,
) -> float:
"""
>>> compound_interest(10000.0, 0.05, 3)
1576.2500000000014
>>> compound_interest(10000.0, 0.05, 1)
500.00000000000045
>>> compound_interest(0.5, 0.05, 3)
0.07881250000000006
>>> compound_interest(10000.0, 0.06, -4)
Traceback (most recent call last):
...
ValueError: number_of_compounding_periods must be > 0
>>> compound_interest(10000.0, -3.5, 3.0)
Traceback (most recent call last):
...
ValueError: nominal_annual_interest_rate_percentage must be >= 0
>>> compound_interest(-5500.0, 0.01, 5)
Traceback (most recent call last):
...
ValueError: principal must be > 0
"""
if number_of_compounding_periods <= 0:
raise ValueError("number_of_compounding_periods must be > 0")
if nominal_annual_interest_rate_percentage < 0:
raise ValueError("nominal_annual_interest_rate_percentage must be >= 0")
if principal <= 0:
raise ValueError("principal must be > 0")
return principal * (
(1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods
- 1
)
def apr_interest(
principal: float,
nominal_annual_percentage_rate: float,
number_of_years: float,
) -> float:
"""
>>> apr_interest(10000.0, 0.05, 3)
1618.223072263547
>>> apr_interest(10000.0, 0.05, 1)
512.6749646744732
>>> apr_interest(0.5, 0.05, 3)
0.08091115361317736
>>> apr_interest(10000.0, 0.06, -4)
Traceback (most recent call last):
...
ValueError: number_of_years must be > 0
>>> apr_interest(10000.0, -3.5, 3.0)
Traceback (most recent call last):
...
ValueError: nominal_annual_percentage_rate must be >= 0
>>> apr_interest(-5500.0, 0.01, 5)
Traceback (most recent call last):
...
ValueError: principal must be > 0
"""
if number_of_years <= 0:
raise ValueError("number_of_years must be > 0")
if nominal_annual_percentage_rate < 0:
raise ValueError("nominal_annual_percentage_rate must be >= 0")
if principal <= 0:
raise ValueError("principal must be > 0")
return compound_interest(
principal, nominal_annual_percentage_rate / 365, number_of_years * 365
)
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python/financial/interest.py/0 | {
"file_path": "Python/financial/interest.py",
"repo_id": "Python",
"token_count": 1501
} | 23 |
from math import atan, cos, radians, sin, tan
from .haversine_distance import haversine_distance
AXIS_A = 6378137.0
AXIS_B = 6356752.314245
EQUATORIAL_RADIUS = 6378137
def lamberts_ellipsoidal_distance(
lat1: float, lon1: float, lat2: float, lon2: float
) -> float:
"""
Calculate the shortest distance along the surface of an ellipsoid between
two points on the surface of earth given longitudes and latitudes
https://en.wikipedia.org/wiki/Geographical_distance#Lambert's_formula_for_long_lines
NOTE: This algorithm uses geodesy/haversine_distance.py to compute central angle,
sigma
Representing the earth as an ellipsoid allows us to approximate distances between
points on the surface much better than a sphere. Ellipsoidal formulas treat the
Earth as an oblate ellipsoid which means accounting for the flattening that happens
at the North and South poles. Lambert's formulae provide accuracy on the order of
10 meteres over thousands of kilometeres. Other methods can provide
millimeter-level accuracy but this is a simpler method to calculate long range
distances without increasing computational intensity.
Args:
lat1, lon1: latitude and longitude of coordinate 1
lat2, lon2: latitude and longitude of coordinate 2
Returns:
geographical distance between two points in metres
>>> from collections import namedtuple
>>> point_2d = namedtuple("point_2d", "lat lon")
>>> SAN_FRANCISCO = point_2d(37.774856, -122.424227)
>>> YOSEMITE = point_2d(37.864742, -119.537521)
>>> NEW_YORK = point_2d(40.713019, -74.012647)
>>> VENICE = point_2d(45.443012, 12.313071)
>>> f"{lamberts_ellipsoidal_distance(*SAN_FRANCISCO, *YOSEMITE):0,.0f} meters"
'254,351 meters'
>>> f"{lamberts_ellipsoidal_distance(*SAN_FRANCISCO, *NEW_YORK):0,.0f} meters"
'4,138,992 meters'
>>> f"{lamberts_ellipsoidal_distance(*SAN_FRANCISCO, *VENICE):0,.0f} meters"
'9,737,326 meters'
"""
# CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System
# Distance in metres(m)
# Equation Parameters
# https://en.wikipedia.org/wiki/Geographical_distance#Lambert's_formula_for_long_lines
flattening = (AXIS_A - AXIS_B) / AXIS_A
# Parametric latitudes
# https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude
b_lat1 = atan((1 - flattening) * tan(radians(lat1)))
b_lat2 = atan((1 - flattening) * tan(radians(lat2)))
# Compute central angle between two points
# using haversine theta. sigma = haversine_distance / equatorial radius
sigma = haversine_distance(lat1, lon1, lat2, lon2) / EQUATORIAL_RADIUS
# Intermediate P and Q values
p_value = (b_lat1 + b_lat2) / 2
q_value = (b_lat2 - b_lat1) / 2
# Intermediate X value
# X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2)
x_numerator = (sin(p_value) ** 2) * (cos(q_value) ** 2)
x_demonimator = cos(sigma / 2) ** 2
x_value = (sigma - sin(sigma)) * (x_numerator / x_demonimator)
# Intermediate Y value
# Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2)
y_numerator = (cos(p_value) ** 2) * (sin(q_value) ** 2)
y_denominator = sin(sigma / 2) ** 2
y_value = (sigma + sin(sigma)) * (y_numerator / y_denominator)
return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value)))
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python/geodesy/lamberts_ellipsoidal_distance.py/0 | {
"file_path": "Python/geodesy/lamberts_ellipsoidal_distance.py",
"repo_id": "Python",
"token_count": 1356
} | 24 |
"""
https://en.wikipedia.org/wiki/Breadth-first_search
pseudo-code:
breadth_first_search(graph G, start vertex s):
// all nodes initially unexplored
mark s as explored
let Q = queue data structure, initialized with s
while Q is non-empty:
remove the first node of Q, call it v
for each edge(v, w): // for w in graph[v]
if w unexplored:
mark w as explored
add w to Q (at the end)
"""
from __future__ import annotations
from collections import deque
from queue import Queue
from timeit import timeit
G = {
"A": ["B", "C"],
"B": ["A", "D", "E"],
"C": ["A", "F"],
"D": ["B"],
"E": ["B", "F"],
"F": ["C", "E"],
}
def breadth_first_search(graph: dict, start: str) -> list[str]:
"""
Implementation of breadth first search using queue.Queue.
>>> ''.join(breadth_first_search(G, 'A'))
'ABCDEF'
"""
explored = {start}
result = [start]
queue: Queue = Queue()
queue.put(start)
while not queue.empty():
v = queue.get()
for w in graph[v]:
if w not in explored:
explored.add(w)
result.append(w)
queue.put(w)
return result
def breadth_first_search_with_deque(graph: dict, start: str) -> list[str]:
"""
Implementation of breadth first search using collection.queue.
>>> ''.join(breadth_first_search_with_deque(G, 'A'))
'ABCDEF'
"""
visited = {start}
result = [start]
queue = deque([start])
while queue:
v = queue.popleft()
for child in graph[v]:
if child not in visited:
visited.add(child)
result.append(child)
queue.append(child)
return result
def benchmark_function(name: str) -> None:
setup = f"from __main__ import G, {name}"
number = 10000
res = timeit(f"{name}(G, 'A')", setup=setup, number=number)
print(f"{name:<35} finished {number} runs in {res:.5f} seconds")
if __name__ == "__main__":
import doctest
doctest.testmod()
benchmark_function("breadth_first_search")
benchmark_function("breadth_first_search_with_deque")
# breadth_first_search finished 10000 runs in 0.20999 seconds
# breadth_first_search_with_deque finished 10000 runs in 0.01421 seconds
| Python/graphs/breadth_first_search_2.py/0 | {
"file_path": "Python/graphs/breadth_first_search_2.py",
"repo_id": "Python",
"token_count": 983
} | 25 |
from collections import deque
from math import floor
from random import random
from time import time
# the default weight is 1 if not assigned but all the implementation is weighted
class DirectedGraph:
def __init__(self):
self.graph = {}
# adding vertices and edges
# adding the weight is optional
# handles repetition
def add_pair(self, u, v, w=1):
if self.graph.get(u):
if self.graph[u].count([w, v]) == 0:
self.graph[u].append([w, v])
else:
self.graph[u] = [[w, v]]
if not self.graph.get(v):
self.graph[v] = []
def all_nodes(self):
return list(self.graph)
# handles if the input does not exist
def remove_pair(self, u, v):
if self.graph.get(u):
for _ in self.graph[u]:
if _[1] == v:
self.graph[u].remove(_)
# if no destination is meant the default value is -1
def dfs(self, s=-2, d=-1):
if s == d:
return []
stack = []
visited = []
if s == -2:
s = next(iter(self.graph))
stack.append(s)
visited.append(s)
ss = s
while True:
# check if there is any non isolated nodes
if len(self.graph[s]) != 0:
ss = s
for node in self.graph[s]:
if visited.count(node[1]) < 1:
if node[1] == d:
visited.append(d)
return visited
else:
stack.append(node[1])
visited.append(node[1])
ss = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
if len(stack) != 0:
s = stack[len(stack) - 1]
else:
s = ss
# check if se have reached the starting point
if len(stack) == 0:
return visited
# c is the count of nodes you want and if you leave it or pass -1 to the function
# the count will be random from 10 to 10000
def fill_graph_randomly(self, c=-1):
if c == -1:
c = floor(random() * 10000) + 10
for i in range(c):
# every vertex has max 100 edges
for _ in range(floor(random() * 102) + 1):
n = floor(random() * c) + 1
if n != i:
self.add_pair(i, n, 1)
def bfs(self, s=-2):
d = deque()
visited = []
if s == -2:
s = next(iter(self.graph))
d.append(s)
visited.append(s)
while d:
s = d.popleft()
if len(self.graph[s]) != 0:
for node in self.graph[s]:
if visited.count(node[1]) < 1:
d.append(node[1])
visited.append(node[1])
return visited
def in_degree(self, u):
count = 0
for x in self.graph:
for y in self.graph[x]:
if y[1] == u:
count += 1
return count
def out_degree(self, u):
return len(self.graph[u])
def topological_sort(self, s=-2):
stack = []
visited = []
if s == -2:
s = next(iter(self.graph))
stack.append(s)
visited.append(s)
ss = s
sorted_nodes = []
while True:
# check if there is any non isolated nodes
if len(self.graph[s]) != 0:
ss = s
for node in self.graph[s]:
if visited.count(node[1]) < 1:
stack.append(node[1])
visited.append(node[1])
ss = node[1]
break
# check if all the children are visited
if s == ss:
sorted_nodes.append(stack.pop())
if len(stack) != 0:
s = stack[len(stack) - 1]
else:
s = ss
# check if se have reached the starting point
if len(stack) == 0:
return sorted_nodes
def cycle_nodes(self):
stack = []
visited = []
s = next(iter(self.graph))
stack.append(s)
visited.append(s)
parent = -2
indirect_parents = []
ss = s
on_the_way_back = False
anticipating_nodes = set()
while True:
# check if there is any non isolated nodes
if len(self.graph[s]) != 0:
ss = s
for node in self.graph[s]:
if (
visited.count(node[1]) > 0
and node[1] != parent
and indirect_parents.count(node[1]) > 0
and not on_the_way_back
):
len_stack = len(stack) - 1
while len_stack >= 0:
if stack[len_stack] == node[1]:
anticipating_nodes.add(node[1])
break
else:
anticipating_nodes.add(stack[len_stack])
len_stack -= 1
if visited.count(node[1]) < 1:
stack.append(node[1])
visited.append(node[1])
ss = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
on_the_way_back = True
if len(stack) != 0:
s = stack[len(stack) - 1]
else:
on_the_way_back = False
indirect_parents.append(parent)
parent = s
s = ss
# check if se have reached the starting point
if len(stack) == 0:
return list(anticipating_nodes)
def has_cycle(self):
stack = []
visited = []
s = next(iter(self.graph))
stack.append(s)
visited.append(s)
parent = -2
indirect_parents = []
ss = s
on_the_way_back = False
anticipating_nodes = set()
while True:
# check if there is any non isolated nodes
if len(self.graph[s]) != 0:
ss = s
for node in self.graph[s]:
if (
visited.count(node[1]) > 0
and node[1] != parent
and indirect_parents.count(node[1]) > 0
and not on_the_way_back
):
len_stack_minus_one = len(stack) - 1
while len_stack_minus_one >= 0:
if stack[len_stack_minus_one] == node[1]:
anticipating_nodes.add(node[1])
break
else:
return True
if visited.count(node[1]) < 1:
stack.append(node[1])
visited.append(node[1])
ss = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
on_the_way_back = True
if len(stack) != 0:
s = stack[len(stack) - 1]
else:
on_the_way_back = False
indirect_parents.append(parent)
parent = s
s = ss
# check if se have reached the starting point
if len(stack) == 0:
return False
def dfs_time(self, s=-2, e=-1):
begin = time()
self.dfs(s, e)
end = time()
return end - begin
def bfs_time(self, s=-2):
begin = time()
self.bfs(s)
end = time()
return end - begin
class Graph:
def __init__(self):
self.graph = {}
# adding vertices and edges
# adding the weight is optional
# handles repetition
def add_pair(self, u, v, w=1):
# check if the u exists
if self.graph.get(u):
# if there already is a edge
if self.graph[u].count([w, v]) == 0:
self.graph[u].append([w, v])
else:
# if u does not exist
self.graph[u] = [[w, v]]
# add the other way
if self.graph.get(v):
# if there already is a edge
if self.graph[v].count([w, u]) == 0:
self.graph[v].append([w, u])
else:
# if u does not exist
self.graph[v] = [[w, u]]
# handles if the input does not exist
def remove_pair(self, u, v):
if self.graph.get(u):
for _ in self.graph[u]:
if _[1] == v:
self.graph[u].remove(_)
# the other way round
if self.graph.get(v):
for _ in self.graph[v]:
if _[1] == u:
self.graph[v].remove(_)
# if no destination is meant the default value is -1
def dfs(self, s=-2, d=-1):
if s == d:
return []
stack = []
visited = []
if s == -2:
s = next(iter(self.graph))
stack.append(s)
visited.append(s)
ss = s
while True:
# check if there is any non isolated nodes
if len(self.graph[s]) != 0:
ss = s
for node in self.graph[s]:
if visited.count(node[1]) < 1:
if node[1] == d:
visited.append(d)
return visited
else:
stack.append(node[1])
visited.append(node[1])
ss = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
if len(stack) != 0:
s = stack[len(stack) - 1]
else:
s = ss
# check if se have reached the starting point
if len(stack) == 0:
return visited
# c is the count of nodes you want and if you leave it or pass -1 to the function
# the count will be random from 10 to 10000
def fill_graph_randomly(self, c=-1):
if c == -1:
c = floor(random() * 10000) + 10
for i in range(c):
# every vertex has max 100 edges
for _ in range(floor(random() * 102) + 1):
n = floor(random() * c) + 1
if n != i:
self.add_pair(i, n, 1)
def bfs(self, s=-2):
d = deque()
visited = []
if s == -2:
s = next(iter(self.graph))
d.append(s)
visited.append(s)
while d:
s = d.popleft()
if len(self.graph[s]) != 0:
for node in self.graph[s]:
if visited.count(node[1]) < 1:
d.append(node[1])
visited.append(node[1])
return visited
def degree(self, u):
return len(self.graph[u])
def cycle_nodes(self):
stack = []
visited = []
s = next(iter(self.graph))
stack.append(s)
visited.append(s)
parent = -2
indirect_parents = []
ss = s
on_the_way_back = False
anticipating_nodes = set()
while True:
# check if there is any non isolated nodes
if len(self.graph[s]) != 0:
ss = s
for node in self.graph[s]:
if (
visited.count(node[1]) > 0
and node[1] != parent
and indirect_parents.count(node[1]) > 0
and not on_the_way_back
):
len_stack = len(stack) - 1
while len_stack >= 0:
if stack[len_stack] == node[1]:
anticipating_nodes.add(node[1])
break
else:
anticipating_nodes.add(stack[len_stack])
len_stack -= 1
if visited.count(node[1]) < 1:
stack.append(node[1])
visited.append(node[1])
ss = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
on_the_way_back = True
if len(stack) != 0:
s = stack[len(stack) - 1]
else:
on_the_way_back = False
indirect_parents.append(parent)
parent = s
s = ss
# check if se have reached the starting point
if len(stack) == 0:
return list(anticipating_nodes)
def has_cycle(self):
stack = []
visited = []
s = next(iter(self.graph))
stack.append(s)
visited.append(s)
parent = -2
indirect_parents = []
ss = s
on_the_way_back = False
anticipating_nodes = set()
while True:
# check if there is any non isolated nodes
if len(self.graph[s]) != 0:
ss = s
for node in self.graph[s]:
if (
visited.count(node[1]) > 0
and node[1] != parent
and indirect_parents.count(node[1]) > 0
and not on_the_way_back
):
len_stack_minus_one = len(stack) - 1
while len_stack_minus_one >= 0:
if stack[len_stack_minus_one] == node[1]:
anticipating_nodes.add(node[1])
break
else:
return True
if visited.count(node[1]) < 1:
stack.append(node[1])
visited.append(node[1])
ss = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
on_the_way_back = True
if len(stack) != 0:
s = stack[len(stack) - 1]
else:
on_the_way_back = False
indirect_parents.append(parent)
parent = s
s = ss
# check if se have reached the starting point
if len(stack) == 0:
return False
def all_nodes(self):
return list(self.graph)
def dfs_time(self, s=-2, e=-1):
begin = time()
self.dfs(s, e)
end = time()
return end - begin
def bfs_time(self, s=-2):
begin = time()
self.bfs(s)
end = time()
return end - begin
| Python/graphs/directed_and_undirected_(weighted)_graph.py/0 | {
"file_path": "Python/graphs/directed_and_undirected_(weighted)_graph.py",
"repo_id": "Python",
"token_count": 9249
} | 26 |
"""
An implementation of Karger's Algorithm for partitioning a graph.
"""
from __future__ import annotations
import random
# Adjacency list representation of this graph:
# https://en.wikipedia.org/wiki/File:Single_run_of_Karger%E2%80%99s_Mincut_algorithm.svg
TEST_GRAPH = {
"1": ["2", "3", "4", "5"],
"2": ["1", "3", "4", "5"],
"3": ["1", "2", "4", "5", "10"],
"4": ["1", "2", "3", "5", "6"],
"5": ["1", "2", "3", "4", "7"],
"6": ["7", "8", "9", "10", "4"],
"7": ["6", "8", "9", "10", "5"],
"8": ["6", "7", "9", "10"],
"9": ["6", "7", "8", "10"],
"10": ["6", "7", "8", "9", "3"],
}
def partition_graph(graph: dict[str, list[str]]) -> set[tuple[str, str]]:
"""
Partitions a graph using Karger's Algorithm. Implemented from
pseudocode found here:
https://en.wikipedia.org/wiki/Karger%27s_algorithm.
This function involves random choices, meaning it will not give
consistent outputs.
Args:
graph: A dictionary containing adacency lists for the graph.
Nodes must be strings.
Returns:
The cutset of the cut found by Karger's Algorithm.
>>> graph = {'0':['1'], '1':['0']}
>>> partition_graph(graph)
{('0', '1')}
"""
# Dict that maps contracted nodes to a list of all the nodes it "contains."
contracted_nodes = {node: {node} for node in graph}
graph_copy = {node: graph[node][:] for node in graph}
while len(graph_copy) > 2:
# Choose a random edge.
u = random.choice(list(graph_copy.keys()))
v = random.choice(graph_copy[u])
# Contract edge (u, v) to new node uv
uv = u + v
uv_neighbors = list(set(graph_copy[u] + graph_copy[v]))
uv_neighbors.remove(u)
uv_neighbors.remove(v)
graph_copy[uv] = uv_neighbors
for neighbor in uv_neighbors:
graph_copy[neighbor].append(uv)
contracted_nodes[uv] = set(contracted_nodes[u].union(contracted_nodes[v]))
# Remove nodes u and v.
del graph_copy[u]
del graph_copy[v]
for neighbor in uv_neighbors:
if u in graph_copy[neighbor]:
graph_copy[neighbor].remove(u)
if v in graph_copy[neighbor]:
graph_copy[neighbor].remove(v)
# Find cutset.
groups = [contracted_nodes[node] for node in graph_copy]
return {
(node, neighbor)
for node in groups[0]
for neighbor in graph[node]
if neighbor in groups[1]
}
if __name__ == "__main__":
print(partition_graph(TEST_GRAPH))
| Python/graphs/karger.py/0 | {
"file_path": "Python/graphs/karger.py",
"repo_id": "Python",
"token_count": 1168
} | 27 |
"""
This algorithm (k=33) was first reported by Dan Bernstein many years ago in comp.lang.c
Another version of this algorithm (now favored by Bernstein) uses xor:
hash(i) = hash(i - 1) * 33 ^ str[i];
First Magic constant 33:
It has never been adequately explained.
It's magic because it works better than many other constants, prime or not.
Second Magic Constant 5381:
1. odd number
2. prime number
3. deficient number
4. 001/010/100/000/101 b
source: http://www.cse.yorku.ca/~oz/hash.html
"""
def djb2(s: str) -> int:
"""
Implementation of djb2 hash algorithm that
is popular because of it's magic constants.
>>> djb2('Algorithms')
3782405311
>>> djb2('scramble bits')
1609059040
"""
hash_value = 5381
for x in s:
hash_value = ((hash_value << 5) + hash_value) + ord(x)
return hash_value & 0xFFFFFFFF
| Python/hashes/djb2.py/0 | {
"file_path": "Python/hashes/djb2.py",
"repo_id": "Python",
"token_count": 335
} | 28 |
import unittest
import pytest
from knapsack import greedy_knapsack as kp
class TestClass(unittest.TestCase):
"""
Test cases for knapsack
"""
def test_sorted(self):
"""
kp.calc_profit takes the required argument (profit, weight, max_weight)
and returns whether the answer matches to the expected ones
"""
profit = [10, 20, 30, 40, 50, 60]
weight = [2, 4, 6, 8, 10, 12]
max_weight = 100
assert kp.calc_profit(profit, weight, max_weight) == 210
def test_negative_max_weight(self):
"""
Returns ValueError for any negative max_weight value
:return: ValueError
"""
# profit = [10, 20, 30, 40, 50, 60]
# weight = [2, 4, 6, 8, 10, 12]
# max_weight = -15
pytest.raises(ValueError, match="max_weight must greater than zero.")
def test_negative_profit_value(self):
"""
Returns ValueError for any negative profit value in the list
:return: ValueError
"""
# profit = [10, -20, 30, 40, 50, 60]
# weight = [2, 4, 6, 8, 10, 12]
# max_weight = 15
pytest.raises(ValueError, match="Weight can not be negative.")
def test_negative_weight_value(self):
"""
Returns ValueError for any negative weight value in the list
:return: ValueError
"""
# profit = [10, 20, 30, 40, 50, 60]
# weight = [2, -4, 6, -8, 10, 12]
# max_weight = 15
pytest.raises(ValueError, match="Profit can not be negative.")
def test_null_max_weight(self):
"""
Returns ValueError for any zero max_weight value
:return: ValueError
"""
# profit = [10, 20, 30, 40, 50, 60]
# weight = [2, 4, 6, 8, 10, 12]
# max_weight = null
pytest.raises(ValueError, match="max_weight must greater than zero.")
def test_unequal_list_length(self):
"""
Returns IndexError if length of lists (profit and weight) are unequal.
:return: IndexError
"""
# profit = [10, 20, 30, 40, 50]
# weight = [2, 4, 6, 8, 10, 12]
# max_weight = 100
pytest.raises(IndexError, match="The length of profit and weight must be same.")
if __name__ == "__main__":
unittest.main()
| Python/knapsack/tests/test_greedy_knapsack.py/0 | {
"file_path": "Python/knapsack/tests/test_greedy_knapsack.py",
"repo_id": "Python",
"token_count": 1016
} | 29 |
import unittest
import numpy as np
import pytest
def schur_complement(
mat_a: np.ndarray,
mat_b: np.ndarray,
mat_c: np.ndarray,
pseudo_inv: np.ndarray | None = None,
) -> np.ndarray:
"""
Schur complement of a symmetric matrix X given as a 2x2 block matrix
consisting of matrices A, B and C.
Matrix A must be quadratic and non-singular.
In case A is singular, a pseudo-inverse may be provided using
the pseudo_inv argument.
Link to Wiki: https://en.wikipedia.org/wiki/Schur_complement
See also Convex Optimization โ Boyd and Vandenberghe, A.5.5
>>> import numpy as np
>>> a = np.array([[1, 2], [2, 1]])
>>> b = np.array([[0, 3], [3, 0]])
>>> c = np.array([[2, 1], [6, 3]])
>>> schur_complement(a, b, c)
array([[ 5., -5.],
[ 0., 6.]])
"""
shape_a = np.shape(mat_a)
shape_b = np.shape(mat_b)
shape_c = np.shape(mat_c)
if shape_a[0] != shape_b[0]:
msg = (
"Expected the same number of rows for A and B. "
f"Instead found A of size {shape_a} and B of size {shape_b}"
)
raise ValueError(msg)
if shape_b[1] != shape_c[1]:
msg = (
"Expected the same number of columns for B and C. "
f"Instead found B of size {shape_b} and C of size {shape_c}"
)
raise ValueError(msg)
a_inv = pseudo_inv
if a_inv is None:
try:
a_inv = np.linalg.inv(mat_a)
except np.linalg.LinAlgError:
raise ValueError(
"Input matrix A is not invertible. Cannot compute Schur complement."
)
return mat_c - mat_b.T @ a_inv @ mat_b
class TestSchurComplement(unittest.TestCase):
def test_schur_complement(self) -> None:
a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]])
b = np.array([[0, 3], [3, 0], [2, 3]])
c = np.array([[2, 1], [6, 3]])
s = schur_complement(a, b, c)
input_matrix = np.block([[a, b], [b.T, c]])
det_x = np.linalg.det(input_matrix)
det_a = np.linalg.det(a)
det_s = np.linalg.det(s)
assert np.is_close(det_x, det_a * det_s)
def test_improper_a_b_dimensions(self) -> None:
a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]])
b = np.array([[0, 3], [3, 0], [2, 3]])
c = np.array([[2, 1], [6, 3]])
with pytest.raises(ValueError):
schur_complement(a, b, c)
def test_improper_b_c_dimensions(self) -> None:
a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]])
b = np.array([[0, 3], [3, 0], [2, 3]])
c = np.array([[2, 1, 3], [6, 3, 5]])
with pytest.raises(ValueError):
schur_complement(a, b, c)
if __name__ == "__main__":
import doctest
doctest.testmod()
unittest.main()
| Python/linear_algebra/src/schur_complement.py/0 | {
"file_path": "Python/linear_algebra/src/schur_complement.py",
"repo_id": "Python",
"token_count": 1409
} | 30 |
import numpy as np
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
class GradientBoostingClassifier:
def __init__(self, n_estimators: int = 100, learning_rate: float = 0.1) -> None:
"""
Initialize a GradientBoostingClassifier.
Parameters:
- n_estimators (int): The number of weak learners to train.
- learning_rate (float): The learning rate for updating the model.
Attributes:
- n_estimators (int): The number of weak learners.
- learning_rate (float): The learning rate.
- models (list): A list to store the trained weak learners.
"""
self.n_estimators = n_estimators
self.learning_rate = learning_rate
self.models: list[tuple[DecisionTreeRegressor, float]] = []
def fit(self, features: np.ndarray, target: np.ndarray) -> None:
"""
Fit the GradientBoostingClassifier to the training data.
Parameters:
- features (np.ndarray): The training features.
- target (np.ndarray): The target values.
Returns:
None
>>> import numpy as np
>>> from sklearn.datasets import load_iris
>>> clf = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1)
>>> iris = load_iris()
>>> X, y = iris.data, iris.target
>>> clf.fit(X, y)
>>> # Check if the model is trained
>>> len(clf.models) == 100
True
"""
for _ in range(self.n_estimators):
# Calculate the pseudo-residuals
residuals = -self.gradient(target, self.predict(features))
# Fit a weak learner (e.g., decision tree) to the residuals
model = DecisionTreeRegressor(max_depth=1)
model.fit(features, residuals)
# Update the model by adding the weak learner with a learning rate
self.models.append((model, self.learning_rate))
def predict(self, features: np.ndarray) -> np.ndarray:
"""
Make predictions on input data.
Parameters:
- features (np.ndarray): The input data for making predictions.
Returns:
- np.ndarray: An array of binary predictions (-1 or 1).
>>> import numpy as np
>>> from sklearn.datasets import load_iris
>>> clf = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1)
>>> iris = load_iris()
>>> X, y = iris.data, iris.target
>>> clf.fit(X, y)
>>> y_pred = clf.predict(X)
>>> # Check if the predictions have the correct shape
>>> y_pred.shape == y.shape
True
"""
# Initialize predictions with zeros
predictions = np.zeros(features.shape[0])
for model, learning_rate in self.models:
predictions += learning_rate * model.predict(features)
return np.sign(predictions) # Convert to binary predictions (-1 or 1)
def gradient(self, target: np.ndarray, y_pred: np.ndarray) -> np.ndarray:
"""
Calculate the negative gradient (pseudo-residuals) for logistic loss.
Parameters:
- target (np.ndarray): The target values.
- y_pred (np.ndarray): The predicted values.
Returns:
- np.ndarray: An array of pseudo-residuals.
>>> import numpy as np
>>> clf = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1)
>>> target = np.array([0, 1, 0, 1])
>>> y_pred = np.array([0.2, 0.8, 0.3, 0.7])
>>> residuals = clf.gradient(target, y_pred)
>>> # Check if residuals have the correct shape
>>> residuals.shape == target.shape
True
"""
return -target / (1 + np.exp(target * y_pred))
if __name__ == "__main__":
iris = load_iris()
X, y = iris.data, iris.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
clf = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.2f}")
| Python/machine_learning/gradient_boosting_classifier.py/0 | {
"file_path": "Python/machine_learning/gradient_boosting_classifier.py",
"repo_id": "Python",
"token_count": 1810
} | 31 |
from sklearn.neural_network import MLPClassifier
X = [[0.0, 0.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0]]
y = [0, 1, 0, 0]
clf = MLPClassifier(
solver="lbfgs", alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1
)
clf.fit(X, y)
test = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0]]
Y = clf.predict(test)
def wrapper(y):
"""
>>> wrapper(Y)
[0, 0, 1]
"""
return list(y)
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python/machine_learning/multilayer_perceptron_classifier.py/0 | {
"file_path": "Python/machine_learning/multilayer_perceptron_classifier.py",
"repo_id": "Python",
"token_count": 240
} | 32 |
"""
In a multi-threaded download, this algorithm could be used to provide
each worker thread with a block of non-overlapping bytes to download.
For example:
for i in allocation_list:
requests.get(url,headers={'Range':f'bytes={i}'})
"""
from __future__ import annotations
def allocation_num(number_of_bytes: int, partitions: int) -> list[str]:
"""
Divide a number of bytes into x partitions.
:param number_of_bytes: the total of bytes.
:param partitions: the number of partition need to be allocated.
:return: list of bytes to be assigned to each worker thread
>>> allocation_num(16647, 4)
['1-4161', '4162-8322', '8323-12483', '12484-16647']
>>> allocation_num(50000, 5)
['1-10000', '10001-20000', '20001-30000', '30001-40000', '40001-50000']
>>> allocation_num(888, 999)
Traceback (most recent call last):
...
ValueError: partitions can not > number_of_bytes!
>>> allocation_num(888, -4)
Traceback (most recent call last):
...
ValueError: partitions must be a positive number!
"""
if partitions <= 0:
raise ValueError("partitions must be a positive number!")
if partitions > number_of_bytes:
raise ValueError("partitions can not > number_of_bytes!")
bytes_per_partition = number_of_bytes // partitions
allocation_list = []
for i in range(partitions):
start_bytes = i * bytes_per_partition + 1
end_bytes = (
number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition
)
allocation_list.append(f"{start_bytes}-{end_bytes}")
return allocation_list
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python/maths/allocation_number.py/0 | {
"file_path": "Python/maths/allocation_number.py",
"repo_id": "Python",
"token_count": 632
} | 33 |
def chebyshev_distance(point_a: list[float], point_b: list[float]) -> float:
"""
This function calculates the Chebyshev distance (also known as the
Chessboard distance) between two n-dimensional points represented as lists.
https://en.wikipedia.org/wiki/Chebyshev_distance
>>> chebyshev_distance([1.0, 1.0], [2.0, 2.0])
1.0
>>> chebyshev_distance([1.0, 1.0, 9.0], [2.0, 2.0, -5.2])
14.2
>>> chebyshev_distance([1.0], [2.0, 2.0])
Traceback (most recent call last):
...
ValueError: Both points must have the same dimension.
"""
if len(point_a) != len(point_b):
raise ValueError("Both points must have the same dimension.")
return max(abs(a - b) for a, b in zip(point_a, point_b))
| Python/maths/chebyshev_distance.py/0 | {
"file_path": "Python/maths/chebyshev_distance.py",
"repo_id": "Python",
"token_count": 302
} | 34 |
# Eulers Totient function finds the number of relative primes of a number n from 1 to n
def totient(n: int) -> list:
"""
>>> n = 10
>>> totient_calculation = totient(n)
>>> for i in range(1, n):
... print(f"{i} has {totient_calculation[i]} relative primes.")
1 has 0 relative primes.
2 has 1 relative primes.
3 has 2 relative primes.
4 has 2 relative primes.
5 has 4 relative primes.
6 has 2 relative primes.
7 has 6 relative primes.
8 has 4 relative primes.
9 has 6 relative primes.
"""
is_prime = [True for i in range(n + 1)]
totients = [i - 1 for i in range(n + 1)]
primes = []
for i in range(2, n + 1):
if is_prime[i]:
primes.append(i)
for j in range(len(primes)):
if i * primes[j] >= n:
break
is_prime[i * primes[j]] = False
if i % primes[j] == 0:
totients[i * primes[j]] = totients[i] * primes[j]
break
totients[i * primes[j]] = totients[i] * (primes[j] - 1)
return totients
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python/maths/eulers_totient.py/0 | {
"file_path": "Python/maths/eulers_totient.py",
"repo_id": "Python",
"token_count": 545
} | 35 |
"""
== Liouville Lambda Function ==
The Liouville Lambda function, denoted by ฮป(n)
and ฮป(n) is 1 if n is the product of an even number of prime numbers,
and -1 if it is the product of an odd number of primes.
https://en.wikipedia.org/wiki/Liouville_function
"""
# Author : Akshay Dubey (https://github.com/itsAkshayDubey)
from maths.prime_factors import prime_factors
def liouville_lambda(number: int) -> int:
"""
This functions takes an integer number as input.
returns 1 if n has even number of prime factors and -1 otherwise.
>>> liouville_lambda(10)
1
>>> liouville_lambda(11)
-1
>>> liouville_lambda(0)
Traceback (most recent call last):
...
ValueError: Input must be a positive integer
>>> liouville_lambda(-1)
Traceback (most recent call last):
...
ValueError: Input must be a positive integer
>>> liouville_lambda(11.0)
Traceback (most recent call last):
...
TypeError: Input value of [number=11.0] must be an integer
"""
if not isinstance(number, int):
msg = f"Input value of [number={number}] must be an integer"
raise TypeError(msg)
if number < 1:
raise ValueError("Input must be a positive integer")
return -1 if len(prime_factors(number)) % 2 else 1
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python/maths/liouville_lambda.py/0 | {
"file_path": "Python/maths/liouville_lambda.py",
"repo_id": "Python",
"token_count": 500
} | 36 |
from collections.abc import Callable
def bisection(function: Callable[[float], float], a: float, b: float) -> float:
"""
finds where function becomes 0 in [a,b] using bolzano
>>> bisection(lambda x: x ** 3 - 1, -5, 5)
1.0000000149011612
>>> bisection(lambda x: x ** 3 - 1, 2, 1000)
Traceback (most recent call last):
...
ValueError: could not find root in given interval.
>>> bisection(lambda x: x ** 2 - 4 * x + 3, 0, 2)
1.0
>>> bisection(lambda x: x ** 2 - 4 * x + 3, 2, 4)
3.0
>>> bisection(lambda x: x ** 2 - 4 * x + 3, 4, 1000)
Traceback (most recent call last):
...
ValueError: could not find root in given interval.
"""
start: float = a
end: float = b
if function(a) == 0: # one of the a or b is a root for the function
return a
elif function(b) == 0:
return b
elif (
function(a) * function(b) > 0
): # if none of these are root and they are both positive or negative,
# then this algorithm can't find the root
raise ValueError("could not find root in given interval.")
else:
mid: float = start + (end - start) / 2.0
while abs(start - mid) > 10**-7: # until precisely equals to 10^-7
if function(mid) == 0:
return mid
elif function(mid) * function(start) < 0:
end = mid
else:
start = mid
mid = start + (end - start) / 2.0
return mid
def f(x: float) -> float:
return x**3 - 2 * x - 5
if __name__ == "__main__":
print(bisection(f, 1, 1000))
import doctest
doctest.testmod()
| Python/maths/numerical_analysis/bisection.py/0 | {
"file_path": "Python/maths/numerical_analysis/bisection.py",
"repo_id": "Python",
"token_count": 721
} | 37 |
def perfect_cube(n: int) -> bool:
"""
Check if a number is a perfect cube or not.
>>> perfect_cube(27)
True
>>> perfect_cube(4)
False
"""
val = n ** (1 / 3)
return (val * val * val) == n
def perfect_cube_binary_search(n: int) -> bool:
"""
Check if a number is a perfect cube or not using binary search.
Time complexity : O(Log(n))
Space complexity: O(1)
>>> perfect_cube_binary_search(27)
True
>>> perfect_cube_binary_search(64)
True
>>> perfect_cube_binary_search(4)
False
>>> perfect_cube_binary_search("a")
Traceback (most recent call last):
...
TypeError: perfect_cube_binary_search() only accepts integers
>>> perfect_cube_binary_search(0.1)
Traceback (most recent call last):
...
TypeError: perfect_cube_binary_search() only accepts integers
"""
if not isinstance(n, int):
raise TypeError("perfect_cube_binary_search() only accepts integers")
if n < 0:
n = -n
left = 0
right = n
while left <= right:
mid = left + (right - left) // 2
if mid * mid * mid == n:
return True
elif mid * mid * mid < n:
left = mid + 1
else:
right = mid - 1
return False
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python/maths/perfect_cube.py/0 | {
"file_path": "Python/maths/perfect_cube.py",
"repo_id": "Python",
"token_count": 565
} | 38 |
"""
Created on Thu Oct 5 16:44:23 2017
@author: Christian Bender
This Python library contains some useful functions to deal with
prime numbers and whole numbers.
Overview:
is_prime(number)
sieve_er(N)
get_prime_numbers(N)
prime_factorization(number)
greatest_prime_factor(number)
smallest_prime_factor(number)
get_prime(n)
get_primes_between(pNumber1, pNumber2)
----
is_even(number)
is_odd(number)
kg_v(number1, number2) // least common multiple
get_divisors(number) // all divisors of 'number' inclusive 1, number
is_perfect_number(number)
NEW-FUNCTIONS
simplify_fraction(numerator, denominator)
factorial (n) // n!
fib (n) // calculate the n-th fibonacci term.
-----
goldbach(number) // Goldbach's assumption
"""
from math import sqrt
from maths.greatest_common_divisor import gcd_by_iterative
def is_prime(number: int) -> bool:
"""
input: positive integer 'number'
returns true if 'number' is prime otherwise false.
>>> is_prime(3)
True
>>> is_prime(10)
False
>>> is_prime(97)
True
>>> is_prime(9991)
False
>>> is_prime(-1)
Traceback (most recent call last):
...
AssertionError: 'number' must been an int and positive
>>> is_prime("test")
Traceback (most recent call last):
...
AssertionError: 'number' must been an int and positive
"""
# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and positive"
status = True
# 0 and 1 are none primes.
if number <= 1:
status = False
for divisor in range(2, int(round(sqrt(number))) + 1):
# if 'number' divisible by 'divisor' then sets 'status'
# of false and break up the loop.
if number % divisor == 0:
status = False
break
# precondition
assert isinstance(status, bool), "'status' must been from type bool"
return status
# ------------------------------------------
def sieve_er(n):
"""
input: positive integer 'N' > 2
returns a list of prime numbers from 2 up to N.
This function implements the algorithm called
sieve of erathostenes.
>>> sieve_er(8)
[2, 3, 5, 7]
>>> sieve_er(-1)
Traceback (most recent call last):
...
AssertionError: 'N' must been an int and > 2
>>> sieve_er("test")
Traceback (most recent call last):
...
AssertionError: 'N' must been an int and > 2
"""
# precondition
assert isinstance(n, int) and (n > 2), "'N' must been an int and > 2"
# beginList: contains all natural numbers from 2 up to N
begin_list = list(range(2, n + 1))
ans = [] # this list will be returns.
# actual sieve of erathostenes
for i in range(len(begin_list)):
for j in range(i + 1, len(begin_list)):
if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0):
begin_list[j] = 0
# filters actual prime numbers.
ans = [x for x in begin_list if x != 0]
# precondition
assert isinstance(ans, list), "'ans' must been from type list"
return ans
# --------------------------------
def get_prime_numbers(n):
"""
input: positive integer 'N' > 2
returns a list of prime numbers from 2 up to N (inclusive)
This function is more efficient as function 'sieveEr(...)'
>>> get_prime_numbers(8)
[2, 3, 5, 7]
>>> get_prime_numbers(-1)
Traceback (most recent call last):
...
AssertionError: 'N' must been an int and > 2
>>> get_prime_numbers("test")
Traceback (most recent call last):
...
AssertionError: 'N' must been an int and > 2
"""
# precondition
assert isinstance(n, int) and (n > 2), "'N' must been an int and > 2"
ans = []
# iterates over all numbers between 2 up to N+1
# if a number is prime then appends to list 'ans'
for number in range(2, n + 1):
if is_prime(number):
ans.append(number)
# precondition
assert isinstance(ans, list), "'ans' must been from type list"
return ans
# -----------------------------------------
def prime_factorization(number):
"""
input: positive integer 'number'
returns a list of the prime number factors of 'number'
>>> prime_factorization(0)
[0]
>>> prime_factorization(8)
[2, 2, 2]
>>> prime_factorization(287)
[7, 41]
>>> prime_factorization(-1)
Traceback (most recent call last):
...
AssertionError: 'number' must been an int and >= 0
>>> prime_factorization("test")
Traceback (most recent call last):
...
AssertionError: 'number' must been an int and >= 0
"""
# precondition
assert isinstance(number, int) and number >= 0, "'number' must been an int and >= 0"
ans = [] # this list will be returns of the function.
# potential prime number factors.
factor = 2
quotient = number
if number in {0, 1}:
ans.append(number)
# if 'number' not prime then builds the prime factorization of 'number'
elif not is_prime(number):
while quotient != 1:
if is_prime(factor) and (quotient % factor == 0):
ans.append(factor)
quotient /= factor
else:
factor += 1
else:
ans.append(number)
# precondition
assert isinstance(ans, list), "'ans' must been from type list"
return ans
# -----------------------------------------
def greatest_prime_factor(number):
"""
input: positive integer 'number' >= 0
returns the greatest prime number factor of 'number'
>>> greatest_prime_factor(0)
0
>>> greatest_prime_factor(8)
2
>>> greatest_prime_factor(287)
41
>>> greatest_prime_factor(-1)
Traceback (most recent call last):
...
AssertionError: 'number' must been an int and >= 0
>>> greatest_prime_factor("test")
Traceback (most recent call last):
...
AssertionError: 'number' must been an int and >= 0
"""
# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and >= 0"
ans = 0
# prime factorization of 'number'
prime_factors = prime_factorization(number)
ans = max(prime_factors)
# precondition
assert isinstance(ans, int), "'ans' must been from type int"
return ans
# ----------------------------------------------
def smallest_prime_factor(number):
"""
input: integer 'number' >= 0
returns the smallest prime number factor of 'number'
>>> smallest_prime_factor(0)
0
>>> smallest_prime_factor(8)
2
>>> smallest_prime_factor(287)
7
>>> smallest_prime_factor(-1)
Traceback (most recent call last):
...
AssertionError: 'number' must been an int and >= 0
>>> smallest_prime_factor("test")
Traceback (most recent call last):
...
AssertionError: 'number' must been an int and >= 0
"""
# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and >= 0"
ans = 0
# prime factorization of 'number'
prime_factors = prime_factorization(number)
ans = min(prime_factors)
# precondition
assert isinstance(ans, int), "'ans' must been from type int"
return ans
# ----------------------
def is_even(number):
"""
input: integer 'number'
returns true if 'number' is even, otherwise false.
>>> is_even(0)
True
>>> is_even(8)
True
>>> is_even(287)
False
>>> is_even(-1)
False
>>> is_even("test")
Traceback (most recent call last):
...
AssertionError: 'number' must been an int
"""
# precondition
assert isinstance(number, int), "'number' must been an int"
assert isinstance(number % 2 == 0, bool), "compare must been from type bool"
return number % 2 == 0
# ------------------------
def is_odd(number):
"""
input: integer 'number'
returns true if 'number' is odd, otherwise false.
>>> is_odd(0)
False
>>> is_odd(8)
False
>>> is_odd(287)
True
>>> is_odd(-1)
True
>>> is_odd("test")
Traceback (most recent call last):
...
AssertionError: 'number' must been an int
"""
# precondition
assert isinstance(number, int), "'number' must been an int"
assert isinstance(number % 2 != 0, bool), "compare must been from type bool"
return number % 2 != 0
# ------------------------
def goldbach(number):
"""
Goldbach's assumption
input: a even positive integer 'number' > 2
returns a list of two prime numbers whose sum is equal to 'number'
>>> goldbach(8)
[3, 5]
>>> goldbach(824)
[3, 821]
>>> goldbach(0)
Traceback (most recent call last):
...
AssertionError: 'number' must been an int, even and > 2
>>> goldbach(-1)
Traceback (most recent call last):
...
AssertionError: 'number' must been an int, even and > 2
>>> goldbach("test")
Traceback (most recent call last):
...
AssertionError: 'number' must been an int, even and > 2
"""
# precondition
assert (
isinstance(number, int) and (number > 2) and is_even(number)
), "'number' must been an int, even and > 2"
ans = [] # this list will returned
# creates a list of prime numbers between 2 up to 'number'
prime_numbers = get_prime_numbers(number)
len_pn = len(prime_numbers)
# run variable for while-loops.
i = 0
j = None
# exit variable. for break up the loops
loop = True
while i < len_pn and loop:
j = i + 1
while j < len_pn and loop:
if prime_numbers[i] + prime_numbers[j] == number:
loop = False
ans.append(prime_numbers[i])
ans.append(prime_numbers[j])
j += 1
i += 1
# precondition
assert (
isinstance(ans, list)
and (len(ans) == 2)
and (ans[0] + ans[1] == number)
and is_prime(ans[0])
and is_prime(ans[1])
), "'ans' must contains two primes. And sum of elements must been eq 'number'"
return ans
# ----------------------------------------------
def kg_v(number1, number2):
"""
Least common multiple
input: two positive integer 'number1' and 'number2'
returns the least common multiple of 'number1' and 'number2'
>>> kg_v(8,10)
40
>>> kg_v(824,67)
55208
>>> kg_v(1, 10)
10
>>> kg_v(0)
Traceback (most recent call last):
...
TypeError: kg_v() missing 1 required positional argument: 'number2'
>>> kg_v(10,-1)
Traceback (most recent call last):
...
AssertionError: 'number1' and 'number2' must been positive integer.
>>> kg_v("test","test2")
Traceback (most recent call last):
...
AssertionError: 'number1' and 'number2' must been positive integer.
"""
# precondition
assert (
isinstance(number1, int)
and isinstance(number2, int)
and (number1 >= 1)
and (number2 >= 1)
), "'number1' and 'number2' must been positive integer."
ans = 1 # actual answer that will be return.
# for kgV (x,1)
if number1 > 1 and number2 > 1:
# builds the prime factorization of 'number1' and 'number2'
prime_fac_1 = prime_factorization(number1)
prime_fac_2 = prime_factorization(number2)
elif number1 == 1 or number2 == 1:
prime_fac_1 = []
prime_fac_2 = []
ans = max(number1, number2)
count1 = 0
count2 = 0
done = [] # captured numbers int both 'primeFac1' and 'primeFac2'
# iterates through primeFac1
for n in prime_fac_1:
if n not in done:
if n in prime_fac_2:
count1 = prime_fac_1.count(n)
count2 = prime_fac_2.count(n)
for _ in range(max(count1, count2)):
ans *= n
else:
count1 = prime_fac_1.count(n)
for _ in range(count1):
ans *= n
done.append(n)
# iterates through primeFac2
for n in prime_fac_2:
if n not in done:
count2 = prime_fac_2.count(n)
for _ in range(count2):
ans *= n
done.append(n)
# precondition
assert isinstance(ans, int) and (
ans >= 0
), "'ans' must been from type int and positive"
return ans
# ----------------------------------
def get_prime(n):
"""
Gets the n-th prime number.
input: positive integer 'n' >= 0
returns the n-th prime number, beginning at index 0
>>> get_prime(0)
2
>>> get_prime(8)
23
>>> get_prime(824)
6337
>>> get_prime(-1)
Traceback (most recent call last):
...
AssertionError: 'number' must been a positive int
>>> get_prime("test")
Traceback (most recent call last):
...
AssertionError: 'number' must been a positive int
"""
# precondition
assert isinstance(n, int) and (n >= 0), "'number' must been a positive int"
index = 0
ans = 2 # this variable holds the answer
while index < n:
index += 1
ans += 1 # counts to the next number
# if ans not prime then
# runs to the next prime number.
while not is_prime(ans):
ans += 1
# precondition
assert isinstance(ans, int) and is_prime(
ans
), "'ans' must been a prime number and from type int"
return ans
# ---------------------------------------------------
def get_primes_between(p_number_1, p_number_2):
"""
input: prime numbers 'pNumber1' and 'pNumber2'
pNumber1 < pNumber2
returns a list of all prime numbers between 'pNumber1' (exclusive)
and 'pNumber2' (exclusive)
>>> get_primes_between(3, 67)
[5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61]
>>> get_primes_between(0)
Traceback (most recent call last):
...
TypeError: get_primes_between() missing 1 required positional argument: 'p_number_2'
>>> get_primes_between(0, 1)
Traceback (most recent call last):
...
AssertionError: The arguments must been prime numbers and 'pNumber1' < 'pNumber2'
>>> get_primes_between(-1, 3)
Traceback (most recent call last):
...
AssertionError: 'number' must been an int and positive
>>> get_primes_between("test","test")
Traceback (most recent call last):
...
AssertionError: 'number' must been an int and positive
"""
# precondition
assert (
is_prime(p_number_1) and is_prime(p_number_2) and (p_number_1 < p_number_2)
), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'"
number = p_number_1 + 1 # jump to the next number
ans = [] # this list will be returns.
# if number is not prime then
# fetch the next prime number.
while not is_prime(number):
number += 1
while number < p_number_2:
ans.append(number)
number += 1
# fetch the next prime number.
while not is_prime(number):
number += 1
# precondition
assert (
isinstance(ans, list)
and ans[0] != p_number_1
and ans[len(ans) - 1] != p_number_2
), "'ans' must been a list without the arguments"
# 'ans' contains not 'pNumber1' and 'pNumber2' !
return ans
# ----------------------------------------------------
def get_divisors(n):
"""
input: positive integer 'n' >= 1
returns all divisors of n (inclusive 1 and 'n')
>>> get_divisors(8)
[1, 2, 4, 8]
>>> get_divisors(824)
[1, 2, 4, 8, 103, 206, 412, 824]
>>> get_divisors(-1)
Traceback (most recent call last):
...
AssertionError: 'n' must been int and >= 1
>>> get_divisors("test")
Traceback (most recent call last):
...
AssertionError: 'n' must been int and >= 1
"""
# precondition
assert isinstance(n, int) and (n >= 1), "'n' must been int and >= 1"
ans = [] # will be returned.
for divisor in range(1, n + 1):
if n % divisor == 0:
ans.append(divisor)
# precondition
assert ans[0] == 1 and ans[len(ans) - 1] == n, "Error in function getDivisiors(...)"
return ans
# ----------------------------------------------------
def is_perfect_number(number):
"""
input: positive integer 'number' > 1
returns true if 'number' is a perfect number otherwise false.
>>> is_perfect_number(28)
True
>>> is_perfect_number(824)
False
>>> is_perfect_number(-1)
Traceback (most recent call last):
...
AssertionError: 'number' must been an int and >= 1
>>> is_perfect_number("test")
Traceback (most recent call last):
...
AssertionError: 'number' must been an int and >= 1
"""
# precondition
assert isinstance(number, int) and (
number > 1
), "'number' must been an int and >= 1"
divisors = get_divisors(number)
# precondition
assert (
isinstance(divisors, list)
and (divisors[0] == 1)
and (divisors[len(divisors) - 1] == number)
), "Error in help-function getDivisiors(...)"
# summed all divisors up to 'number' (exclusive), hence [:-1]
return sum(divisors[:-1]) == number
# ------------------------------------------------------------
def simplify_fraction(numerator, denominator):
"""
input: two integer 'numerator' and 'denominator'
assumes: 'denominator' != 0
returns: a tuple with simplify numerator and denominator.
>>> simplify_fraction(10, 20)
(1, 2)
>>> simplify_fraction(10, -1)
(10, -1)
>>> simplify_fraction("test","test")
Traceback (most recent call last):
...
AssertionError: The arguments must been from type int and 'denominator' != 0
"""
# precondition
assert (
isinstance(numerator, int)
and isinstance(denominator, int)
and (denominator != 0)
), "The arguments must been from type int and 'denominator' != 0"
# build the greatest common divisor of numerator and denominator.
gcd_of_fraction = gcd_by_iterative(abs(numerator), abs(denominator))
# precondition
assert (
isinstance(gcd_of_fraction, int)
and (numerator % gcd_of_fraction == 0)
and (denominator % gcd_of_fraction == 0)
), "Error in function gcd_by_iterative(...,...)"
return (numerator // gcd_of_fraction, denominator // gcd_of_fraction)
# -----------------------------------------------------------------
def factorial(n):
"""
input: positive integer 'n'
returns the factorial of 'n' (n!)
>>> factorial(0)
1
>>> factorial(20)
2432902008176640000
>>> factorial(-1)
Traceback (most recent call last):
...
AssertionError: 'n' must been a int and >= 0
>>> factorial("test")
Traceback (most recent call last):
...
AssertionError: 'n' must been a int and >= 0
"""
# precondition
assert isinstance(n, int) and (n >= 0), "'n' must been a int and >= 0"
ans = 1 # this will be return.
for factor in range(1, n + 1):
ans *= factor
return ans
# -------------------------------------------------------------------
def fib(n: int) -> int:
"""
input: positive integer 'n'
returns the n-th fibonacci term , indexing by 0
>>> fib(0)
1
>>> fib(5)
8
>>> fib(20)
10946
>>> fib(99)
354224848179261915075
>>> fib(-1)
Traceback (most recent call last):
...
AssertionError: 'n' must been an int and >= 0
>>> fib("test")
Traceback (most recent call last):
...
AssertionError: 'n' must been an int and >= 0
"""
# precondition
assert isinstance(n, int) and (n >= 0), "'n' must been an int and >= 0"
tmp = 0
fib1 = 1
ans = 1 # this will be return
for _ in range(n - 1):
tmp = ans
ans += fib1
fib1 = tmp
return ans
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python/maths/primelib.py/0 | {
"file_path": "Python/maths/primelib.py",
"repo_id": "Python",
"token_count": 8106
} | 39 |
"""
This is a pure Python implementation of the P-Series algorithm
https://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#P-series
For doctests run following command:
python -m doctest -v p_series.py
or
python3 -m doctest -v p_series.py
For manual testing run:
python3 p_series.py
"""
from __future__ import annotations
def p_series(nth_term: float | str, power: float | str) -> list[str]:
"""
Pure Python implementation of P-Series algorithm
:return: The P-Series starting from 1 to last (nth) term
Examples:
>>> p_series(5, 2)
['1', '1 / 4', '1 / 9', '1 / 16', '1 / 25']
>>> p_series(-5, 2)
[]
>>> p_series(5, -2)
['1', '1 / 0.25', '1 / 0.1111111111111111', '1 / 0.0625', '1 / 0.04']
>>> p_series("", 1000)
['']
>>> p_series(0, 0)
[]
>>> p_series(1, 1)
['1']
"""
if nth_term == "":
return [""]
nth_term = int(nth_term)
power = int(power)
series: list[str] = []
for temp in range(int(nth_term)):
series.append(f"1 / {pow(temp + 1, int(power))}" if series else "1")
return series
if __name__ == "__main__":
import doctest
doctest.testmod()
nth_term = int(input("Enter the last number (nth term) of the P-Series"))
power = int(input("Enter the power for P-Series"))
print("Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p")
print(p_series(nth_term, power))
| Python/maths/series/p_series.py/0 | {
"file_path": "Python/maths/series/p_series.py",
"repo_id": "Python",
"token_count": 591
} | 40 |
def is_happy_number(number: int) -> bool:
"""
A happy number is a number which eventually reaches 1 when replaced by the sum of
the square of each digit.
:param number: The number to check for happiness.
:return: True if the number is a happy number, False otherwise.
>>> is_happy_number(19)
True
>>> is_happy_number(2)
False
>>> is_happy_number(23)
True
>>> is_happy_number(1)
True
>>> is_happy_number(0)
Traceback (most recent call last):
...
ValueError: number=0 must be a positive integer
>>> is_happy_number(-19)
Traceback (most recent call last):
...
ValueError: number=-19 must be a positive integer
>>> is_happy_number(19.1)
Traceback (most recent call last):
...
ValueError: number=19.1 must be a positive integer
>>> is_happy_number("happy")
Traceback (most recent call last):
...
ValueError: number='happy' must be a positive integer
"""
if not isinstance(number, int) or number <= 0:
msg = f"{number=} must be a positive integer"
raise ValueError(msg)
seen = set()
while number != 1 and number not in seen:
seen.add(number)
number = sum(int(digit) ** 2 for digit in str(number))
return number == 1
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python/maths/special_numbers/happy_number.py/0 | {
"file_path": "Python/maths/special_numbers/happy_number.py",
"repo_id": "Python",
"token_count": 514
} | 41 |
"""
Calculates the nth number in Sylvester's sequence
Source:
https://en.wikipedia.org/wiki/Sylvester%27s_sequence
"""
def sylvester(number: int) -> int:
"""
:param number: nth number to calculate in the sequence
:return: the nth number in Sylvester's sequence
>>> sylvester(8)
113423713055421844361000443
>>> sylvester(-1)
Traceback (most recent call last):
...
ValueError: The input value of [n=-1] has to be > 0
>>> sylvester(8.0)
Traceback (most recent call last):
...
AssertionError: The input value of [n=8.0] is not an integer
"""
assert isinstance(number, int), f"The input value of [n={number}] is not an integer"
if number == 1:
return 2
elif number < 1:
msg = f"The input value of [n={number}] has to be > 0"
raise ValueError(msg)
else:
num = sylvester(number - 1)
lower = num - 1
upper = num
return lower * upper + 1
if __name__ == "__main__":
print(f"The 8th number in Sylvester's sequence: {sylvester(8)}")
| Python/maths/sylvester_sequence.py/0 | {
"file_path": "Python/maths/sylvester_sequence.py",
"repo_id": "Python",
"token_count": 443
} | 42 |
# https://www.chilimath.com/lessons/advanced-algebra/cramers-rule-with-two-variables
# https://en.wikipedia.org/wiki/Cramer%27s_rule
def cramers_rule_2x2(equation1: list[int], equation2: list[int]) -> tuple[float, float]:
"""
Solves the system of linear equation in 2 variables.
:param: equation1: list of 3 numbers
:param: equation2: list of 3 numbers
:return: String of result
input format : [a1, b1, d1], [a2, b2, d2]
determinant = [[a1, b1], [a2, b2]]
determinant_x = [[d1, b1], [d2, b2]]
determinant_y = [[a1, d1], [a2, d2]]
>>> cramers_rule_2x2([2, 3, 0], [5, 1, 0])
(0.0, 0.0)
>>> cramers_rule_2x2([0, 4, 50], [2, 0, 26])
(13.0, 12.5)
>>> cramers_rule_2x2([11, 2, 30], [1, 0, 4])
(4.0, -7.0)
>>> cramers_rule_2x2([4, 7, 1], [1, 2, 0])
(2.0, -1.0)
>>> cramers_rule_2x2([1, 2, 3], [2, 4, 6])
Traceback (most recent call last):
...
ValueError: Infinite solutions. (Consistent system)
>>> cramers_rule_2x2([1, 2, 3], [2, 4, 7])
Traceback (most recent call last):
...
ValueError: No solution. (Inconsistent system)
>>> cramers_rule_2x2([1, 2, 3], [11, 22])
Traceback (most recent call last):
...
ValueError: Please enter a valid equation.
>>> cramers_rule_2x2([0, 1, 6], [0, 0, 3])
Traceback (most recent call last):
...
ValueError: No solution. (Inconsistent system)
>>> cramers_rule_2x2([0, 0, 6], [0, 0, 3])
Traceback (most recent call last):
...
ValueError: Both a & b of two equations can't be zero.
>>> cramers_rule_2x2([1, 2, 3], [1, 2, 3])
Traceback (most recent call last):
...
ValueError: Infinite solutions. (Consistent system)
>>> cramers_rule_2x2([0, 4, 50], [0, 3, 99])
Traceback (most recent call last):
...
ValueError: No solution. (Inconsistent system)
"""
# Check if the input is valid
if not len(equation1) == len(equation2) == 3:
raise ValueError("Please enter a valid equation.")
if equation1[0] == equation1[1] == equation2[0] == equation2[1] == 0:
raise ValueError("Both a & b of two equations can't be zero.")
# Extract the coefficients
a1, b1, c1 = equation1
a2, b2, c2 = equation2
# Calculate the determinants of the matrices
determinant = a1 * b2 - a2 * b1
determinant_x = c1 * b2 - c2 * b1
determinant_y = a1 * c2 - a2 * c1
# Check if the system of linear equations has a solution (using Cramer's rule)
if determinant == 0:
if determinant_x == determinant_y == 0:
raise ValueError("Infinite solutions. (Consistent system)")
else:
raise ValueError("No solution. (Inconsistent system)")
else:
if determinant_x == determinant_y == 0:
# Trivial solution (Inconsistent system)
return (0.0, 0.0)
else:
x = determinant_x / determinant
y = determinant_y / determinant
# Non-Trivial Solution (Consistent system)
return (x, y)
| Python/matrix/cramers_rule_2x2.py/0 | {
"file_path": "Python/matrix/cramers_rule_2x2.py",
"repo_id": "Python",
"token_count": 1347
} | 43 |
"""
Testing here assumes that numpy and linalg is ALWAYS correct!!!!
If running from PyCharm you can place the following line in "Additional Arguments" for
the pytest run configuration
-vv -m mat_ops -p no:cacheprovider
"""
import logging
# standard libraries
import sys
import numpy as np
import pytest # type: ignore
# Custom/local libraries
from matrix import matrix_operation as matop
mat_a = [[12, 10], [3, 9]]
mat_b = [[3, 4], [7, 4]]
mat_c = [[3, 0, 2], [2, 0, -2], [0, 1, 1]]
mat_d = [[3, 0, -2], [2, 0, 2], [0, 1, 1]]
mat_e = [[3, 0, 2], [2, 0, -2], [0, 1, 1], [2, 0, -2]]
mat_f = [1]
mat_h = [2]
logger = logging.getLogger()
logger.level = logging.DEBUG
stream_handler = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
@pytest.mark.mat_ops()
@pytest.mark.parametrize(
("mat1", "mat2"), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)]
)
def test_addition(mat1, mat2):
if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2):
logger.info(f"\n\t{test_addition.__name__} returned integer")
with pytest.raises(TypeError):
matop.add(mat1, mat2)
elif (np.array(mat1)).shape == (np.array(mat2)).shape:
logger.info(f"\n\t{test_addition.__name__} with same matrix dims")
act = (np.array(mat1) + np.array(mat2)).tolist()
theo = matop.add(mat1, mat2)
assert theo == act
else:
logger.info(f"\n\t{test_addition.__name__} with different matrix dims")
with pytest.raises(ValueError):
matop.add(mat1, mat2)
@pytest.mark.mat_ops()
@pytest.mark.parametrize(
("mat1", "mat2"), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)]
)
def test_subtraction(mat1, mat2):
if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2):
logger.info(f"\n\t{test_subtraction.__name__} returned integer")
with pytest.raises(TypeError):
matop.subtract(mat1, mat2)
elif (np.array(mat1)).shape == (np.array(mat2)).shape:
logger.info(f"\n\t{test_subtraction.__name__} with same matrix dims")
act = (np.array(mat1) - np.array(mat2)).tolist()
theo = matop.subtract(mat1, mat2)
assert theo == act
else:
logger.info(f"\n\t{test_subtraction.__name__} with different matrix dims")
with pytest.raises(ValueError):
assert matop.subtract(mat1, mat2)
@pytest.mark.mat_ops()
@pytest.mark.parametrize(
("mat1", "mat2"), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)]
)
def test_multiplication(mat1, mat2):
if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2):
logger.info(f"\n\t{test_multiplication.__name__} returned integer")
with pytest.raises(TypeError):
matop.add(mat1, mat2)
elif (np.array(mat1)).shape == (np.array(mat2)).shape:
logger.info(f"\n\t{test_multiplication.__name__} meets dim requirements")
act = (np.matmul(mat1, mat2)).tolist()
theo = matop.multiply(mat1, mat2)
assert theo == act
else:
logger.info(
f"\n\t{test_multiplication.__name__} does not meet dim requirements"
)
with pytest.raises(ValueError):
assert matop.subtract(mat1, mat2)
@pytest.mark.mat_ops()
def test_scalar_multiply():
act = (3.5 * np.array(mat_a)).tolist()
theo = matop.scalar_multiply(mat_a, 3.5)
assert theo == act
@pytest.mark.mat_ops()
def test_identity():
act = (np.identity(5)).tolist()
theo = matop.identity(5)
assert theo == act
@pytest.mark.mat_ops()
@pytest.mark.parametrize("mat", [mat_a, mat_b, mat_c, mat_d, mat_e, mat_f])
def test_transpose(mat):
if (np.array(mat)).shape < (2, 2):
logger.info(f"\n\t{test_transpose.__name__} returned integer")
with pytest.raises(TypeError):
matop.transpose(mat)
else:
act = (np.transpose(mat)).tolist()
theo = matop.transpose(mat, return_map=False)
assert theo == act
| Python/matrix/tests/test_matrix_operation.py/0 | {
"file_path": "Python/matrix/tests/test_matrix_operation.py",
"repo_id": "Python",
"token_count": 1880
} | 44 |
"""
Squareplus Activation Function
Use Case: Squareplus designed to enhance positive values and suppress negative values.
For more detailed information, you can refer to the following link:
https://en.wikipedia.org/wiki/Rectifier_(neural_networks)#Squareplus
"""
import numpy as np
def squareplus(vector: np.ndarray, beta: float) -> np.ndarray:
"""
Implements the SquarePlus activation function.
Parameters:
vector (np.ndarray): The input array for the SquarePlus activation.
beta (float): size of the curved region
Returns:
np.ndarray: The input array after applying the SquarePlus activation.
Formula: f(x) = ( x + sqrt(x^2 + b) ) / 2
Examples:
>>> squareplus(np.array([2.3, 0.6, -2, -3.8]), beta=2)
array([2.5 , 1.06811457, 0.22474487, 0.12731349])
>>> squareplus(np.array([-9.2, -0.3, 0.45, -4.56]), beta=3)
array([0.0808119 , 0.72891979, 1.11977651, 0.15893419])
"""
return (vector + np.sqrt(vector**2 + beta)) / 2
if __name__ == "__main__":
import doctest
doctest.testmod()
| Python/neural_network/activation_functions/squareplus.py/0 | {
"file_path": "Python/neural_network/activation_functions/squareplus.py",
"repo_id": "Python",
"token_count": 410
} | 45 |
"""
This is a pure Python implementation of the Graham scan algorithm
Source: https://en.wikipedia.org/wiki/Graham_scan
For doctests run following command:
python3 -m doctest -v graham_scan.py
"""
from __future__ import annotations
from collections import deque
from enum import Enum
from math import atan2, degrees
from sys import maxsize
# traversal from the lowest and the most left point in anti-clockwise direction
# if direction gets right, the previous point is not the convex hull.
class Direction(Enum):
left = 1
straight = 2
right = 3
def __repr__(self):
return f"{self.__class__.__name__}.{self.name}"
def angle_comparer(point: tuple[int, int], minx: int, miny: int) -> float:
"""Return the angle toward to point from (minx, miny)
:param point: The target point
minx: The starting point's x
miny: The starting point's y
:return: the angle
Examples:
>>> angle_comparer((1,1), 0, 0)
45.0
>>> angle_comparer((100,1), 10, 10)
-5.710593137499642
>>> angle_comparer((5,5), 2, 3)
33.690067525979785
"""
# sort the points accorgind to the angle from the lowest and the most left point
x, y = point
return degrees(atan2(y - miny, x - minx))
def check_direction(
starting: tuple[int, int], via: tuple[int, int], target: tuple[int, int]
) -> Direction:
"""Return the direction toward to the line from via to target from starting
:param starting: The starting point
via: The via point
target: The target point
:return: the Direction
Examples:
>>> check_direction((1,1), (2,2), (3,3))
Direction.straight
>>> check_direction((60,1), (-50,199), (30,2))
Direction.left
>>> check_direction((0,0), (5,5), (10,0))
Direction.right
"""
x0, y0 = starting
x1, y1 = via
x2, y2 = target
via_angle = degrees(atan2(y1 - y0, x1 - x0))
via_angle %= 360
target_angle = degrees(atan2(y2 - y0, x2 - x0))
target_angle %= 360
# t-
# \ \
# \ v
# \|
# s
# via_angle is always lower than target_angle, if direction is left.
# If they are same, it means they are on a same line of convex hull.
if target_angle > via_angle:
return Direction.left
elif target_angle == via_angle:
return Direction.straight
else:
return Direction.right
def graham_scan(points: list[tuple[int, int]]) -> list[tuple[int, int]]:
"""Pure implementation of graham scan algorithm in Python
:param points: The unique points on coordinates.
:return: The points on convex hell.
Examples:
>>> graham_scan([(9, 6), (3, 1), (0, 0), (5, 5), (5, 2), (7, 0), (3, 3), (1, 4)])
[(0, 0), (7, 0), (9, 6), (5, 5), (1, 4)]
>>> graham_scan([(0, 0), (1, 0), (1, 1), (0, 1)])
[(0, 0), (1, 0), (1, 1), (0, 1)]
>>> graham_scan([(0, 0), (1, 1), (2, 2), (3, 3), (-1, 2)])
[(0, 0), (1, 1), (2, 2), (3, 3), (-1, 2)]
>>> graham_scan([(-100, 20), (99, 3), (1, 10000001), (5133186, -25), (-66, -4)])
[(5133186, -25), (1, 10000001), (-100, 20), (-66, -4)]
"""
if len(points) <= 2:
# There is no convex hull
raise ValueError("graham_scan: argument must contain more than 3 points.")
if len(points) == 3:
return points
# find the lowest and the most left point
minidx = 0
miny, minx = maxsize, maxsize
for i, point in enumerate(points):
x = point[0]
y = point[1]
if y < miny:
miny = y
minx = x
minidx = i
if y == miny and x < minx:
minx = x
minidx = i
# remove the lowest and the most left point from points for preparing for sort
points.pop(minidx)
sorted_points = sorted(points, key=lambda point: angle_comparer(point, minx, miny))
# This insert actually costs complexity,
# and you should instead add (minx, miny) into stack later.
# I'm using insert just for easy understanding.
sorted_points.insert(0, (minx, miny))
stack: deque[tuple[int, int]] = deque()
stack.append(sorted_points[0])
stack.append(sorted_points[1])
stack.append(sorted_points[2])
# The first 3 points lines are towards the left because we sort them by their angle
# from minx, miny.
current_direction = Direction.left
for i in range(3, len(sorted_points)):
while True:
starting = stack[-2]
via = stack[-1]
target = sorted_points[i]
next_direction = check_direction(starting, via, target)
if next_direction == Direction.left:
current_direction = Direction.left
break
if next_direction == Direction.straight:
if current_direction == Direction.left:
# We keep current_direction as left.
# Because if the straight line keeps as straight,
# we want to know if this straight line is towards left.
break
elif current_direction == Direction.right:
# If the straight line is towards right,
# every previous points on that straight line is not convex hull.
stack.pop()
if next_direction == Direction.right:
stack.pop()
stack.append(sorted_points[i])
return list(stack)
| Python/other/graham_scan.py/0 | {
"file_path": "Python/other/graham_scan.py",
"repo_id": "Python",
"token_count": 2295
} | 46 |
def apply_table(inp, table):
"""
>>> apply_table("0123456789", list(range(10)))
'9012345678'
>>> apply_table("0123456789", list(range(9, -1, -1)))
'8765432109'
"""
res = ""
for i in table:
res += inp[i - 1]
return res
def left_shift(data):
"""
>>> left_shift("0123456789")
'1234567890'
"""
return data[1:] + data[0]
def xor(a, b):
"""
>>> xor("01010101", "00001111")
'01011010'
"""
res = ""
for i in range(len(a)):
if a[i] == b[i]:
res += "0"
else:
res += "1"
return res
def apply_sbox(s, data):
row = int("0b" + data[0] + data[-1], 2)
col = int("0b" + data[1:3], 2)
return bin(s[row][col])[2:]
def function(expansion, s0, s1, key, message):
left = message[:4]
right = message[4:]
temp = apply_table(right, expansion)
temp = xor(temp, key)
l = apply_sbox(s0, temp[:4]) # noqa: E741
r = apply_sbox(s1, temp[4:])
l = "0" * (2 - len(l)) + l # noqa: E741
r = "0" * (2 - len(r)) + r
temp = apply_table(l + r, p4_table)
temp = xor(left, temp)
return temp + right
if __name__ == "__main__":
key = input("Enter 10 bit key: ")
message = input("Enter 8 bit message: ")
p8_table = [6, 3, 7, 4, 8, 5, 10, 9]
p10_table = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6]
p4_table = [2, 4, 3, 1]
IP = [2, 6, 3, 1, 4, 8, 5, 7]
IP_inv = [4, 1, 3, 5, 7, 2, 8, 6]
expansion = [4, 1, 2, 3, 2, 3, 4, 1]
s0 = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]]
s1 = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]]
# key generation
temp = apply_table(key, p10_table)
left = temp[:5]
right = temp[5:]
left = left_shift(left)
right = left_shift(right)
key1 = apply_table(left + right, p8_table)
left = left_shift(left)
right = left_shift(right)
left = left_shift(left)
right = left_shift(right)
key2 = apply_table(left + right, p8_table)
# encryption
temp = apply_table(message, IP)
temp = function(expansion, s0, s1, key1, temp)
temp = temp[4:] + temp[:4]
temp = function(expansion, s0, s1, key2, temp)
CT = apply_table(temp, IP_inv)
print("Cipher text is:", CT)
# decryption
temp = apply_table(CT, IP)
temp = function(expansion, s0, s1, key2, temp)
temp = temp[4:] + temp[:4]
temp = function(expansion, s0, s1, key1, temp)
PT = apply_table(temp, IP_inv)
print("Plain text after decypting is:", PT)
| Python/other/sdes.py/0 | {
"file_path": "Python/other/sdes.py",
"repo_id": "Python",
"token_count": 1248
} | 47 |
"""
The root-mean-square speed is essential in measuring the average speed of particles
contained in a gas, defined as,
-----------------
| Vrms = โ3RT/M |
-----------------
In Kinetic Molecular Theory, gasified particles are in a condition of constant random
motion; each particle moves at a completely different pace, perpetually clashing and
changing directions consistently velocity is used to describe the movement of gas
particles, thereby taking into account both speed and direction. Although the velocity
of gaseous particles is constantly changing, the distribution of velocities does not
change.
We cannot gauge the velocity of every individual particle, thus we frequently reason
in terms of the particles average behavior. Particles moving in opposite directions
have velocities of opposite signs. Since gas particles are in random motion, it's
plausible that there'll be about as several moving in one direction as within the other
way, which means that the average velocity for a collection of gas particles equals
zero; as this value is unhelpful, the average of velocities can be determined using an
alternative method.
"""
UNIVERSAL_GAS_CONSTANT = 8.3144598
def rms_speed_of_molecule(temperature: float, molar_mass: float) -> float:
"""
>>> rms_speed_of_molecule(100, 2)
35.315279554323226
>>> rms_speed_of_molecule(273, 12)
23.821458421977443
"""
if temperature < 0:
raise Exception("Temperature cannot be less than 0 K")
if molar_mass <= 0:
raise Exception("Molar mass cannot be less than or equal to 0 kg/mol")
else:
return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5
if __name__ == "__main__":
import doctest
# run doctest
doctest.testmod()
# example
temperature = 300
molar_mass = 28
vrms = rms_speed_of_molecule(temperature, molar_mass)
print(f"Vrms of Nitrogen gas at 300 K is {vrms} m/s")
| Python/physics/rms_speed_of_molecule.py/0 | {
"file_path": "Python/physics/rms_speed_of_molecule.py",
"repo_id": "Python",
"token_count": 583
} | 48 |
"""
Project Euler Problem 2: https://projecteuler.net/problem=2
Even Fibonacci Numbers
Each new term in the Fibonacci sequence is generated by adding the previous
two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
References:
- https://en.wikipedia.org/wiki/Fibonacci_number
"""
def solution(n: int = 4000000) -> int:
"""
Returns the sum of all even fibonacci sequence elements that are lower
or equal to n.
>>> solution(10)
10
>>> solution(15)
10
>>> solution(2)
2
>>> solution(1)
0
>>> solution(34)
44
"""
i = 1
j = 2
total = 0
while j <= n:
if j % 2 == 0:
total += j
i, j = j, i + j
return total
if __name__ == "__main__":
print(f"{solution() = }")
| Python/project_euler/problem_002/sol1.py/0 | {
"file_path": "Python/project_euler/problem_002/sol1.py",
"repo_id": "Python",
"token_count": 375
} | 49 |
"""
Project Euler Problem 6: https://projecteuler.net/problem=6
Sum square difference
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten
natural numbers and the square of the sum is 3025 - 385 = 2640.
Find the difference between the sum of the squares of the first one
hundred natural numbers and the square of the sum.
"""
def solution(n: int = 100) -> int:
"""
Returns the difference between the sum of the squares of the first n
natural numbers and the square of the sum.
>>> solution(10)
2640
>>> solution(15)
13160
>>> solution(20)
41230
>>> solution(50)
1582700
"""
sum_of_squares = 0
sum_of_ints = 0
for i in range(1, n + 1):
sum_of_squares += i**2
sum_of_ints += i
return sum_of_ints**2 - sum_of_squares
if __name__ == "__main__":
print(f"{solution() = }")
| Python/project_euler/problem_006/sol1.py/0 | {
"file_path": "Python/project_euler/problem_006/sol1.py",
"repo_id": "Python",
"token_count": 391
} | 50 |
"""
Problem 14: https://projecteuler.net/problem=14
Collatz conjecture: start with any positive integer n. Next term obtained from
the previous term as follows:
If the previous term is even, the next term is one half the previous term.
If the previous term is odd, the next term is 3 times the previous term plus 1.
The conjecture states the sequence will always reach 1 regardless of starting
n.
Problem Statement:
The following iterative sequence is defined for the set of positive integers:
n โ n/2 (n is even)
n โ 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 โ 40 โ 20 โ 10 โ 5 โ 16 โ 8 โ 4 โ 2 โ 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains
10 terms. Although it has not been proved yet (Collatz Problem), it is thought
that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
"""
from __future__ import annotations
COLLATZ_SEQUENCE_LENGTHS = {1: 1}
def collatz_sequence_length(n: int) -> int:
"""Returns the Collatz sequence length for n."""
if n in COLLATZ_SEQUENCE_LENGTHS:
return COLLATZ_SEQUENCE_LENGTHS[n]
next_n = n // 2 if n % 2 == 0 else 3 * n + 1
sequence_length = collatz_sequence_length(next_n) + 1
COLLATZ_SEQUENCE_LENGTHS[n] = sequence_length
return sequence_length
def solution(n: int = 1000000) -> int:
"""Returns the number under n that generates the longest Collatz sequence.
>>> solution(1000000)
837799
>>> solution(200)
171
>>> solution(5000)
3711
>>> solution(15000)
13255
"""
result = max((collatz_sequence_length(i), i) for i in range(1, n))
return result[1]
if __name__ == "__main__":
print(solution(int(input().strip())))
| Python/project_euler/problem_014/sol2.py/0 | {
"file_path": "Python/project_euler/problem_014/sol2.py",
"repo_id": "Python",
"token_count": 593
} | 51 |
"""
Problem 20: https://projecteuler.net/problem=20
n! means n ร (n โ 1) ร ... ร 3 ร 2 ร 1
For example, 10! = 10 ร 9 ร ... ร 3 ร 2 ร 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
"""
from math import factorial
def solution(num: int = 100) -> int:
"""Returns the sum of the digits in the factorial of num
>>> solution(1000)
10539
>>> solution(200)
1404
>>> solution(100)
648
>>> solution(50)
216
>>> solution(10)
27
>>> solution(5)
3
>>> solution(3)
6
>>> solution(2)
2
>>> solution(1)
1
>>> solution(0)
1
"""
return sum(map(int, str(factorial(num))))
if __name__ == "__main__":
print(solution(int(input("Enter the Number: ").strip())))
| Python/project_euler/problem_020/sol3.py/0 | {
"file_path": "Python/project_euler/problem_020/sol3.py",
"repo_id": "Python",
"token_count": 343
} | 52 |
"""
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):
if 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/project_euler/problem_033/sol1.py/0 | {
"file_path": "Python/project_euler/problem_033/sol1.py",
"repo_id": "Python",
"token_count": 753
} | 53 |
"""
Pandigital prime
Problem 41: https://projecteuler.net/problem=41
We shall say that an n-digit number is pandigital if it makes use of all the digits
1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
All pandigital numbers except for 1, 4 ,7 pandigital numbers are divisible by 3.
So we will check only 7 digit pandigital numbers to obtain the largest possible
pandigital prime.
"""
from __future__ import annotations
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 solution(n: int = 7) -> int:
"""
Returns the maximum pandigital prime number of length n.
If there are none, then it will return 0.
>>> solution(2)
0
>>> solution(4)
4231
>>> solution(7)
7652413
"""
pandigital_str = "".join(str(i) for i in range(1, n + 1))
perm_list = [int("".join(i)) for i in permutations(pandigital_str, n)]
pandigitals = [num for num in perm_list if is_prime(num)]
return max(pandigitals) if pandigitals else 0
if __name__ == "__main__":
print(f"{solution() = }")
| Python/project_euler/problem_041/sol1.py/0 | {
"file_path": "Python/project_euler/problem_041/sol1.py",
"repo_id": "Python",
"token_count": 775
} | 54 |
"""
Project Euler Problem 72: https://projecteuler.net/problem=72
Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1,
it is called a reduced proper fraction.
If we list the set of reduced proper fractions for d โค 8 in ascending order of size,
we get:
1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2,
4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8
It can be seen that there are 21 elements in this set.
How many elements would be contained in the set of reduced proper fractions
for d โค 1,000,000?
"""
def solution(limit: int = 1000000) -> int:
"""
Return the number of reduced proper fractions with denominator less than limit.
>>> solution(8)
21
>>> solution(1000)
304191
"""
primes = set(range(3, limit, 2))
primes.add(2)
for p in range(3, limit, 2):
if p not in primes:
continue
primes.difference_update(set(range(p * p, limit, p)))
phi = [float(n) for n in range(limit + 1)]
for p in primes:
for n in range(p, limit + 1, p):
phi[n] *= 1 - 1 / p
return int(sum(phi[2:]))
if __name__ == "__main__":
print(f"{solution() = }")
| Python/project_euler/problem_072/sol2.py/0 | {
"file_path": "Python/project_euler/problem_072/sol2.py",
"repo_id": "Python",
"token_count": 502
} | 55 |
"""
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/project_euler/problem_087/sol1.py/0 | {
"file_path": "Python/project_euler/problem_087/sol1.py",
"repo_id": "Python",
"token_count": 626
} | 56 |
"""
A pure implementation of Dutch national flag (DNF) sort algorithm in Python.
Dutch National Flag algorithm is an algorithm originally designed by Edsger Dijkstra.
It is the most optimal sort for 3 unique values (eg. 0, 1, 2) in a sequence. DNF can
sort a sequence of n size with [0 <= a[i] <= 2] at guaranteed O(n) complexity in a
single pass.
The flag of the Netherlands consists of three colors: white, red, and blue.
The task is to randomly arrange balls of white, red, and blue in such a way that balls
of the same color are placed together. DNF sorts a sequence of 0, 1, and 2's in linear
time that does not consume any extra space. This algorithm can be implemented only on
a sequence that contains three unique elements.
1) Time complexity is O(n).
2) Space complexity is O(1).
More info on: https://en.wikipedia.org/wiki/Dutch_national_flag_problem
For doctests run following command:
python3 -m doctest -v dutch_national_flag_sort.py
For manual testing run:
python dnf_sort.py
"""
# Python program to sort a sequence containing only 0, 1 and 2 in a single pass.
red = 0 # The first color of the flag.
white = 1 # The second color of the flag.
blue = 2 # The third color of the flag.
colors = (red, white, blue)
def dutch_national_flag_sort(sequence: list) -> list:
"""
A pure Python implementation of Dutch National Flag sort algorithm.
:param data: 3 unique integer values (e.g., 0, 1, 2) in an sequence
:return: The same collection in ascending order
>>> dutch_national_flag_sort([])
[]
>>> dutch_national_flag_sort([0])
[0]
>>> dutch_national_flag_sort([2, 1, 0, 0, 1, 2])
[0, 0, 1, 1, 2, 2]
>>> dutch_national_flag_sort([0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1])
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2]
>>> dutch_national_flag_sort("abacab")
Traceback (most recent call last):
...
ValueError: The elements inside the sequence must contains only (0, 1, 2) values
>>> dutch_national_flag_sort("Abacab")
Traceback (most recent call last):
...
ValueError: The elements inside the sequence must contains only (0, 1, 2) values
>>> dutch_national_flag_sort([3, 2, 3, 1, 3, 0, 3])
Traceback (most recent call last):
...
ValueError: The elements inside the sequence must contains only (0, 1, 2) values
>>> dutch_national_flag_sort([-1, 2, -1, 1, -1, 0, -1])
Traceback (most recent call last):
...
ValueError: The elements inside the sequence must contains only (0, 1, 2) values
>>> dutch_national_flag_sort([1.1, 2, 1.1, 1, 1.1, 0, 1.1])
Traceback (most recent call last):
...
ValueError: The elements inside the sequence must contains only (0, 1, 2) values
"""
if not sequence:
return []
if len(sequence) == 1:
return list(sequence)
low = 0
high = len(sequence) - 1
mid = 0
while mid <= high:
if sequence[mid] == colors[0]:
sequence[low], sequence[mid] = sequence[mid], sequence[low]
low += 1
mid += 1
elif sequence[mid] == colors[1]:
mid += 1
elif sequence[mid] == colors[2]:
sequence[mid], sequence[high] = sequence[high], sequence[mid]
high -= 1
else:
msg = f"The elements inside the sequence must contains only {colors} values"
raise ValueError(msg)
return sequence
if __name__ == "__main__":
import doctest
doctest.testmod()
user_input = input("Enter numbers separated by commas:\n").strip()
unsorted = [int(item.strip()) for item in user_input.split(",")]
print(f"{dutch_national_flag_sort(unsorted)}")
| Python/sorts/dutch_national_flag_sort.py/0 | {
"file_path": "Python/sorts/dutch_national_flag_sort.py",
"repo_id": "Python",
"token_count": 1340
} | 57 |
"""
This is a pure Python implementation of the pancake sort algorithm
For doctests run following command:
python3 -m doctest -v pancake_sort.py
or
python -m doctest -v pancake_sort.py
For manual testing run:
python pancake_sort.py
"""
def pancake_sort(arr):
"""Sort Array with Pancake Sort.
:param arr: Collection containing comparable items
:return: Collection ordered in ascending order of items
Examples:
>>> pancake_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> pancake_sort([])
[]
>>> pancake_sort([-2, -5, -45])
[-45, -5, -2]
"""
cur = len(arr)
while cur > 1:
# Find the maximum number in arr
mi = arr.index(max(arr[0:cur]))
# Reverse from 0 to mi
arr = arr[mi::-1] + arr[mi + 1 : len(arr)]
# Reverse whole list
arr = arr[cur - 1 :: -1] + arr[cur : len(arr)]
cur -= 1
return arr
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(pancake_sort(unsorted))
| Python/sorts/pancake_sort.py/0 | {
"file_path": "Python/sorts/pancake_sort.py",
"repo_id": "Python",
"token_count": 439
} | 58 |
def binary_search(lst, item, start, end):
if start == end:
return start if lst[start] > item else start + 1
if start > end:
return start
mid = (start + end) // 2
if lst[mid] < item:
return binary_search(lst, item, mid + 1, end)
elif lst[mid] > item:
return binary_search(lst, item, start, mid - 1)
else:
return mid
def insertion_sort(lst):
length = len(lst)
for index in range(1, length):
value = lst[index]
pos = binary_search(lst, value, 0, index - 1)
lst = lst[:pos] + [value] + lst[pos:index] + lst[index + 1 :]
return lst
def merge(left, right):
if not left:
return right
if not right:
return left
if left[0] < right[0]:
return [left[0], *merge(left[1:], right)]
return [right[0], *merge(left, right[1:])]
def tim_sort(lst):
"""
>>> tim_sort("Python")
['P', 'h', 'n', 'o', 't', 'y']
>>> tim_sort((1.1, 1, 0, -1, -1.1))
[-1.1, -1, 0, 1, 1.1]
>>> tim_sort(list(reversed(list(range(7)))))
[0, 1, 2, 3, 4, 5, 6]
>>> tim_sort([3, 2, 1]) == insertion_sort([3, 2, 1])
True
>>> tim_sort([3, 2, 1]) == sorted([3, 2, 1])
True
"""
length = len(lst)
runs, sorted_runs = [], []
new_run = [lst[0]]
sorted_array = []
i = 1
while i < length:
if lst[i] < lst[i - 1]:
runs.append(new_run)
new_run = [lst[i]]
else:
new_run.append(lst[i])
i += 1
runs.append(new_run)
for run in runs:
sorted_runs.append(insertion_sort(run))
for run in sorted_runs:
sorted_array = merge(sorted_array, run)
return sorted_array
def main():
lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
sorted_lst = tim_sort(lst)
print(sorted_lst)
if __name__ == "__main__":
main()
| Python/sorts/tim_sort.py/0 | {
"file_path": "Python/sorts/tim_sort.py",
"repo_id": "Python",
"token_count": 931
} | 59 |
from string import ascii_lowercase, ascii_uppercase
def capitalize(sentence: str) -> str:
"""
Capitalizes the first letter of a sentence or word.
>>> capitalize("hello world")
'Hello world'
>>> capitalize("123 hello world")
'123 hello world'
>>> capitalize(" hello world")
' hello world'
>>> capitalize("a")
'A'
>>> capitalize("")
''
"""
if not sentence:
return ""
# Create a dictionary that maps lowercase letters to uppercase letters
# Capitalize the first character if it's a lowercase letter
# Concatenate the capitalized character with the rest of the string
lower_to_upper = dict(zip(ascii_lowercase, ascii_uppercase))
return lower_to_upper.get(sentence[0], sentence[0]) + sentence[1:]
if __name__ == "__main__":
from doctest import testmod
testmod()
| Python/strings/capitalize.py/0 | {
"file_path": "Python/strings/capitalize.py",
"repo_id": "Python",
"token_count": 298
} | 60 |
import re
def is_sri_lankan_phone_number(phone: str) -> bool:
"""
Determine whether the string is a valid sri lankan mobile phone number or not
References: https://aye.sh/blog/sri-lankan-phone-number-regex
>>> is_sri_lankan_phone_number("+94773283048")
True
>>> is_sri_lankan_phone_number("+9477-3283048")
True
>>> is_sri_lankan_phone_number("0718382399")
True
>>> is_sri_lankan_phone_number("0094702343221")
True
>>> is_sri_lankan_phone_number("075 3201568")
True
>>> is_sri_lankan_phone_number("07779209245")
False
>>> is_sri_lankan_phone_number("0957651234")
False
"""
pattern = re.compile(r"^(?:0|94|\+94|0{2}94)7(0|1|2|4|5|6|7|8)(-| |)\d{7}$")
return bool(re.search(pattern, phone))
if __name__ == "__main__":
phone = "0094702343221"
print(is_sri_lankan_phone_number(phone))
| Python/strings/is_srilankan_phone_number.py/0 | {
"file_path": "Python/strings/is_srilankan_phone_number.py",
"repo_id": "Python",
"token_count": 410
} | 61 |
def reverse_letters(sentence: str, length: int = 0) -> str:
"""
Reverse all words that are longer than the given length of characters in a sentence.
If unspecified, length is taken as 0
>>> reverse_letters("Hey wollef sroirraw", 3)
'Hey fellow warriors'
>>> reverse_letters("nohtyP is nohtyP", 2)
'Python is Python'
>>> reverse_letters("1 12 123 1234 54321 654321", 0)
'1 21 321 4321 12345 123456'
>>> reverse_letters("racecar")
'racecar'
"""
return " ".join(
"".join(word[::-1]) if len(word) > length else word for word in sentence.split()
)
if __name__ == "__main__":
import doctest
doctest.testmod()
print(reverse_letters("Hey wollef sroirraw"))
| Python/strings/reverse_letters.py/0 | {
"file_path": "Python/strings/reverse_letters.py",
"repo_id": "Python",
"token_count": 277
} | 62 |
"""
Scrape the price and pharmacy name for a prescription drug from rx site
after providing the drug name and zipcode.
"""
from urllib.error import HTTPError
from bs4 import BeautifulSoup
from requests import exceptions, get
BASE_URL = "https://www.wellrx.com/prescriptions/{0}/{1}/?freshSearch=true"
def fetch_pharmacy_and_price_list(drug_name: str, zip_code: str) -> list | None:
"""[summary]
This function will take input of drug name and zipcode,
then request to the BASE_URL site.
Get the page data and scrape it to the generate the
list of lowest prices for the prescription drug.
Args:
drug_name (str): [Drug name]
zip_code(str): [Zip code]
Returns:
list: [List of pharmacy name and price]
>>> fetch_pharmacy_and_price_list(None, None)
>>> fetch_pharmacy_and_price_list(None, 30303)
>>> fetch_pharmacy_and_price_list("eliquis", None)
"""
try:
# Has user provided both inputs?
if not drug_name or not zip_code:
return None
request_url = BASE_URL.format(drug_name, zip_code)
response = get(request_url)
# Is the response ok?
response.raise_for_status()
# Scrape the data using bs4
soup = BeautifulSoup(response.text, "html.parser")
# This list will store the name and price.
pharmacy_price_list = []
# Fetch all the grids that contains the items.
grid_list = soup.find_all("div", {"class": "grid-x pharmCard"})
if grid_list and len(grid_list) > 0:
for grid in grid_list:
# Get the pharmacy price.
pharmacy_name = grid.find("p", {"class": "list-title"}).text
# Get price of the drug.
price = grid.find("span", {"p", "price price-large"}).text
pharmacy_price_list.append(
{
"pharmacy_name": pharmacy_name,
"price": price,
}
)
return pharmacy_price_list
except (HTTPError, exceptions.RequestException, ValueError):
return None
if __name__ == "__main__":
# Enter a drug name and a zip code
drug_name = input("Enter drug name: ").strip()
zip_code = input("Enter zip code: ").strip()
pharmacy_price_list: list | None = fetch_pharmacy_and_price_list(
drug_name, zip_code
)
if pharmacy_price_list:
print(f"\nSearch results for {drug_name} at location {zip_code}:")
for pharmacy_price in pharmacy_price_list:
name = pharmacy_price["pharmacy_name"]
price = pharmacy_price["price"]
print(f"Pharmacy: {name} Price: {price}")
else:
print(f"No results found for {drug_name}")
| Python/web_programming/fetch_well_rx_price.py/0 | {
"file_path": "Python/web_programming/fetch_well_rx_price.py",
"repo_id": "Python",
"token_count": 1190
} | 63 |
from __future__ import annotations
import requests
valid_terms = set(
"""approved_at_utc approved_by author_flair_background_color
author_flair_css_class author_flair_richtext author_flair_template_id author_fullname
author_premium can_mod_post category clicked content_categories created_utc downs
edited gilded gildings hidden hide_score is_created_from_ads_ui is_meta
is_original_content is_reddit_media_domain is_video link_flair_css_class
link_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title
name permalink pwls quarantine saved score secure_media secure_media_embed selftext
subreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type
total_awards_received ups upvote_ratio url user_reports""".split()
)
def get_subreddit_data(
subreddit: str, limit: int = 1, age: str = "new", wanted_data: list | None = None
) -> dict:
"""
subreddit : Subreddit to query
limit : Number of posts to fetch
age : ["new", "top", "hot"]
wanted_data : Get only the required data in the list
"""
wanted_data = wanted_data or []
if invalid_search_terms := ", ".join(sorted(set(wanted_data) - valid_terms)):
msg = f"Invalid search term: {invalid_search_terms}"
raise ValueError(msg)
response = requests.get(
f"https://reddit.com/r/{subreddit}/{age}.json?limit={limit}",
headers={"User-agent": "A random string"},
)
if response.status_code == 429:
raise requests.HTTPError(response=response)
data = response.json()
if not wanted_data:
return {id_: data["data"]["children"][id_] for id_ in range(limit)}
data_dict = {}
for id_ in range(limit):
data_dict[id_] = {
item: data["data"]["children"][id_]["data"][item] for item in wanted_data
}
return data_dict
if __name__ == "__main__":
# If you get Error 429, that means you are rate limited.Try after some time
print(get_subreddit_data("learnpython", wanted_data=["title", "url", "selftext"]))
| Python/web_programming/reddit.py/0 | {
"file_path": "Python/web_programming/reddit.py",
"repo_id": "Python",
"token_count": 729
} | 64 |
### Index
* [0 - Meta-Listas](#0---meta-listas)
* [1 - Agnรณsticos](#1---agnósticos)
* [Algoritmos y Estructuras de Datos](#algoritmos-y-estructuras-de-datos)
* [Base de Datos](#base-de-datos)
* [Ciencia Computacional](#ciencia-computacional)
* [Inteligencia Artificial](#inteligencia-artificial)
* [Metodologรญas de Desarrollo de Software](#metodologías-de-desarrollo-de-software)
* [Miscelรกneos](#misceláneos)
* [Sistemas Operativos](#sistemas-operativos)
* [Android](#android)
* [C++](#cpp)
* [Ensamblador](#ensamblador)
* [Erlang](#erlang)
* [Git](#git)
* [Go](#go)
* [Haskell](#haskell)
* [HTML and CSS](#html-and-css)
* [Java](#java)
* [JavaScript](#javascript)
* [AngularJS](#angularjs)
* [D3](#d3js)
* [jQuery](#jquery)
* [node.js](#nodejs)
* [React](#react)
* [Kotlin](#kotlin)
* [LaTeX](#latex)
* [Linux](#linux)
* [Lisp](#lisp)
* [Matemรกticas](#matem%C3%A1ticas)
* [.NET (C# Visual Studio)](#net-c--visual-studio)
* [NoSQL](#nosql)
* [DynamoDB](#dynamodb)
* [MongoDB](#mongodb)
* [Redis](#redis)
* [Perl](#perl)
* [Perl 6 / Raku](#perl-6--raku)
* [PHP](#php)
* [Symfony](#symfony)
* [Python](#python)
* [Django](#django)
* [Web2py](#web2py)
* [R](#r)
* [Ruby](#ruby)
* [Ruby on Rails](#ruby-on-rails)
* [Scala](#scala)
* [Scratch](#scratch)
* [SQL](#sql)
* [Subversion](#subversion)
* [TypeScript](#typescript)
* [Angular](#angular)
### 0 - Meta-Listas
* [Aprender Python](https://wiki.python.org.ar/aprendiendopython/) - Python Argentina
* [Apuntes Completos de Desarrollo Web](http://jorgesanchez.net) - Jorge Sรกnchez
* [Asombroso DDD: Una lista curada de recursos sobre Domain Driven Design](https://github.com/ddd-espanol/asombroso-ddd)
* [Desarrollo de Aplicaciones Web - Temario Completo](https://github.com/statickidz/TemarioDAW#temario-daw) - Josรฉ Luis Comesaรฑa (GitHub)
* [Desarrollo de Aplicaciones Web y Sistemas Microinformรกticos y Redes](https://javiergarciaescobedo.es) - Javier Garcรญa Escobedo
* [Gitbook - Libros รบtiles en espaรฑol](https://github.com/rosepac/gitbook-biblioteca-impresionante-en-espanol#gitbook---gu%C3%ADas-creadas-en-gitbook-en-espa%C3%B1ol) - Pablo Alvarez Corredera (GitHub)
* [Mรบltiples Cursos y Enlaces de Tecnologรญa Informรกtica](http://elvex.ugr.es) - Fernando Berzal Galiano
* [OpenLibra - Biblioteca recopilatorio de libros libres](https://openlibra.com/es/collection)
* [Universidad Nacional Autรณnoma de Mรฉxico - Plan (2016)](http://fcasua.contad.unam.mx/apuntes/interiores/plan2016_1.php)
### 1 - Agnรณsticos
#### Algoritmos y Estructuras de Datos
* [Algoritmos y Programaciรณn (Guรญa para docentes)](http://www.eduteka.org/pdfdir/AlgoritmosProgramacion.pdf) - Juan Carlos Lรณpez Garcรญa (PDF)
* [Anรกlisis, Diseรฑo e Implantaciรณn de Algoritmos](http://fcasua.contad.unam.mx/apuntes/interiores/docs/20181/informatica/1/LI_1164_06097_A_Analisis_Diseno_Implantacion_Algoritmos_Plan2016.pdf) - Universidad Nacional Autรณnoma de Mรฉxico, Juan Alberto Adam Siade, Gilberto Manzano Peรฑaloza, Renรฉ Montesano Brand, Luis Fernando Zรบรฑiga Lรณpez, et al. (PDF)
* [Apuntes de Algoritmos y Estructuras de Datos](https://openlibra.com/en/book/download/apuntes-de-algoritmos-y-estructuras-de-datos) - Alejandro Santos (PDF)
* [Breves Notas sobre Anรกlisis de Algoritmos](https://lya.fciencias.unam.mx/jloa/publicaciones/analisisdeAlgoritmos.pdf) - Universidad Nacional Autรณnoma de Mรฉxico, Jorge L. Ortega Arjona (PDF)
* [Fundamentos de Informรกtica y Programaciรณn](https://informatica.uv.es/docencia/fguia/TI/Libro/Libro_Fundamentos_Inform_Program.htm) - Gregorio Martรญn Quetglรกs, Francisco Toledo Lobo, Vicente Cerverรณn Lleรณ (HTML)
* [Fundamentos de programaciรณn](https://es.wikibooks.org/wiki/Fundamentos_de_programaci%C3%B3n) - WikiLibros
* [Introducciรณn a la programaciรณn](https://es.wikibooks.org/wiki/Introducci%C3%B3n_a_la_Programaci%C3%B3n) - WikiLibros
* [Temas selectos de estructuras de datos](https://lya.fciencias.unam.mx/jloa/publicaciones/estructurasdeDatos.pdf) - Universidad Nacional Autรณnoma de Mรฉxico, Jorge L. Ortega Arjona (PDF)
#### Base de Datos
* [Apuntes de Base de Datos 1](http://rua.ua.es/dspace/bitstream/10045/2990/1/ApuntesBD1.pdf) - Eva Gรณmez Ballester, Patricio Martรญnez Barco, Paloma Moreda Pozo, Armando Suรกrez Cueto, Andrรฉs Montoyo Guijarro, Estela Saquete Boro (PDF)
* [Base de Datos (2005)](http://www.uoc.edu/masters/oficiales/img/913.pdf) - Rafael Camps Parรฉ, Luis Alberto Casillas Santillรกn, Dolors Costal Costa, Marc Gibert Ginestร , Carme Martรญn Escofet, Oscar Pรฉrez Mora (PDF)
* [Base de Datos (2011)](https://openlibra.com/es/book/download/bases-de-datos-2) - Mercedes Marquรฉs (PDF)
* [Base de Datos Avanzadas (2013)](https://openlibra.com/es/book/download/bases-de-datos-avanzadas) - Marรญa Josรฉ Aramburu Cabo, Ismael Sanz Blasco (PDF)
* [Diseรฑo Conceptual de Bases de Datos](https://openlibra.com/es/book/download/diseno-conceptual-de-bases-de-datos) - Jorge Sรกnchez (PDF)
#### Ciencia Computacional
* [Breves Notas sobre Autรณmatas y Lenguajes](https://lya.fciencias.unam.mx/jloa/publicaciones/automatasyLenguajes.pdf) - Universidad Nacional Autรณnoma de Mรฉxico, Jorge L. Ortega Arjona (PDF)
* [Breves Notas sobre Complejidad](https://lya.fciencias.unam.mx/jloa/publicaciones/complejidad.pdf) - Universidad Nacional Autรณnoma de Mรฉxico, Jorge L. Ortega Arjona (PDF)
* [Breves Notas sobre Teorรญa de la Computaciรณn](https://lya.fciencias.unam.mx/jloa/publicaciones/teoria.pdf) - Universidad Nacional Autรณnoma de Mรฉxico, Jorge L. Ortega Arjona (PDF)
* [Teorรญa de la Computaciรณn: Lenguajes, Autรณmatas, Gramรกticas](http://ciencias.bogota.unal.edu.co/fileadmin/Facultad_de_Ciencias/Publicaciones/Archivos_Libros/Libros_Matematicas/_Teoria_de_la_Computacion___lenguajes__automatas__gramaticas._/teoriacomputacion.pdf) - Rodrigo De Castro Korgi (PDF)
#### Inteligencia Artificial
* [Deep Learning](http://www.uhu.es/publicaciones/?q=libros&code=1252) - Isaac Pรฉrez Borrero, Manuel E. Gegรบndez Arias (PDF)
* [Libro online de IAAR](https://iaarbook.github.io) - Raรบl E. Lรณpez Briega, IAAR (HTML)
#### Metodologรญas de desarrollo de software
* [Ingenierรญa de Software: Una Guรญa para Crear Sistemas de Informaciรณn](https://web.archive.org/web/20150824055042/http://www.wolnm.org/apa/articulos/Ingenieria_Software.pdf) - Alejandro Peรฑa Ayala (PDF)
* [Scrum & Extreme Programming (para programadores)](https://web.archive.org/web/20140209204645/http://www.cursosdeprogramacionadistancia.com/static/pdf/material-sin-personalizar-agile.pdf) - Eugenia Bahit (PDF)
* [Scrum Level](https://scrumlevel.com/files/scrumlevel.pdf) - Juan Palacio, Scrum Manager (PDF) [(EPUB)](https://scrumlevel.com/files/scrumlevel.epub)
* [Scrum Master - Temario troncal 1](https://scrummanager.net/files/scrum_master.pdf) - Marta Palacio, Scrum Manager (PDF) [(EPUB)](https://scrummanager.net/files/scrum_master.epub)
* [Scrum y XP desde las trincheras](http://www.proyectalis.com/wp-content/uploads/2008/02/scrum-y-xp-desde-las-trincheras.pdf) - Henrik Kniberg, `trl.:` proyectalis.com (PDF)
#### Miscelรกneos
* [97 cosas que todo programador deberรญa saber](http://97cosas.com/programador/) - Kevlin Henney, `trl.:` Espartaco Palma, `trl.:` Natรกn Calzolari (HTML)
* [Docker](https://github.com/brunocascio/docker-espanol#docker) - Bruno Cascio (GitHub)
* [El camino a un mejor programador](http://emanchado.github.io/camino-mejor-programador/downloads/camino_2013-01-19_0688b6e.html) - Esteban Manchado Velรกzquez, Joaquรญn Caraballo Moreno, Yeray Darias Camacho (HTML) [(PDF, ePub)](http://emanchado.github.io/camino-mejor-programador/)
* [Introducciรณn a Docker](https://www.rediris.es/tecniris/archie/doc/TECNIRIS47-1b.pdf) - Benito Cuesta, Salvador Gonzรกlez (PDF)
* [Los Apuntes de Majo](https://losapuntesdemajo.vercel.app) - Majo Ledesma (PDF)
* [Programaciรณn de videojuegos SDL](http://libros.metabiblioteca.org/bitstream/001/271/8/Programacion_Videojuegos_SDL.pdf) - Alberto Garcรญa Serrano (PDF)
#### Sistemas Operativos
* [Fundamentos de Sistemas Operativos](http://sistop.org/pdf/sistemas_operativos.pdf) - Gunnar Wolf, Esteban Ruiz, Federico Bergero, Erwin Meza, et al. (PDF)
* [Sistemas Operativos](http://sistop.gwolf.org/html/biblio/Sistemas_Operativos_-_Luis_La_Red_Martinez.pdf) - David Luis la Red Martinez (PDF)
### Android
* [Curso Android](https://www.develou.com/android/) (HTML)
* [Manual de Programaciรณn Android v.2.0](http://ns2.elhacker.net/timofonica/manuales/Manual_Programacion_Android_v2.0.pdf) - Salvador Gรณmez Oliver (PDF)
### <a id="cpp"></a>C++
* [Aprenda C++ avanzado como si estuviera en primero](https://web.archive.org/web/20100701020037/http://www.tecnun.es/asignaturas/Informat1/AyudaInf/aprendainf/cpp/avanzado/cppavan.pdf) - Paul Bustamante, Iker Aguinaga, Miguel Aybar, Luis Olaizola, Iรฑigo Lazcano (PDF)
* [Aprenda C++ bรกsico como si estuviera en primero](https://web.archive.org/web/20100701020025/http://www.tecnun.es/asignaturas/Informat1/AyudaInf/aprendainf/cpp/basico/cppbasico.pdf) - Paul Bustamante, Iker Aguinaga, Miguel Aybar, Luis Olaizola, Iรฑigo Lazcano (PDF)
* [Ejercicios de programaciรณn creativos y recreativos en C++](http://antares.sip.ucm.es/cpareja/libroCPP/) - Luis Llana, Carlos Gregorio, Raquel Martรญnez, Pedro Palao, Cristรณbal Pareja (HTML)
### Ensamblador
* [Curso ASM de 80x86 por AESOFT](http://redeya.bytemaniacos.com/electronica/cursos/aesoft.htm) - Francisco Jesus Riquelme (HTML)
* [Lenguaje Ensamblador para PC](https://pacman128.github.io/static/pcasm-book-spanish.pdf) - Paul A. Carter, `trl.:` Leonardo Rodrรญguez Mรบjica (PDF)
### Erlang
* [Programaciรณn en Erlang](https://es.wikibooks.org/wiki/Programaci%C3%B3n_en_Erlang) - WikiLibros
### Git
* [Git Immersiรณn en Espaรฑol](https://esparta.github.io/gitimmersion-spanish) - Jim Weirich, `trl.:` Espartaco Palma
* [Git. La guรญa simple](https://rogerdudler.github.io/git-guide/index.es.html) - Roger Dudler, `trl.:` Luis Barragan, `trl.:` Adrian Matellanes (HTML)
* [Gitmagic](http://www-cs-students.stanford.edu/~blynn/gitmagic/intl/es) - Ben Lynn, `trl.:` Rodrigo Toledo, `trl.:` Ariset Llerena Tapia (HTML, PDF)
* [Pro Git](http://git-scm.com/book/es/) - Scott Chacon, Ben Straub, `trl.:` Andres Mancera, `trl.:` Antonino Ingargiola, et al. (HTML, PDF, EPUB)
### Go
* [El pequeรฑo libro Go](https://raulexposito.com/the-little-go-book-en-castellano.html) - Karl Seguin, `trl.:` Raรบl Expรณsito (HTML, [PDF](https://raulexposito.com/assets/pdf/go.pdf), [EPUB](https://raulexposito.com/assets/epub/go.epub))
* [Go en Espaรฑol](https://nachopacheco.gitbooks.io/go-es/content/doc) - Nacho Pacheco (HTML)
### Haskell
* [ยกAprende Haskell por el bien de todos!](http://aprendehaskell.es/main.html) (HTML)
* [Piensa en Haskell (ejercicios de programaciรณn funcional)](http://www.cs.us.es/~jalonso/publicaciones/Piensa_en_Haskell.pdf) - Josรฉ A. Alonso Jimรฉnez, Mยช Josรฉ Hidalgo Doblado (PDF)
### HTML and CSS
* [99 tips para Web Development](https://fmontes.gumroad.com/l/99tips) - Freddy Montes (PDF) (se solicita email)
* [CSS avanzado](http://librosweb.es/libro/css_avanzado) - Javier Eguรญluz Pรฉrez (HTML) [(PDF)](https://openlibra.com/es/book/download/css-avanzado)
* [CSS3 y JavaScript avanzado](https://openlibra.com/es/book/download/css3-y-javascript-avanzado) - Jordi Collell Puig (PDF)
* [Diseรฑo de Interfaces Web](http://interfacesweb.github.io/unidades/) - Pedro Prieto (HTML)
* [El gran libro del diseรฑo web](https://freeditorial.com/es/books/el-gran-libro-del-diseno-web) - Rither Cobeรฑa C (HTML, PDF, EPUB, Kindle)
* [Estructura con CSS](http://es.learnlayout.com) - Greg Smith, Isaac Durazo, `trl.:` Isaac Durazo (HTML)
* [Guรญa Completa de CSS3](https://openlibra.com/es/book/download/guia-completa-de-css3) - Antonio Navajas Ojeda (PDF)
* [HTML5](https://openlibra.com/es/book/html5) - Arkaitz Garro (PDF)
* [Introducciรณn a CSS](http://librosweb.es/libro/css/) - Javier Eguรญluz Pรฉrez (HTML) [(PDF)](https://openlibra.com/es/book/download/introduccion-a-css)
### Java
* [Aprendiendo Java y POO (2008)](https://openlibra.com/es/book/download/aprendiendo-java-y-poo) - Gustavo Guillermo Pรฉrez (PDF)
* [Curso Jakarta EEย 9](https://danielme.com/curso-jakarta-ee-indice/) - Daniel Medina
* [Desarrollando con Java 8: Poker](https://ia601504.us.archive.org/21/items/DesarrollandoConJava8Poker/DesarrollandoConJava8Poker.pdf) - David Pรฉrez Cabrera (PDF)
* [Desarrollo de proyectos informรกticos con Java](http://www3.uji.es/~belfern/libroJava.pdf) - รscar Belmonte Fernรกndez, Carlos Granell Canut, Marรญa del Carmen Erdozain Navarro, et al. (PDF)
* [Ejercicios de Programaciรณn en Java](https://www.arkaitzgarro.com/java/) - Arkaitz Garro, Javier Eguรญluz Pรฉrez, A. Garcรญa-Beltrรกn, J.M. Arranz (PDF)
* [Notas de Introducciรณn al Lenguaje de Programaciรณn Java (2004)](https://lya.fciencias.unam.mx/jloa/publicaciones/introduccionJava.pdf) - Universidad Nacional Autรณnoma de Mรฉxico, Jorge L. Ortega Arjona (PDF)
* [Pensando la computaciรณn como un cientรญfico (con Java)](http://www.ungs.edu.ar/cm/uploaded_files/publicaciones/476_cid03-Pensar%20la%20computacion.pdf) (PDF)
* [PlugIn Apache Tapestry: desarrollo de aplicaciones y pรกginas web](https://picodotdev.github.io/blog-bitix/assets/custom/PlugInTapestry.pdf) - picodotdev (PDF) ([EPUB](https://picodotdev.github.io/blog-bitix/assets/custom/PlugInTapestry.epub), [Kindle](https://picodotdev.github.io/blog-bitix/assets/custom/PlugInTapestry.mobi), [:package: cรณdigo fuente ejemplos](https://github.com/picodotdev/blog-ejemplos/tree/HEAD/PlugInTapestry))
* [Prรกcticas de Java (2009)](https://openlibra.com/es/book/download/practicas-de-java) - Gorka Prieto Agujeta, et al. (PDF)
* [Preparando JavaSun 6 - OCPJP6](https://github.com/PabloReyes/ocpjp-resumen-espanol#ocpjp6-resumen-espaรฑol) - Pablo Reyes Almagro (GitHub) [(PDF)](https://github.com/PabloReyes/ocpjp-resumen-espanol/blob/master/OCPJP6%20Resumen.pdf)
* [Programaciรณn en Java](http://elvex.ugr.es/decsai/java/) - Fernando Berzal Galiano (HTML)
* [Tutorial bรกsico de Java EE](http://static1.1.sqspcdn.com/static/f/923743/14770633/1416082087870/JavaEE.pdf) - Abraham Otero (PDF)
* [Tutorial introducciรณn a Maven 3](http://static1.1.sqspcdn.com/static/f/923743/15025126/1320942755733/Tutorial_de_Maven_3_Erick_Camacho.pdf) - Erick Camacho (PDF)
### JavaScript
* [El Tutorial de JavaScript Moderno](https://es.javascript.info) - Ilya Kantor, Elizabeth Portilla, joaquinelio, Ezequiel Castellanos, et al. (HTML)
* [Eloquent JavaScript](https://eloquentjs-es.thedojo.mx) - Marijn Haverbeke, `trl.:` Various (HTML, PDF, EPUB, MOBI)
* [Guรญa de JavaScript 'Mozilla'](https://developer.mozilla.org/es/docs/Web/JavaScript/Guide) (HTML)
* [Introducciรณn a AJAX](http://librosweb.es/libro/ajax) - Javier Eguรญluz Pรฉrez (HTML) [(PDF)](https://openlibra.com/es/book/download/introduccion-ajax)
* [Introducciรณn a JavaScript](http://librosweb.es/libro/javascript) - Javier Eguรญluz Pรฉrez (HTML) [(PDF)](https://openlibra.com/es/book/download/introduccion-a-javascript)
* [JavaScript, ยกInspรญrate!](https://leanpub.com/javascript-inspirate) - Ulises Gascรณn Gonzรกlez (Leanpub cuenta requerida)
* [JavaScript Para Gatos](https://jsparagatos.com) - Maxwell Ogden, `trl.:` Dan Zajdband (HTML)
* [Manual de JavaScript](https://desarrolloweb.com/manuales/manual-javascript.html#capitulos20) (HTML)
#### AngularJS
> :information_source: Vรฉase tambiรฉn … [Angular](#angular)
* [AngularJS](https://eladrodriguez.gitbooks.io/angularjs) - Elad Rodriguez (HTML)
* [Guรญa de estilo AngularJS](https://github.com/johnpapa/angular-styleguide/blob/master/a1/i18n/es-ES.md) - John Papa, et al., `trl.:` Alberto Calleja Rรญos, `trl.:` Gilberto (HTML)
* [Manual de AngularJS](https://desarrolloweb.com/manuales/manual-angularjs.html) - desarrolloweb.com (HTML, PDF, EPUB, Kindle)
#### D3.js
* [Tutorial de D3](http://gcoch.github.io/D3-tutorial/index.html) - Scott Murray, `trl.:` Gabriel Coch (HTML)
#### jQuery
* [Fundamentos de jQuery](https://librosweb.es/libro/fundamentos_jquery) - Rebecca Murphey, `trl.:` Leandro D'Onofrio (HTML) [(PDF)](https://openlibra.com/es/book/download/fundamentos-de-jquery)
* [Manual de jQuery](http://mundosica.github.io/tutorial_hispano_jQuery/) - MundoSICA, et al. (HTML, PDF)
#### Node.js
* [El Libro para Principiantes en Node.js](https://www.nodebeginner.org/index-es.html) - Manuel Kiessling, Herman A. Junge (HTML)
* [Introducciรณn a Node.js a travรฉs de Koans](http://nodejskoans.com) - Arturo Muรฑoz de la Torre (PDF)
#### React
* [Desarrollo de Aplicaciones Web con React.js y Redux.js](https://leanpub.com/react-redux/read) - Sergio Daniel Xalambrรญ (HTML)
* [SurviveJS - React de aprendiz a maestro](https://es.survivejs.com) - Juho Vepsรคlรคinen, `trl.:` Raรบl Expรณsito (HTML, PDF)
### Kotlin
* [Curso programaciรณn Android en Kotlin](https://cursokotlin.com/curso-programacion-kotlin-android/) - AristiDevs (HTML)
### LaTeX
* [Ediciรณn de textos cientรญficos con LaTeX. Composiciรณn, grรกficos, diseรฑo editorial y presentaciones beamer](https://tecdigital.tec.ac.cr/servicios/revistamatematica/Libros/LaTeX/MoraW_BorbonA_LibroLaTeX.pdf) - Walter Mora F., Alexander Borbรณn A. (PDF)
* [La introducciรณn no-tan-corta a LaTeX 2ฮต](http://osl.ugr.es/CTAN/info/lshort/spanish/lshort-a4.pdf) - Tobias Oetiker, Hubert Partl, Irene Hyna, Elisabeth Schlegl, `trl.:` Enrique Carleos Artime, `trl.:` Daniel Cuevas, `trl.:` J. Luis Rivera (PDF)
### Linux
* [BASH Scripting Avanzado: Utilizando Declare para definiciรณn de tipo](https://web.archive.org/web/20150307181233/http://library.originalhacker.org:80/biblioteca/articulo/ver/123) - Eugenia Bahit (descarga directa)
* [El Manual de BASH Scripting Bรกsico para Principiantes](https://es.wikibooks.org/wiki/El_Manual_de_BASH_Scripting_B%C3%A1sico_para_Principiantes) - WikiLibros
* [El Manual del Administrador de Debian](https://debian-handbook.info/browse/es-ES/stable/) - Raphaรซl Hertzog, Roland Mas (HTML)
### Lisp
* [Una Introducciรณn a Emacs Lisp en Espaรฑol](http://savannah.nongnu.org/git/?group=elisp-es) (HTML)
### Matemรกticas
* [Sage para Estudiantes de Pregrado](http://www.sage-para-estudiantes.com) - Gregory Bard, `trl.:` Diego Sejas Viscarra
### .NET (C# / Visual Studio)
* [El lenguaje de programaciรณn C#](http://dis.um.es/~bmoros/privado/bibliografia/LibroCsharp.pdf) - Josรฉ Antonio Gonzรกlez Seco (PDF)
* [Guรญa de Arquitectura N-capas Orientadas al Dominio](https://blogs.msdn.microsoft.com/cesardelatorre/2010/03/11/nuestro-nuevo-libro-guia-de-arquitectura-n-capas-ddd-net-4-0-y-aplicacion-ejemplo-en-disponibles-para-download-en-msdn-y-codeplex) - Cesar De la Torre (HTML)
### NoSQL
#### DynamoDB
* [Aprendizaje amazon-dynamodb](https://riptutorial.com/Download/amazon-dynamodb-es.pdf) - Compiled from StackOverflow documentation (PDF)
#### MongoDB
* [El pequeรฑo libro MongoDB](https://github.com/uokesita/the-little-mongodb-book) - Karl Seguin, `trl.:` Osledy Bazo
* [MongoDB en espaรฑol: T1, El principio](https://dpdc.gitbooks.io/mongodb-en-espanol-tomo-1/content) - Yohan D. Graterol (HTML) *(:construction: en proceso)*
#### Redis
* [El pequeรฑo libro Redis](https://raulexposito.com/the-little-redis-book-en-castellano.html) - Karl Seguin, `trl.:` Raรบl Expรณsito (HTML, PDF, EPUB)
### PHP
* [Domain Driven Design with PHP (Diseรฑo guiado por Dominio con PHP)](https://www.youtube.com/playlist?list=PLfgj7DYkKH3DjmXTOxIMs-5fcOgDg_Dd2) - Carlos Buenosvinos Zamora (YouTube playlist)
* [Manual de estudio introductorio al lenguaje PHP procedural](https://web.archive.org/web/20140209203630/http://www.cursosdeprogramacionadistancia.com/static/pdf/material-sin-personalizar-php.pdf) - Eugenia Bahit (PDF)
* [PHP y Programaciรณn orientada a objetos](https://styde.net/php-y-programacion-orientada-a-objetos/) - Duilio Palacios (HTML)
* [POO y MVC en PHP](https://bibliotecafacet.com.ar/wp-content/uploads/2014/12/eugeniabahitpooymvcenphp.pdf) - Eugenia Bahit (PDF)
* [Programaciรณn en PHP a travรฉs de ejemplos](https://openlibra.com/es/book/programacion-en-php-a-traves-de-ejemplos) - Manuel Palomo Duarte, Ildefonso Montero Pรฉrez (HTML)
* [Programaciรณn web avanzada: Ajax y Google Maps](http://rua.ua.es/dspace/bitstream/10045/13176/9/04-ajaxphp.pdf) - Sergio Lujรกn Mora, Universidad de Colima (PDF)
* [Silex, el manual oficial](http://librosweb.es/libro/silex) - Igor Wiedler, `trl.:` Javier Eguรญluz Pรฉrez (HTML)
#### Symfony
* [Symfony 1.4, la guรญa definitiva](http://librosweb.es/libro/symfony_1_4) - Fabien Potencier, Franรงois Zaninotto, `trl.:` Javier Eguรญluz Pรฉrez (HTML) [(PDF)](https://openlibra.com/es/book/download/symfony-la-guia-definitiva)
* [Symfony 2.4, el libro oficial](http://librosweb.es/libro/symfony_2_4/) - Fabien Potencier, Ryan Weaver, `trl.:` Javier Eguรญluz Pรฉrez (HTML) [(PDF)](https://openlibra.com/es/book/download/manual-de-symfony2-ver-2-0-12)
* [Symfony 5: La Vรญa Rรกpida](https://web.archive.org/web/20210805141343/https://symfony.com/doc/current/the-fast-track/es/index.html) - Fabien Potencier (HTML)
### Perl
* [Tutorial Perl](http://es.tldp.org/Tutoriales/PERL/tutoperl-print.pdf) - Juan Juliรกn Merelo Guervรณs (PDF)
* [Tutorial Perl](http://kataix.umag.cl/~ruribe/Utilidades/Tutorial%20de%20Perl.pdf) (PDF)
* [Tutoriales de Perl](http://perlenespanol.com/tutoriales/) - Uriel Lizama (HTML)
### Perl 6 / Raku
* [Piensa en Perl 6](https://uzluisf.gitlab.io/piensaperl6/) - Laurent Rosenfeld, Allen B. Downey, `trl.:` Luis F. Uceta (PDF)
### Python
* [Aprenda a pensar como un programador (con Python)](https://argentinaenpython.com/quiero-aprender-python/aprenda-a-pensar-como-un-programador-con-python.pdf) - Allen Downey, Jeffrey Elkner, Chris Meyers, `trl.:` Miguel รngel Vilella, `trl.:` รngel Arnal, `trl.:` Ivรกn Juanes, `trl.:` Litza Amurrio, `trl.:` Efrain Andia, `trl.:` Cรฉsar Ballardini (PDF)
* [Aprende Python](https://aprendepython.es) - Sergio Delgado Quintero (HTML, PDF)
* [Aprendiendo a Programar en Python con mi Computador](https://openlibra.com/en/book/download/aprendiendo-a-programar-en-python-con-mi-computador) (PDF)
* [Doma de Serpientes para Niรฑos: Aprendiendo a Programar con Python](http://code.google.com/p/swfk-es/) (HTML)
* [Inmersiรณn en Python](https://code.google.com/archive/p/inmersionenpython3/) (HTML)
* [Inmersiรณn en Python 3](https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/inmersionenpython3/inmersionEnPython3.0.11.pdf) - Mark Pilgrim, `trl.:` Josรฉ Miguel Gonzรกlez Aguilera (PDF) (descarga directa)
* [Introducciรณn a la programaciรณn con Python](http://repositori.uji.es/xmlui/bitstream/handle/10234/24305/s23.pdf) - Andrรฉs Marzal, Isabel Gracia (PDF)
* [Introducciรณn a Programando con Python](http://opentechschool.github.io/python-beginners/es_CL/) - OpenTechSchool, et al. (HTML)
* [Python para ciencia e ingenierรญa](https://github.com/mgaitan/curso-python-cientifico#curso-de-python-para-ciencias-e-ingenierรญas) - Martรญn Gaitรกn (GitHub)
* [Python para principiantes](http://librosweb.es/libro/python) - Eugenia Bahit (HTML) [(PDF)](https://web.archive.org/web/20150421012120/http://www.cursosdeprogramacionadistancia.com/static/pdf/material-sin-personalizar-python.pdf)
* [Python para todos](https://launchpadlibrarian.net/18980633/Python%20para%20todos.pdf) - Raรบl Gonzรกlez Duque (PDF)
#### Django
* [Guรญa Oficial de Django](https://docs.djangoproject.com/es/3.2/) (3.2) (HTML)
* [Tutorial de Django Girls](https://tutorial.djangogirls.org/es/) (2.2.4) (HTML)
#### Web2py
* [Web2py - Manual de Referencia Completo, 5a Ediciรณn](http://www.web2py.com/books/default/chapter/41) - Massimo Di Pierro, `trl.:` Alan Etkin (HTML)
### Ruby
* [Aprende a programar con Ruby](http://rubysur.org/aprende.a.programar) - RubySur (HTML)
* [La Guรญa de Estilos de Ruby](https://github.com/alemohamad/ruby-style-guide/blob/master/README-esLA.md#preludio) - Ale Mohamad (GitHub)
* [Ruby en 20 minutos](https://www.ruby-lang.org/es/documentation/quickstart) (HTML)
* [Ruby tutorial o cรณmo pasar un buen rato programando](http://rubytutorial.wikidot.com/introduccion) - Andrรฉs Suรกrez Garcรญa (HTML)
#### Ruby on Rails
* [Introducciรณn a Rails](http://rubysur.org/introduccion.a.rails/) - RubySur (HTML)
### R
* [Cartas sobre Estadรญstica de la Revista Argentina de Bioingenierรญa](http://cran.r-project.org/doc/contrib/Risk-Cartas-sobre-Estadistica.pdf) - Marcelo R. Risk (PDF)
* [Generaciรณn automรกtica de reportes con R y LaTeX](http://cran.r-project.org/doc/contrib/Rivera-Tutorial_Sweave.pdf) - Mario Alfonso Morales Rivera (PDF)
* [Grรกficos Estadรญsticos con R](http://cran.r-project.org/doc/contrib/grafi3.pdf) - Juan Carlos Correa, Nelfi Gonzรกlez (PDF)
* [Introducciรณn a R](http://cran.r-project.org/doc/contrib/R-intro-1.1.0-espanol.1.pdf) - R Development Core Team, `trl.:` Andrรฉs Gonzรกlez, `trl.:` Silvia Gonzรกlez (PDF)
* [Introducciรณn al uso y programaciรณn del sistema estadรญstico R](http://cran.r-project.org/doc/contrib/curso-R.Diaz-Uriarte.pdf) - Ramรณn Dรญaz-Uriarte (PDF)
* [Mรฉtodos Estadรญsticos con R y R Commander](http://cran.r-project.org/doc/contrib/Saez-Castillo-RRCmdrv21.pdf) - Antonio Josรฉ Sรกez Castillo (PDF)
* [Optimizaciรณn Matemรกtica con R: Volรบmen I](http://cran.r-project.org/doc/contrib/Optimizacion_Matematica_con_R_Volumen_I.pdf) - Enrique Gabriel Baquela, Andrรฉs Redchuk (PDF)
* [R para Principiantes](http://cran.r-project.org/doc/contrib/rdebuts_es.pdf) - Michel Schinz, Philipp Haller, `trl.:` Juanjo Bazรกn (PDF)
### Scala
* [Manual de Scala para programadores Java](http://www.scala-lang.org/docu/files/ScalaTutorial-es_ES.pdf) - Emmanuel Paradis, `trl.:` Jorge A. Ahumada (PDF)
* [Scala con Ejemplos](https://github.com/ErunamoJAZZ/ScalaByExample-es) - Martin Odersky, `trl.:` Daniel Erunamo *(:construction: en proceso)*
### Scratch
* [Informรกtica Creativa](https://github.com/programamos/GuiaScratch) - Karen Brennan, Christan Balch, Michelle Chung, `trl.:` programamos (PDF)
* [Manual de Scratch 2](http://lsi.vc.ehu.es/pablogn/docencia/FdI/Scratch/Aprenda%20a%20programar%20con%20Scratch%20en%20un%20par%20de%20tardes.pdf) - Pablo Gonzรกlez Nalda (PDF)
### SQL
* [Manual de SQL](http://jorgesanchez.net/manuales/sql/intro-sql-sql2016.html) - Jorge Sanchez Asenjo (HTML)
* [Tutorial de SQL](http://www.desarrolloweb.com/manuales/9/) (HTML)
### Subversion
* [Control de versiones con Subversion](http://svnbook.red-bean.com/nightly/es/index.html) - Ben Collins-Sussman, Brian W. Fitzpatrick, C. Michael Pilato (HTML)
### TypeScript
* [Aprendizaje TypeScript](https://riptutorial.com/Download/typescript-es.pdf) - Compiled from StackOverflow Documentation (PDF)
* [Introduccion a TypeScript](https://khru.gitbooks.io/typescript/) - Emmanuel Valverde Ramos (HTML)
* [TypeScript Deep Dive](https://github.com/melissarofman/typescript-book) - Basarat Ali Syed, `trl.:` Melissa Rofman (HTML)
* [Uso avanzado de TypeScript en un ejemplo real](https://neliosoftware.com/es/blog/uso-avanzado-de-typescript/) - Nelio Software (HTML)
#### Angular
> :information_source: Vรฉase tambiรฉn … [AngularJS](#angularjs)
* [Aprendizaje Angular](https://riptutorial.com/Download/angular-es.pdf) - Compiled from StackOverflow Documentation (PDF)
* [Aprendizaje Angular 2](https://riptutorial.com/Download/angular-2-es.pdf) - Compiled from StackOverflow Documentation (PDF)
* [Entendiendo Angular](https://jorgeucano.gitbook.io/entendiendo-angular/) - Jorge Cano
| free-programming-books/books/free-programming-books-es.md/0 | {
"file_path": "free-programming-books/books/free-programming-books-es.md",
"repo_id": "free-programming-books",
"token_count": 10915
} | 65 |
### Index
* [Blockchain](#blockchain)
* [Go](#go)
* [HTML and CSS](#html-and-css)
* [Java](#java)
* [JavaScript](#javascript)
* [Linux](#linux)
* [PHP](#php)
* [Python](#python)
* [Web Development](#web-development)
### Blockchain
* [Bitcoin - On Point](https://eimaung.com/bitcoin/) - Ei Maung (PDF)
### Go
* [The Little Go Book](https://github.com/nainglinaung/the-little-go-book) - Karl Seguin, `trl.:` Naing Lin Aung ([HTML](https://github.com/nainglinaung/the-little-go-book/blob/master/mm/go.md), [PDF](https://github.com/nainglinaung/the-little-go-book/blob/master/mm/go.pdf), [EPUB](https://github.com/nainglinaung/the-little-go-book/blob/master/mm/go.epub))
### HTML and CSS
* [Bootstrap - On Point](https://eimaung.com/bootstrap/) - Ei Maung (PDF)
* [HTML](https://books.saturngod.net/HTML5/) - Saturngod
* [HTML & CSS - Beginner To Super Beginner](https://lwinmoepaing.github.io/books/) - Lwin Moe Paing (PDF)
### Java
* [Design Patterns](https://designpatterns.saturngod.net) - Saturngod
### JavaScript
* [API - On Point](https://eimaung.com/api/) - Ei Maung (PDF)
* [JavaScript - On Point](https://eimaung.com/jsbook/) - Ei Maung (PDF)
* [React - On Point](https://eimaung.com/react/) - Ei Maung (PDF)
### Linux
* [Ubuntu Linux for You](http://eimaung.com/ubuntu-for-you) - Ei Maung (PDF)
### PHP
* [Laravel - On Point](https://eimaung.com/laravel/) - Ei Maung (PDF)
* [PHP - On Point](https://eimaung.com/php/) - Ei Maung (PDF)
### Python
* [Programming Basic For Beginner](http://books.saturngod.net/programming_basic/) - Saturngod
### Web Development
* [Professional Web Developer](http://eimaung.com/professional-web-developer) - Ei Maung (PDF)
* [Professional Web Developer 2023](https://eimaung.com/pwd2023/) - Ei Maung (PDF)
* [Rockstar Developer](http://eimaung.com/rockstar-developer) - Ei Maung (PDF)
| free-programming-books/books/free-programming-books-my.md/0 | {
"file_path": "free-programming-books/books/free-programming-books-my.md",
"repo_id": "free-programming-books",
"token_count": 727
} | 66 |
### Index
* [C and C++](#c-and-cpp)
* [ClosureScript](#clojurescript)
* [Haskell](#haskell)
* [JavaScript](#javascript)
* [React](#react)
* [Language Agnostic](#language-agnostic)
* [PHP](#php)
* [Python](#python)
* [Django](#django)
* [Ruby](#ruby)
### <a id="c-and-cpp"></a>C and C++
* [ะก/C++ ะขะตะพััั ัะฐ ะฟัะฐะบัะธะบะฐ](https://shron1.chtyvo.org.ua/Voitenko_Volodymyr/C_Cpp_Teoriia_ta_praktyka.pdf) - ะะพะปะพะดะธะผะธั ะะพะนัะตะฝะบะพ (PDF)
### ClojureScript
* [ะ ะพะทะฟะปััะฐะฝะธะน ClojureScript](https://lambdabooks.github.io/clojurescript-unraveled) - ะ ะพะผะฐะฝ ะัััะบะพะฒ (LambdaBooks)
### Haskell
* [ะะธะฒัะธัั ัะพะฑั ะฅะฐัะบะตะปะฐ ะฝะฐ ะฒะตะปะธะบะต ัะฐััั!](http://haskell.trygub.com) - ะััะฐะฝ ะัะฟะพะฒะฐัะฐ
### JavaScript
* [ะ ะพะทัะผัะฝะฝั ECMAScript 6](http://understandinges6.denysdovhan.com) - ะะตะฝะธั ะะพะฒะณะฐะฝั (LambdaBooks)
#### React
* [ะะพัะฐัะพะบ ัะพะฑะพัะธ](https://uk.reactjs.org/docs/getting-started.html)
### Language Agnostic
* [ะะธะทะฐะนะฝ-ะฟะฐัะตัะฝะธ - ะฟัะพััะพ, ัะบ ะดะฒะตัั](http://designpatterns.andriybuday.com) - ะะฝะดััะน ะัะดะฐะน
### PHP
* [Symfony: ะจะฒะธะดะบะธะน ััะฐัั](https://symfony.com/doc/current/the-fast-track/uk/index.html) - Symfony SAS
### Python
* [ะะพัะธะฝััะต ั Python 3](https://uk.wikibooks.org/wiki/ะะพัะธะฝััะต_ั_Python_3) - ะะฐัะบ ะัะปัะณัะธะผ
* [ะัะดัััะฝะธะบ ะผะพะฒะธ Python](http://docs.linux.org.ua/%D0%9F%D1%80%D0%BE%D0%B3%D1%80%D0%B0%D0%BC%D1%83%D0%B2%D0%B0%D0%BD%D0%BD%D1%8F/Python/%D0%9F%D1%96%D0%B4%D1%80%D1%83%D1%87%D0%BD%D0%B8%D0%BA_%D0%BC%D0%BE%D0%B2%D0%B8_Python/) - าะฒัะดะพ ะฒะฐะฝ ะ ะพัััะผ (Guido van Rossum)
#### Django
* [ะะฐะฒัะฐะปัะฝะธะน ะฟะพััะฑะฝะธะบ Django Girls](https://tutorial.djangogirls.org/uk/)
### Ruby
* [ะะฐะปะตะฝัะบะฐ ะบะฝะธะณะฐ ะฟัะพ Ruby](https://lambdabooks.github.io/thelittlebookofruby) - ะกะตัะณัะน ะัะฑะฐ (LambdaBooks)
| free-programming-books/books/free-programming-books-uk.md/0 | {
"file_path": "free-programming-books/books/free-programming-books-uk.md",
"repo_id": "free-programming-books",
"token_count": 1013
} | 67 |
### Index
* [Desenvolvimento Web](#desenvolvimento-web)
* [Laravel](#laravel)
* [Ubuntu](#ubuntu)
### Desenvolvimento Web
* [10webPodcast sobre web e desenvolvimento em portuguรชs](https://10web.pt/acerca) - Ricardo Correia, Vitor Silva, Ana Sampaio (podcast)
### Laravel
* [Laravel Portugal Live](https://laravelportugal.simplecast.fm) (screencast)
### Ubuntu
* [O Podcast Ubuntu Portugal](https://podcastubuntuportugal.org) (podcast)
| free-programming-books/casts/free-podcasts-screencasts-pt_PT.md/0 | {
"file_path": "free-programming-books/casts/free-podcasts-screencasts-pt_PT.md",
"repo_id": "free-programming-books",
"token_count": 165
} | 68 |
### Index
* [Algorithmes & Structures des donnรฉes](#algorithmes)
* [APL](#apl)
* [Bash / Shell](#bash--shell)
* [C](#c)
* [C#](#csharp)
* [C++](#cpp)
* [Delphi](#delphi)
* [Git](#git)
* [HTML and CSS](#html-and-css)
* [Java](#java)
* [JavaScript](#javascript)
* [jQuery](#jquery)
* [React](#react)
* [Vue.js](#vuejs)
* [Linux](#linux)
* [PHP](#php)
* [Python](#python)
* [Ruby](#ruby)
* [SQL](#sql)
* [SysAdmin](#sysadmin)
### Algorithmes
* [Algorithmie - Cours](https://www.youtube.com/playlist?list=PLrSOXFDHBtfE0AkOm795c2qpLQJNiEBbZ) - Formation Video
### APL
* [Dรฉcouvrez le langage APL](https://www.youtube.com/playlist?list=PLIz4PfDd5D29oOW61VkB4MHxGurtSCmhh) - Schraf : Maths-info
### Bash / Shell
* [Apprendre ร utiliser le shell Bash](https://www.pierre-giraud.com/shell-bash/) - Pierre Giraud
* [Exercices shell scripts](https://ineumann.developpez.com/tutoriels/linux/exercices-shell/) - Idriss Neumann
* [Quelques bonnes pratiques dans l'รฉcriture de scripts en Bash](https://ineumann.developpez.com/tutoriels/linux/bash-bonnes-pratiques/) - Idriss Neumann
### C
* [Apprendre le langage C](https://www.youtube.com/playlist?list=PLrSOXFDHBtfEh6PCE39HERGgbbaIHhy4j) - Formation Video
* [Apprendre le langage C - Exercices](https://www.youtube.com/playlist?list=PLrSOXFDHBtfF6lXQpJ4hBha76DsQufiEQ) - Formation Video
* [Le Langage C](https://zestedesavoir.com/tutoriels/755/le-langage-c-1/) - sur Zeste de Savoir, Informaticienzero, Taure, Paraze, Lucas-84
* [TUTOS C](https://www.youtube.com/playlist?list=PLEagTQfI6nPOWS4JPnxW5pRVgeyLuS5oC) - PrimFX
### <a id="csharp"></a>C\#
* [C# - Cours](https://www.youtube.com/playlist?list=PLrSOXFDHBtfGBHAMEg9Om9nF_7R7h5mO7) - Formation Video
### <a id="cpp"></a>C++
* [La programmation en C++ moderne](https://zestedesavoir.com/tutoriels/822/la-programmation-en-c-moderne/) - Zeste de savoir informaticienzero mehdidou99
### Delphi
* [Apprendre la programmation avec Delphi](https://apprendre-delphi.fr/apprendre-la-programmation-avec-delphi-2020.php) - Patrick Prรฉmartin
### Git
* [Apprendre ร utiliser Git et GitHub \| Cours Complet (2020)](https://www.pierre-giraud.com/git-github-apprendre-cours/) - Pierre Giraud
* [Formation Git en vidรฉo, Cours Complet](https://www.youtube.com/playlist?list=PLjwdMgw5TTLXuY5i7RW0QqGdW0NZntqiP) - Grafikart
### HTML and CSS
* [Apprendre ร coder en HTML et CSS \| Cours complet (2020)](https://www.pierre-giraud.com/html-css-apprendre-coder-cours/) - Pierre Giraud
* [Apprendre ร utiliser le framework Bootstrap \| Cours complet (2020)](https://www.pierre-giraud.com/bootstrap-apprendre-cours/) - Pierre Giraud
* [Apprendre ร utiliser Sass \| Cours Complet (2020)](https://www.pierre-giraud.com/sass-apprendre-cours-complet/) - Pierre Giraud
* [Apprendre l'HTML](https://www.youtube.com/playlist?list=PLjwdMgw5TTLUeixVGPNl1uZNeJy4UY6qX) - Grafikart
* [Dรฉcouvrir CSS](https://www.youtube.com/playlist?list=PLjwdMgw5TTLVjTZQocrMwKicV5wsZlRpj) - Grafikart
* [Documentation du MDN](https://developer.mozilla.org/fr/) (MDN Mozilla)
* [HTML/CSS - Exercices](https://www.youtube.com/playlist?list=PLrSOXFDHBtfHEFVqv0pjGkPHv6PhWZQBb) - Formation Video
* [HTML/CSS - Tutoriels](https://www.youtube.com/playlist?list=PLrSOXFDHBtfG1_4HrfPttdwF8aLpgdsRL) - Formation Video
* [Le prรฉprocesseur SASS](https://www.youtube.com/playlist?list=PLjwdMgw5TTLWVp8WUGheSrGnmEWIMk9H6) - Grafikart
* [Tutoriel CSS](http://fr.html.net/tutorials/css/) - `trl.:` Jean Jacques Solari
* [Tutoriel HTML](http://fr.html.net/tutorials/html/) - `trl.:` Jean Jacques Solari
* [TUTOS HTML et CSS](https://www.youtube.com/playlist?list=PLEagTQfI6nPObScwsDmTCbLuZXRYfiUM-) - PrimFX
### Java
* [Cours Java](https://www.youtube.com/playlist?list=PLrSOXFDHBtfHkq8dd3BbSaopVgRSYtgPv) - Formation Video
### JavaScript
* [Apprendre ร coder en JavaScript \| Cours complet (2020)](https://www.pierre-giraud.com/javascript-apprendre-coder-cours/) - Pierre Giraud
* [Apprendre le JavaScript](https://www.youtube.com/playlist?list=PLjwdMgw5TTLVzD9Jq_WBd1crqDwXRn4cw) - Grafikart
* [Cours JavaScript](https://www.youtube.com/playlist?list=PLrSOXFDHBtfGxf_PtXLu_OrjFKt4_dqB_) - Formation Video
* [Dรฉboguer son code JavaScript](https://www.youtube.com/playlist?list=PLjwdMgw5TTLWWXgsHpfCLHJ1Oq4YnE08e) - Grafikart
* [Le Tutoriel JavaScript Moderne](https://fr.javascript.info) - javascript.info
* [TUTOS JS](https://www.youtube.com/playlist?list=PLEagTQfI6nPPVSKoYo2p8Cf8eijcyz5t9) - PrimFX
#### JQuery
* [Apprendre ร utiliser la bibliothรจque JavaScript jQuery \| Cours complet (2019)](https://www.pierre-giraud.com/jquery-apprendre-cours/) - Pierre Giraud
#### React
* [Apprendre React - Le framework](https://www.youtube.com/playlist?list=PLjwdMgw5TTLWom67YfZuha-1iYzIirwJR) - Grafikart
#### Vue.js
* [VueJS 2](https://www.youtube.com/playlist?list=PLjwdMgw5TTLW-mAtlR46VajrKs4dep3y0) - Grafikart
### Linux
* [Linux et Ubuntu - Administration Rรฉseau](https://www.tutoriels-video.fr/category/ubuntu/) - Alexis Madrzejewski
### Python
* [Apprendre ร programmer en Python \| Cours complet (2019)](https://www.pierre-giraud.com/python-apprendre-programmer-cours/) - Pierre Giraud
* [Apprendre Python](https://www.youtube.com/playlist?list=PLrSOXFDHBtfHg8fWBd7sKPxEmahwyVBkC) - Formation Video
### PHP
* [Apprendre Laravel 5.0.X](https://www.youtube.com/playlist?list=PLjwdMgw5TTLUCpXVEehCHs99N7IWByS3i) - Grafikart
* [Apprendre PHP](https://www.youtube.com/playlist?list=PLrSOXFDHBtfFuZttC17M-jNpKnzUL5Adc) - Formation Video
* [Apprendre PHP - Cours Complet + POO](https://www.youtube.com/playlist?list=PLjwdMgw5TTLVDv-ceONHM_C19dPW1MAMD) - Grafikart
* [Apprendre Symfony 4 par l'exemple](https://www.youtube.com/playlist?list=PLjwdMgw5TTLX7wmorGgfrqI9TcA8nMb29) - Grafikart
* [Cours complet de Pierre Giraud sur le dรฉveloppement PHP avec MySQL](https://www.pierre-giraud.com/php-mysql-apprendre-coder-cours/) - Pierre Giraud
* [Tester sur Symfony](https://www.youtube.com/playlist?list=PLjwdMgw5TTLWtWmdMzPaoc45Iztu7tVQ8) - Grafikart
* [Tutoriel PHP](http://fr.html.net/tutorials/php/) - `trl.:` Jean Jacques Solari
* [TUTOS PHP](https://www.youtube.com/playlist?list=PLEagTQfI6nPN2sdrLWhX_hO1pMOmC9JGU) - PrimFX
### Ruby
* [Apprendre Ruby](https://www.youtube.com/playlist?list=PLjwdMgw5TTLVVJHvstDYgqTCao-e-BgA8) - Grafikart
* [Apprendre Ruby on Rails 5.X](https://www.youtube.com/playlist?list=PLjwdMgw5TTLWfI1B2Wv2WPgR9iOyw12zi) - Grafikart
### SQL
* [Apprendre MySQL - Ancien Cours](https://www.youtube.com/playlist?list=PLjwdMgw5TTLUJLpzUYGBK7K5-hPgZA7zo) - Grafikart
* [SQL - Cours](https://www.youtube.com/playlist?list=PLrSOXFDHBtfGl66sXijiN8SU9YJaM_EQg) - Formation Video
### SysAdmin
* [Dรฉveloppement Web - Administration Rรฉseau](https://www.tutoriels-video.fr/category/webdev/) - Alexis Madrzejewski
| free-programming-books/courses/free-courses-fr.md/0 | {
"file_path": "free-programming-books/courses/free-courses-fr.md",
"repo_id": "free-programming-books",
"token_count": 2960
} | 69 |
### Index
* [Android](#android)
* [C](#c)
* [C#](#csharp)
* [C++](#cpp)
* [Compiladores](#compiladores)
* [Dart](#dart)
* [Database](#database)
* [Delphi](#delphi)
* [Docker](#docker)
* [Elixir](#elixir)
* [Flutter](#flutter)
* [Git](#git)
* [Go](#go)
* [Gulp](#gulp)
* [Haskell](#haskell)
* [HTML and CSS](#html-and-css)
* [IDE and editors](#ide-and-editors)
* [Ionic](#ionic)
* [Java](#java)
* [JavaScript](#javascript)
* [React](#react)
* [Vue.js](#vuejs)
* [Jekyll](#jekyll)
* [Kotlin](#kotlin)
* [Kubernetes](#kubernetes)
* [Linux](#linux)
* [Lua](#lua)
* [Machine Learning](#machine-learning)
* [Markdown](#markdown)
* [Networking](#networking)
* [Node.js](#nodejs)
* [PHP](#php)
* [Programaรงรฃo](#programaรงรฃo)
* [Python](#python)
* [R](#r)
* [Raspberry Pi](#raspberry-pi)
* [React Native](#react-native)
* [Ruby](#ruby)
* [Rust](#rust)
* [Sass](#sass)
* [Seguranรงa da Informaรงรฃo](#seguranรงa-da-informaรงรฃo)
* [SEO](#seo)
* [Shell](#shell)
* [Sistemas Embarcados](#sistemas-embarcados)
* [Smalltalk](#smalltalk)
* [Swift](#swift)
* [TypeScript](#typescript)
* [Angular](#angular)
* [WordPress](#wordpress)
### Android
* [Desenvolvedor Android Iniciante](https://www.udemy.com/desenvolvedor-android-iniciante/) - Gabriel Ferrari, Adriano Sacardo (Udemy)
* [Introduรงรฃo ao Desenvolvimento de Aplicativos Android](https://pt.coursera.org/learn/introducao-aplicativos-android) - Unicamp (Coursera)
### C
* [Aprenda C e C++ - Fundamentos Para Lรณgica de Programaรงรฃo](https://www.udemy.com/c-e-c-fundamentos-para-logica-de-programacao/) - One Day Code (Udemy)
* [Curso de C](https://www.youtube.com/playlist?list=PLesCEcYj003SwVdufCQM5FIbrOd0GG1M4) - Clรกudio Rogรฉrio Carvalho Filho (eXcript)
* [Curso de Programaรงรฃo C Completo](https://www.youtube.com/playlist?list=PLqJK4Oyr5WSjjEQCKkX6oXFORZX7ro3DA) - Programe seu futuro
* [Programaรงรฃo Moderna em C](https://www.youtube.com/playlist?list=PLIfZMtpPYFP5qaS2RFQxcNVkmJLGQwyKE) - Papo Binรกrio
### <a id="csharp"></a>C\#
* [C# e Windows Forms: Consultar CEP no WebService dos Correios](https://www.udemy.com/webservice-correios/) - Gilseone Moraes, Training4All Cursos (Udemy)
* [C# e Windows Forms: Encurtando URLs com a API do Bitly](https://www.udemy.com/bitly-api/) - Gilseone Moraes, Training4All Cursos (Udemy)
* [C# e Windows Forms: Utilizando Formulรกrios MDI Parent](https://www.udemy.com/formularios-mdi/) - Gilseone Moraes, Training4All Cursos (Udemy)
* [Curso de C# / .NET Para Iniciantes](https://www.youtube.com/playlist?list=PLkhtU8XJLj-5q4fcgUkjmrICOqWsgWNJr) - Fredi
* [Fundamentos do C#](https://balta.io/cursos/fundamentos-csharp) - Andrรฉ Baltieri (Balta.io)
* [Iniciando com ASP.NET Core](https://desenvolvedor.io/curso-online-iniciando-com-asp-net-core) - Eduardo Pires (Desenvolvedor.io)
* [Introduรงรฃo ao Entity Framework Core](https://desenvolvedor.io/curso-online-introducao-entity-framework-core) - Rafael Almeida (Desenvolvedor.io)
* [Manipulando Listas Genรฉricas em C#](https://www.udemy.com/listas-genericas-em-csharp/) - Gilseone Moraes, Training4All Cursos (Udemy)
### <a id="cpp"></a>C++
* [Curso C++](https://www.youtube.com/playlist?list=PLesCEcYj003QTw6OhCOFb1Fdl8Uiqyrqo) - Clรกudio Rogรฉrio Carvalho Filho (eXcript)
* [Curso de C++ - A linguagem de programaรงรฃo fundamental para quem quer ser um programador](https://www.youtube.com/playlist?list=PLx4x_zx8csUjczg1qPHavU1vw1IkBcm40) - Canal Fessor Bruno (CFBCursos)
### Compiladores
* [Compiladores](https://www.youtube.com/playlist?list=PL9-1FzPYzEfA-QTycUARDqIjakp_NJxe5) - Fรกbio Mendes
### Dart
* [Curso Dart](https://www.youtube.com/playlist?list=PLAqdhPoZdJtBnMfZtpExJlFTuuXE0TabS) - Luis Claudio Leite Pereira
* [Curso de Dart Lang](https://www.udemy.com/curso-de-dart-lang-completo/) - Sthefane Soares (Udemy)
* [Lรณgica de Programaรงรฃo com Dart](https://www.udemy.com/course/logica-de-programacao-com-dart/) - Jacob Moura (Udemy)
### Database
* [Curso de Banco de Dados MySQL](https://www.youtube.com/playlist?list=PLHz_AreHm4dkBs-795Dsgvau_ekxg8g1r) - Gustavo Guanabara, Curso em Video
* [Curso de Modelagem de Dados](https://www.youtube.com/playlist?list=PLucm8g_ezqNoNHU8tjVeHmRGBFnjDIlxD) - Bosรณn Treinamentos
* [Introduรงรฃo ao MySQL e phpMyAdmin](https://www.udemy.com/mysql-phpmyadmin/) - Fernando Carmo, Mestres BI (Udemy)
### Delphi
* [Aprenda Delphi e Lazarus do Zero - 100% Gratuito](https://www.udemy.com/aprenda-delphi-e-lazarus-do-zero/) - Marcos Fabricio Rosa (Udemy)
### Docker
* [Curso de Docker Completo](https://www.youtube.com/playlist?list=PLg7nVxv7fa6dxsV1ftKI8FAm4YD6iZuI4) - Robert Silva
* [Curso de Docker para iniciantes - aprenda Docker em 1 hora](https://www.youtube.com/watch?v=np_vyd7QlXk) - Matheus Battisti
### Elixir
* [Curso de Elixir Alquimia](https://www.youtube.com/playlist?list=PLv3nyCBtlWP8I9rknIrfcJWrO05yEzknD) - Alquimia Stone
* [Elixir (Linguagem de Programaรงรฃo)](https://www.youtube.com/playlist?list=PLydk1OOOmzo-AtU2l102ooounamleyMB9) - Elly Academy
### Flutter
* [Criando seu primeiro App com Flutter](https://balta.io/cursos/criando-seu-primeiro-app-com-flutter) - Andre Baltieri (balta.io)
* [Curso Arquitetura no Flutter - 2022](https://www.youtube.com/playlist?list=PLRpTFz5_57cvCYRhHUui2Bis-5Ybh78TS) - Deivid Willyan
* [Curso COMPLETO de Flutter](https://youtube.com/playlist?list=PLlBnICoI-g-d-J57QIz6Tx5xtUDGQdBFB) - Flutterando
* [Curso Flutter Bรกsico \[NV1\] - 2022](https://www.youtube.com/playlist?list=PLRpTFz5_57cvo0CHf-AnojOvpznz8YO7S) - Deivid Willyan
* [Curso Flutter Intermediรกrio \[NV2\] - 2022](https://www.youtube.com/playlist?list=PLRpTFz5_57cvYvKja5Ex92aQ_HNADo4Oh) - Deivid Willyan
### Git
* [Curso de Git](https://www.youtube.com/playlist?list=PLucm8g_ezqNq0dOgug6paAkH0AQSJPlIe) - Bรณson Treinamentos
* [Curso de Git e GitHub: grรกtis, prรกtico e sem usar comandos no terminal](https://www.youtube.com/playlist?list=PLHz_AreHm4dm7ZULPAmadvNhH6vk9oNZA) - Gustavo Guanabara
* [Git e contribuiรงรตes para projetos Open Source](https://www.udemy.com/course/git-e-github/) - Bruno Orlandi (Udemy)
* [Git e Github para iniciantes](https://www.udemy.com/git-e-github-para-iniciantes/) - Willian Justen de Vasconcellos (Udemy)
* [Git para iniciantes](https://www.udemy.com/git-para-iniciantes/) - Ricardo Netto (Udemy)
### Go
* [Aprenda Go / Golang (Curso Tutorial de Programaรงรฃo)](https://www.youtube.com/playlist?list=PLUbb2i4BuuzCX8CLeArvx663_0a_hSguW) - NBK Mundo Tech
* [Curso de Introduรงรฃo a Linguagem Go (Golang)](https://www.youtube.com/playlist?list=PLXFk6ROPeWoAvLMyJ_PPfu8oF0-N_NgEI) - EuProgramador
* [Curso Golang](https://www.youtube.com/playlist?list=PL3IMfVHTpXw14FL_TRIdHfeYTeOet1GS9) - Universo Mainframe
* [Go - Aprenda a Programar (Curso)](https://www.youtube.com/playlist?list=PLCKpcjBB_VlBsxJ9IseNxFllf-UFEXOdg) - Ellen Kรถrbes
* [Go 101 (Curso)](https://www.youtube.com/playlist?list=PLHPgIIn9ls6-1l7h8RUClMKPHi4NoKeQF) - Tiago Temporin
* [Golang do Zero](https://www.youtube.com/playlist?list=PL5aY_NrL1rjucQqO21QH8KclsLDYu1BIg) - Full Cycle
### Gulp
* [Curso de Gulp](https://www.udemy.com/curso-de-gulp/) - Fabio Ewerton (Udemy)
### Haskell
* [Curso Haskell para Iniciantes](https://www.udemy.com/curso-haskell/) - Marcos Castro (Udemy)
* [Desenvolvimento Orientado a Tipos](https://www.youtube.com/playlist?list=PLYItvall0TqKaY6qObQMlZ45Bo94xq9Ym) - UFABC
### HTML and CSS
* [Curso completo e atual de HTML5 e CSS3 - Mรณdulo 1 de 5](https://www.youtube.com/playlist?list=PLHz_AreHm4dkZ9-atkcmcBaMZdmLHft8n) - Gustavo Guanabara (Curso em Vรญdeo)
* [Curso completo e atual de HTML5 e CSS3 - Mรณdulo 2 de 5](https://www.youtube.com/playlist?list=PLHz_AreHm4dlUpEXkY1AyVLQGcpSgVF8s) - Gustavo Guanabara (Curso em Vรญdeo)
* [Curso completo e atual de HTML5 e CSS3 - Mรณdulo 3 de 5](https://www.youtube.com/playlist?list=PLHz_AreHm4dmcAviDwiGgHbeEJToxbOpZ) - Gustavo Guanabara (Curso em Vรญdeo)
* [Curso completo e atual de HTML5 e CSS3 - Mรณdulo 4 de 5](https://www.youtube.com/playlist?list=PLHz_AreHm4dkcVCk2Bn_fdVQ81Fkrh6WT) - Gustavo Guanabara (Curso em Vรญdeo)
* [Introduรงรฃo ร linguagem CSS](https://www.udemy.com/introducao-a-linguagem-css/) - Diego Mariano (Udemy)
* [Introduรงรฃo ร Linguagem HTML](https://www.udemy.com/introducao-a-linguagem-html/) - Diego Mariano (Udemy)
### IDE and editors
* [Domine o sublime text](https://www.udemy.com/course/domine-o-sublime-text/) - Alexandre Cardoso (Udemy)
* [Eclipse IDE para Desenvolvedores Java](https://www.udemy.com/eclipse-ide-para-desenvolvedores-java/) - Fernando Franzini (Udemy)
* [Intellij IDE para Desenvolvedores Java](https://www.udemy.com/intellij-ide-para-desenvolvedores-java/) - Fernando Franzini (Udemy)
* [Produtividade mรกxima com o VS Code (Visual Studio Code)](https://www.udemy.com/course/truques-vscode/) - Diego Martins de Pinho (Udemy)
### Ionic
* [Curso IONIC 6 ๐ - De 0 a PRO](https://www.youtube.com/playlist?list=PLsngLoGbAagFEG-jwlpPhGsLzMSQ0tadP) - Randy Varela
* [Desenvolvimento com Ionic 3 + WebComponents com StencilJS](https://www.udemy.com/ionic-3-e-webcomponents-com-stenciljs/) - Gabriel Barreto (Udemy)
* [Ionic 3 para iniciantes](https://www.udemy.com/ionic-3-para-iniciantes/) - Charles dos Santos Franรงa (Udemy)
### Java
* [Curso de Java Bรกsico](https://loiane.training/curso/java-basico) - Loiane Groner
* [Curso de Java Intermediรกrio](https://loiane.training/curso/java-intermediario) - Loiane Groner
* [Curso de Java para Iniciantes - Grรกtis, Completo e com Certificado](https://www.youtube.com/playlist?list=PLHz_AreHm4dkI2ZdjTwZA4mPMxWTfNSpR) - Gustavo Guanabara
* [Curso de Programaรงรฃo Orientada a Objetos em Java - Grรกtis, Completo e com Certificado](https://www.youtube.com/playlist?list=PLHz_AreHm4dkqe2aR0tQK74m8SFe-aGsY) - Gustavo Guanabara
* [Curso de Spring Boot - Criando um blog com Spring Boot e deploy na AWS Elastic Beanstalk](https://www.youtube.com/playlist?list=PL8iIphQOyG-AdKMQWtt1bqdVm8QUnX7_S) - Michelli Brito
* [Desenvolvedor Funcional com Java 8](https://www.udemy.com/desenvolvedor-funcional-com-java-8/) - Fernando Franzini (Udemy)
* [Desenvolvimento รgil com Java Avanรงado](https://www.coursera.org/learn/desenvolvimento-agil-com-java-avancado) - Eduardo Guerra, Clovis Fernandes - ITA (Coursera)
* [Desenvolvimento รgil com Padrรตes de Projeto](https://www.coursera.org/learn/desenvolvimento-agil-com-padroes-de-projeto) - Eduardo Guerra e Clovis Fernandes - ITA (Coursera)
* [Estrutura de Dados com Java](https://loiane.training/curso/estrutura-de-dados) - Loiane Groner
* [Introduรงรฃo ร Interfaces Grรกficas em Java com o NetBeans](https://www.udemy.com/introducao-a-interface-grafica-em-java-com-o-netbeans/) - Cezar Augusto Crummenauer (Udemy)
* [Introduรงรฃo ao Java e Orientaรงรฃo a objetos](https://www.udemy.com/introducao-ao-java-e-orientacao-a-objetos/) - Helder Guimaraes Aragao (Udemy)
* [Java SE - Polimorfismo](https://www.udemy.com/java-se-polimorfismo/) - Fernando Franzini (Udemy)
* [Orientaรงรฃo a Objetos com Java](https://www.coursera.org/learn/orientacao-a-objetos-com-java) - Eduardo Guerra e Clovis Fernandes - ITA (Coursera)
* [Princรญpios de Desenvolvimento รgil de Software](https://www.coursera.org/learn/principios-de-desenvolvimento-agil-de-software) - Eduardo Guerra e Clovis Fernandes - ITA (Coursera)
* [Produtos Java - Especificaรงรตes versus Proprietรกrios](https://www.udemy.com/produtos-java-especificacoes-versus-proprietarios/) - Fernando Franzini (Udemy)
* [TDD โ Desenvolvimento de software guiado por testes](https://www.coursera.org/learn/tdd-desenvolvimento-de-software-guiado-por-testes) - Eduardo Guerra e Clovis Fernandes - ITA (Coursera)
* [Testes unitรกrios com Java utilizando o Junit](https://www.udemy.com/testes-unidade-automaticos-software-junit/) - Gustavo Farias (Udemy)
### JavaScript
* [Curso de Javascript Completo](https://www.youtube.com/playlist?list=PL2Fdisxwzt_d590u3uad46W-kHA0PTjjw) - Programaรงรฃo Web
* [Curso Grรกtis de JavaScript e ECMAScript para Iniciantes](https://www.youtube.com/playlist?list=PLHz_AreHm4dlsK3Nr9GVvXCbpQyHQl1o1) - Gustavo Guanabara (Curso em Vรญdeo)
* [Curso Javascript Completo 2023 [Iniciantes] + 14 Mini-Projetos](https://www.youtube.com/watch?v=i6Oi-YtXnAU) - Jhonatan de Souza
* [Fast & Furious](https://www.youtube.com/playlist?list=PLy5T05I_eQYOoUz2TtAqq35RLCc-xBZCe) - Codecasts
* [Kubernetes para Devs Javascript](https://www.youtube.com/playlist?list=PLqFwRPueWb5ccEFVx5vOvrKlYT_uQ3aQw) - Erick Wendel, Lucas Santos
* [Testes no NodeJS aplicando TDD com Jest](https://www.youtube.com/watch?v=2G_mWfG0DZE) - Diego Fernandes
#### React
* [Aprenda Next.js,GraphQL e Leaflet na prรกtica!](https://www.youtube.com/playlist?list=PLR8OzKI52ppWoTRvAmB_FQPPlHS0otV7V) - Willian Justen
* [Bootcamp da Brainn de React](https://www.youtube.com/playlist?list=PLF7Mi9HNzvVmzOyDyl--xQVdi60jxduU1) - Canal Brainn Co.
* [Curso Intensivo de Next.js & React](https://www.cod3r.com.br/courses/curso-intensivo-next-react) - Leonardo Leitรฃo (Cod3r)
* [Next js 13.4 Masterclass Prรกtico c/ Stripe e Shadcn-ui](https://www.youtube.com/playlist?list=PLR8OzKI52ppWoTRvAmB_FQPPlHS0otV7V) - DeveloperDeck101
#### Vue.js
* [Aplicaรงรฃo Desktop com JavaScript, Electron JS e Vue JS](https://www.udemy.com/course/aplicacao-desktop-com-javascript-electron-js-e-vue-js/) - Leonardo Moura Leitao, Cod3r (Udemy)
* [Curso completo e gratuito de Vue.js 3 do iniciante ao avanรงado](https://igorhalfeld.teachable.com/p/treinamento-completo-e-gratuito-de-vue-js-3-do-iniciante-ao-avancado) - Igor Halfeld, Vue.js Brasil (Teachable)
* [Introduรงรฃo ao Vue JS](https://www.udemy.com/course/introducao-ao-vue-js/) - Rafael Rend (Udemy)
* [Minicurso: Vue.js - O basicรฃo](https://evolutio.io/curso/minicurso_vuejs) - Tony Lรขmpada (Evolutio)
### Jekyll
* [Criando sites estรกticos com Jekyll](https://www.udemy.com/course/criando-sites-estaticos-com-jekyll/) - Willian Justen de Vasconcellos (Udemy)
### Kotlin
* [Aprenda Kotlin do zero - Mรณdulo Bรกsico](https://www.udemy.com/kotlin-aprenda-do-zero-modulo-basico/) - Pedro Massango (Udemy)
* [Curso de Kotlin - Bรกsico](https://www.youtube.com/playlist?list=PLlGFv5gh9fBIJ8SEaQ_AKon-uenAlUbjE) - Rapadura Dev
* [Curso de Kotlin 2020 \| Bรกsico](https://www.youtube.com/playlist?list=PLPs3nlHFeKTr-aDDvUxU971rPSVTyQ6Bn) - Douglas Motta
* [Curso de Kotlin 2021](https://www.youtube.com/playlist?list=PL9dOBCBB2d-hhioxKoL6ODVILWcWuas8b) - Devaria
* [Desenvolvedor Kotlin Iniciante](https://www.udemy.com/desenvolvedor-kotlin-iniciante/) - Gabriel Ferrari, Adriano Sacardo (Udemy)
### Kubernetes
* [Maratona Kubernetes](https://www.youtube.com/playlist?list=PLB1hpnUGshULerdlzMknMLrHI810xIBJv&origin=CursosErickWendel) - Microsoft Brasil
### Linux
* [Curso de Linux - Primeiros Passos](https://www.youtube.com/playlist?list=PLHz_AreHm4dlIXleu20uwPWFOSswqLYbV) - Gustavo Guanabara
* [Introduรงรฃo ao Sistema Operacional Linux](https://www.udemy.com/course/linux-ubuntu/) - Diego Mariano (Udemy)
* [Terminal Linux](https://www.udemy.com/course/terminal-de-comandos-linux/) - Diego Mariano (Udemy)
### Lua
* [Curso de Programaรงรฃo Lua](https://youtube.com/playlist?list=PLa4jh645PxpfOYT5bNkim9yoevX8dCYpt) - Techiesse
* [Introduรงรฃo a Programaรงรฃo com Lua](https://www.youtube.com/playlist?list=PLqYboeh3Jru55Yq4J08zsBoOwwwjUtZNA) - Alfred R. Baudisch
### Machine Learning
* [Curso Data Science e Machine Learning](https://youtube.com/playlist?list=PLFE-LjWAAP9R4G0WOXWuha4P5cCvw7hGB) - Data ICMC
* [Curso Deep Learning](https://www.youtube.com/playlist?list=PLSZEVLiOtIgF19_cPrvhJC2bWn-dUh1zB) - Deep Learning Brasil
* [Machine Learning e Data Science: O Guia para Iniciantes](https://www.udemy.com/course/guia-iniciantes-machine-learning-data-science/) - Jones Granatyr (Udemy)
* [Neural Networks e Deep Learning para Leigos: Sem Mistรฉrios!](https://www.udemy.com/course/neural-networks-e-deep-learnig-para-leigos/) - Fernando Amaral (Udemy)
### Markdown
* [Aprenda Markdown](https://www.udemy.com/aprenda-markdown/) - Roberto Achar (Udemy)
### Networking
* [Curso de IPv6 Bรกsico a Distรขncia](http://saladeaula.nic.br/courses/course-v1:NIC.br+IPV6-001+T001/about) - NIC.br
* [Curso Redes de Computadores](https://www.youtube.com/playlist?list=PLHz_AreHm4dkd4lr9G0Up-W-YaHYdTDuP) - Gustavo Guanabara (Curso em Vรญdeo)
### Node.js
* [Criando APIs com NodeJs](https://www.youtube.com/playlist?list=PLHlHvK2lnJndvvycjBqQAbgEDqXxKLoqn) - Balta.io
* [Curso de Node](https://www.youtube.com/watch?v=XN705pQeoyU&list=PLx4x_zx8csUjFC41ev2qX5dnr-0ThpoXE) - Bruno CFBCursos
* [Curso de Node.js](https://www.youtube.com/playlist?list=PLJ_KhUnlXUPtbtLwaxxUxHqvcNQndmI4B) - Victor Lima Guia do Programador
* [Do Zero A Produรงรฃo: Aprenda A Construir Uma API Node.Js Com Typescript](https://www.youtube.com/playlist?list=PLz_YTBuxtxt6_Zf1h-qzNsvVt46H8ziKh) - Waldemar Neto Dev Lab
* [Imersรฃo em desenvolvimento de APIs com Node.js](https://erickwendel.teachable.com/p/node-js-para-iniciantes-nodebr) - Erick Wendel (Teachable)
* [RESTful com Node.js e Restify](https://www.youtube.com/playlist?list=PLy5T05I_eQYO5Y3S3kVqBxQzkUNllPazF) - Codecasts
* [Serie API NodeJS](https://www.youtube.com/playlist?list=PL85ITvJ7FLoiXVwHXeOsOuVppGbBzo2dp) - Diego Fernandes (Rocketseat)
* [Testes no NodeJS aplicando TDD com Jest](https://www.youtube.com/watch?v=2G_mWfG0DZE&list=PL85ITvJ7FLoh7QBmTVzuNYvZaYPYwDmei) - Diego Fernandes (Rocketseat)
### PHP
* [Boas prรกticas em PHP](https://www.udemy.com/boas-praticas-em-php/) - Diego Mariano (Udemy)
* [Curso Bรกsico de Bootstrap 4 , PHP e MySQL](https://www.udemy.com/curso-basico-de-bootstrap-4-php-e-mysql-gratis/) - Ricardo Milbrath Gonรงalves (Udemy)
* [Curso de CodeIgniter para iniciantes](https://www.youtube.com/playlist?list=PLInBAd9OZCzz2vtRFDwum0OyUmJg8UqDV) - RBtech
* [Curso de PHP para Iniciantes](https://www.youtube.com/playlist?list=PLHz_AreHm4dm4beCCCmW4xwpmLf6EHY9k) - Gustavo Guanabara (Curso em Vรญdeo)
* [Curso Introduรงรฃo ao Laravel 8](https://academy.especializati.com.br/curso/introducao-ao-laravel-8) - Carlos Ferreira (Especializati academy)
* [Introduรงรฃo ร Criaรงรฃo de Sites Dinรขmicos com PHP](https://www.udemy.com/criacao-de-paginas-de-internet-dinamicas-com-php-basico/) - Diego Mariano (Udemy)
* [Introduรงรฃo ao PHP orientado a objetos](https://www.udemy.com/php-orientado-a-objetos/) - Diego Mariano (Udemy)
* [Lรณgica de Programaรงรฃo com PHP](https://www.youtube.com/playlist?list=PLhTDLccA9vgHHwGZArcUqIZ5AUGwrbZ_A) - Curso Zend Framework
* [Login com validaรงรฃo e flash messages (PHP)](https://www.udemy.com/login-com-validacao-e-flash-messages-php/) - Alexandre Cardoso (Udemy)
* [PDO para quem nรฃo sabe PDO](https://www.udemy.com/pdo-para-quem-nao-sabe-pdo/) - Alexandre Cardoso (Udemy)
* [PHP 7 do Bรกsico ao Intermediรกrio](https://www.udemy.com/php-do-basico-ao-intermediario/) - Gunnar Correa (Udemy)
* [PHP para quem entende PHP](https://www.udemy.com/php-para-quem-entende-php/) - Alexandre Cardoso (Udemy)
### Programaรงรฃo
* [Algoritmos de Ordenaรงรฃo](https://www.youtube.com/playlist?list=PLzZut2slkqywtFxqTY8AQwIG65h_2oMBL) - Bruno Ribas
* [Curso Lรณgica de Programaรงรฃo Completo 2023 [Iniciantes] + Desafios + Muita prรกtica](https://www.youtube.com/watch?v=iF2MdbrTiBM) - Jonathan de Souza
### Python
* [Algoritmos em Python](https://algoritmosempython.com.br) - Douglas do Couto
* [Aprenda Python 3 em 6 horas](https://www.udemy.com/course/aprenda-python-3-em-6h/) - Alcimar A. Costa (Udemy)
* [Aulas Python](https://www.youtube.com/playlist?list=PLfCKf0-awunOu2WyLe2pSD2fXUo795xRe) - Ignorรขncia zero (You Tube)
* [Construindo API's robustas utilizando Python](https://github.com/luizalabs/tutorial-python-brasil) - Cรกssio Botaro, et al.
* [Curso de Programaรงรฃo em Python](https://www.youtube.com/playlist?list=PLFKhhNd35zq_INvuX9YzXIbtpo_LGDzYK) - Prime Cursos do Brasil
* [Curso de Python](https://www.youtube.com/playlist?list=PLesCEcYj003QxPQ4vTXkt22-E11aQvoVj) - Clรกudio Rogรฉrio Carvalho Filho (eXcript)
* [Curso de Python 3 - Mundo 1: Fundamentos](https://www.youtube.com/playlist?list=PLHz_AreHm4dlKP6QQCekuIPky1CiwmdI6) - Gustavo Guanabara (Curso em Vรญdeo)
* [Curso de Python 3 - Mundo 2: Estruturas de Controle](https://www.youtube.com/playlist?list=PLHz_AreHm4dk_nZHmxxf_J0WRAqy5Czye) - Gustavo Guanabara (Curso em Vรญdeo)
* [Curso de Python 3 - Mundo 3: Estruturas Compostas](https://www.youtube.com/playlist?list=PLHz_AreHm4dksnH2jVTIVNviIMBVYyFnH) - Gustavo Guanabara (Curso em Vรญdeo)
* [Curso em vรญdeo - Python](https://www.youtube.com/playlist?list=PLvE-ZAFRgX8hnECDn1v9HNTI71veL3oW0) - Gustavo Guanabara, Joao Pedro Araujo (Curso em Vรญdeo)
* [Data Science: Visualizaรงรฃo de Dados com Python](https://www.udemy.com/visualizacao-de-dados-com-python/) - Diego Mariano (Udemy)
* [Django 2.0 - Aprendendo os conceitos fundamentais](https://www.udemy.com/django-20-aprendendo-os-conceitos-fundamentais/) - Gregory Pacheco (Udemy)
* [Do zero ร implantaรงรฃo](https://cassiobotaro.dev/do_zero_a_implantacao/) - Cรกssio Botaro
* [Estruturas compostas em Python](https://www.youtube.com/playlist?list=PLHz_AreHm4dksnH2jVTIVNviIMBVYyFnH) - Gustavo Guanabara (Curso em Vรญdeo)
* [Estruturas de controle em Python](https://www.youtube.com/playlist?list=PLHz_AreHm4dk_nZHmxxf_J0WRAqy5Czye) - Gustavo Guanabara (Curso em Vรญdeo)
* [Fundamentamentos em Python](https://www.youtube.com/playlist?list=PLHz_AreHm4dlKP6QQCekuIPky1CiwmdI6) - Gustavo Guanabara (Curso em Vรญdeo)
* [Introduรงรฃo ร Ciรชncia da Computaรงรฃo com Python - Parte 1](https://pt.coursera.org/learn/ciencia-computacao-python-conceitos) - USP (Coursera)
* [Introduรงรฃo ร Ciรชncia da Computaรงรฃo com Python - Parte 2](https://pt.coursera.org/learn/ciencia-computacao-python-conceitos-2) - USP (Coursera)
* [Introduรงรฃo a linguagem de programaรงรฃo python](https://www.udemy.com/introducao-programacaopython/) - Abraรฃo Passos de Oliveira (Udemy)
* [Introduรงรฃo ร linguagem Python](https://www.udemy.com/intro_python/) - Diego Mariano (Udemy)
* [Programaรงรฃo em Python](https://www.youtube.com/playlist?list=PLucm8g_ezqNrrtduPx7s4BM8phepMn9I2) - Bรณson Treinamentos
* [Programaรงรฃo em Python: O Guia para Iniciantes](https://www.udemy.com/course/programacao-python-guia-para-iniciantes/) - Jones Granatyr (Udemy)
* [Python 3 na Prรกtica](https://www.udemy.com/python-3-na-pratica/) - Joรฃo Batista (Udemy)
* [Python 3 na Web com Django (Bรกsico e Intermediรกrio)](https://www.udemy.com/python-3-na-web-com-django-basico-intermediario/) - Gileno Alves Santa Cruz Filho (Udemy)
* [Python Bรกsico](https://solyd.com.br/treinamentos/python-basico) - Guilherme Junqueira (Solyd Offensive Security)
* [Python Fundamentos para Anรกlise de Dados](https://www.datascienceacademy.com.br/course?courseid=python-fundamentos) - Data Science Academy
* [Python para Competiรงรตes de Programaรงรฃo](https://www.youtube.com/playlist?list=PLMxflQ9_eOd9CY6Id5gfs3Edqt8vLC47p) - Adorilson
* [Python para Iniciantes](https://www.udemy.com/python-para-iniciantes/) - Tiago Miguel (Udemy)
* [Selenium com Python](https://www.youtube.com/playlist?list=PLOQgLBuj2-3LqnMYKZZgzeC7CKCPF375B) - Eduardo Mendes
### R
* [Curso de R com R Studio](https://www.youtube.com/playlist?list=PLzWDDw1w8cTS4i_B49WOWtjngjcMqTruG) - Escola de Inteligรชncia Artificial
* [Curso R para Iniciantes](https://www.youtube.com/playlist?list=PLyqOvdQmGdTQ5dE6hSD7ZGBu8bud70wYf) - Didรกtica Tech
### Raspberry Pi
* [Curso de Raspberry Pi: primeiros passos](https://www.youtube.com/playlist?list=PLHz_AreHm4dnGZ_nudmN4rvyLk2fHFRzy) - Gustavo Guanabara
### React Native
* [Aprenda React Native](https://www.youtube.com/playlist?list=PL8fIRnD1uUSnRqz3E2caAWDqbtIFXmNtW) - Canal Geek Dev
* [Curso React Native (aprendiz)](https://www.youtube.com/playlist?list=PLdDT8if5attEd4sRnZBIkNihR-_tE612_) - One Bit Code
### Ruby
* [Curso de Ruby on Rails para Iniciantes](https://www.youtube.com/playlist?list=PLe3LRfCs4go-mkvHRMSXEOG-HDbzesyaP) - Jackson Pires
* [Ruby on Rails 5 na Prรกtica](https://www.udemy.com/ruby-on-rails-5-na-pratica/) - Bruno Paulino (Udemy)
* [Ruby Para Iniciantes](https://www.udemy.com/ruby-para-iniciantes/) - Bruno Paulino (Udemy)
* [Ruby Puro](https://onebitcode.com/course/ruby-puro/) - One Bit Code (Site One Bit Code)
* [Tutorial Rails Girls](http://guides.railsgirls.com/guides-ptbr/)
### Rust
* [Programando do 0 ao avanรงado na linguagem de programaรงรฃo Rust](https://www.youtube.com/playlist?list=PLWmXJQDlXOHX6UdAmXv6euoqDPUtMLpJf) - Lanby 0xff3 ฮป
### Sass
* [Sass placeholders: o jeito certo](https://www.udemy.com/course/sass-placeholders-o-jeito-certo/) - Tรกrcio Zemel (Udemy)
### Shell
* [Conceitos de Programaรงรฃo em Shell Script](https://www.udemy.com/conceitos-de-programacao-em-shell-script/) - TemWeb (Udemy)
* [Curso de Shell Scripting - Programaรงรฃo no Linux](https://www.youtube.com/playlist?list=PLucm8g_ezqNrYgjXC8_CgbvHbvI7dDfhs) - Bรณson Treinamentos
* [Curso Shell GNU](https://www.youtube.com/playlist?list=PLXoSGejyuQGqJEEyo2fY3SA-QCKlF2rxO) - debxp
### Sistemas Embarcados
* [Fundamentos de Sistemas Embarcados](https://www.youtube.com/playlist?list=PLqvo6YdcIqXXGY1dLbf_xA-JLMBumTyzG) - Renato Sampaio
### Smalltalk
* [Conhecendo o SmallTalk](https://www.researchgate.net/publication/262882317_Conhecendo_o_Smalltalk_-_Todos_os_Detalhes_da_Melhor_Linguagem_de_Programacao_Orientada_a_Objetos) - Daniel Duarte Abdala, Aldo von Wangenheim (PDF)
* [Introduรงรฃo ร Programaรงรฃo Orientada a Objetos com Smalltalk](https://dcc.ufrj.br/~jonathan/smalltalk/Introd-a-POO-com-Smalltalk-1994.pdf) - Miguel Jonathan (PDF)
### Swift
* [Aprendendo Swift do Iniciante ao Avanรงado. (Mac e Windows)](https://www.udemy.com/aprendendoswift3/) - Lucas Alencar (Udemy)
* [Curso de Swift - Programaรงรฃo](https://www.youtube.com/playlist?list=PLJ0AcghBBWShgIH122uw7H9T9-NIaFpP-) - Tiago Aguiar
### TypeScript
* [Mini-curso de TypeScript](https://www.youtube.com/playlist?list=PLlAbYrWSYTiPanrzauGa7vMuve7_vnXG_) - Willian Justen Curso
* [TypeScript - Aprendendo Junto](https://www.youtube.com/playlist?list=PL62G310vn6nGg5OzjxE8FbYDzCs_UqrUs) - DevDojo
* [Typescript - Zero to Hero](https://github.com/glaucia86/curso-typescript-zero-to-hero) - Glaucia Lemos
* [TypeScript, o inรญcio, de forma prรกtica](https://www.youtube.com/watch?v=0mYq5LrQN1s) - Rocketseat, Diego Fernandes
#### Angular
* [Comeรงando com Angular](https://balta.io/cursos/comecando-com-angular) - Andre Baltieri (balta.io)
* [Curso Angular 9](https://www.youtube.com/playlist?list=PLdPPE0hUkt0rPyAkdhHIIquKbwrGUkvw3) - Cod3r
* [Curso de Angular](https://loiane.training/curso/angular/) - Loiane Groner
### WordPress
* [Curso de Loja Virtual: WooCommerce + WordPress](https://www.youtube.com/playlist?list=PLHz_AreHm4dkZNE5PAYc0h4iVkqBCgBZR) - Gustavo Guanabara (Curso em Vรญdeo)
* [Curso de WordPress 2022 Grรกtis e Completo](https://www.youtube.com/playlist?list=PLltHgIJnfTsAnyA8KPXC6ohTYzGEreVEa) - CursoB Cursos Online
* [Curso de WordPress: Criando um site do zero](https://www.youtube.com/playlist?list=PLHz_AreHm4dmDP_RWdiKekjTEmCuq_MW2) - Gustavo Guanabara (Curso em Vรญdeo)
### Seguranรงa da Informaรงรฃo
* [Boas Prรกticas de Seguranรงa da Informaรงรฃo para Sua Empresa](https://www.udemy.com/course/empresa-mais-segura/) - Afonso da Silva E. (Udemy)
* [Curso de Seguranรงa da Informaรงรฃo](https://www.youtube.com/playlist?list=PLHz_AreHm4dkYS6J9KeYgCCVpo5OXkvgE) - Gustavo Guanabara, (Curso em Video)
* [Seguranรงa da Informaรงรฃo: Por onde iniciar sua carreira](https://www.udemy.com/course/seguranca-da-informacao-por-onde-iniciar-sua-carreira/) - Alexandro Silva (Udemy)
### SEO
* [Curso de SEO - Mรฃo na massa](https://www.youtube.com/playlist?list=PLVPIs-7SxXA_O-fUH5PbKhEHdTPnYKMiE) - Flavio Klens (Agรชncia Klens)
* [Curso prรกtico de SEO](https://www.youtube.com/playlist?list=PLHz_AreHm4dm4pBTRvBFMpSXvEoymoa90) - Gustavo Guanabara (Curso em Video)
| free-programming-books/courses/free-courses-pt_BR.md/0 | {
"file_path": "free-programming-books/courses/free-courses-pt_BR.md",
"repo_id": "free-programming-books",
"token_count": 11865
} | 70 |
# ฮฯฮดฮนฮบฮฑฯ ฮฮตฮฟฮฝฯฮฟฮปฮฟฮณฮฏฮฑฯ ฮฃฯ
ฮฝฮตฮนฯฯฮตฯฯฮฝฯฯฮฝ
ฮฉฯ ฯฯ
ฮฝฮตฮนฯฯฮญฯฮฟฮฝฯฮตฯ ฮบฮฑฮน ฯฯ
ฮฝฯฮทฯฮทฯฮญฯ ฮฑฯ
ฯฮฟฯ ฯฮฟฯ
ฮญฯฮณฮฟฯ
, ฮบฮฑฮน ฯฯฮฟฮบฮตฮนฮผฮญฮฝฯ ฮฝฮฑ
ฯฯฮฟฯฮธฮฎฯฮฟฯ
ฮผฮต ฮผฮนฮฑ ฮฑฮฝฮฟฮนฯฯฮฎ ฮบฮฑฮน ฯฮนฮปฯฮพฮตฮฝฮท ฮบฮฟฮนฮฝฯฯฮทฯฮฑ, ฮดฮตฯฮผฮตฯ
ฯฮผฮฑฯฯฮต ฮฝฮฑ ฯฮตฮฒฯฮผฮฑฯฯฮต ฯฮปฮฟฯ
ฯ ฯฮฟฯ
ฯ ฮฑฮฝฮธฯฯฯฮฟฯ
ฯ ฯฮฟฯ
ฯฯ
ฮฝฮตฮนฯฯฮญฯฮฟฯ
ฮฝ ฮผฮญฯฯ ฯฯฮฝ ฮฑฮฝฮฑฯฮฟฯฯฮฝ ฮถฮทฯฮทฮผฮฌฯฯฮฝ, ฯฮทฮฝ ฮฑฮฝฮฌฯฯฮทฯฮท ฮฑฮนฯฮทฮผฮฌฯฯฮฝ ฮณฮนฮฑ ฮฝฮญฮตฯ ฮปฮตฮนฯฮฟฯ
ฯฮณฮฏฮตฯ, ฯฮทฮฝ ฮตฮฝฮทฮผฮญฯฯฯฮท
ฯฮฟฯ
documentation, ฯฮทฮฝ ฯ
ฯฮฟฮฒฮฟฮปฮฎ pull requests ฮฎ patch, ฮบฮฑฮน ฮฌฮปฮปฯฮฝ ฮดฯฮฑฯฯฮทฯฮนฮฟฯฮฎฯฯฮฝ.
ฮฮตฯฮผฮตฯ
ฯฮผฮฑฯฯฮต ฮฝฮฑ ฮบฮฌฮฝฮฟฯ
ฮผฮต ฯฮท ฯฯ
ฮผฮผฮตฯฮฟฯฮฎ ฯฮต ฮฑฯ
ฯฯ ฯฮฟ ฮญฯฮณฮฟ ฮผฮนฮฑ ฮตฮผฯฮตฮนฯฮฏฮฑ ฯฯฯฮฏฯ ฯฮฑฯฮตฮฝฯฯฮปฮทฯฮท ฮณฮนฮฑ ฮบฮฑฮฝฮญฮฝฮฑฮฝ,
ฮฌฯฯฮตฯฮฑ ฮฑฯฯ ฯฮฟ ฮตฯฮฏฯฮตฮดฮฟ ฯฮทฯ ฮตฮผฯฮตฮนฯฮฏฮฑฯ, ฯฮฟฯ
ฯฯฮปฮฟฯ
, ฯฮทฯ ฯฮฑฯ
ฯฯฯฮทฯฮฑฯ ฯฯฮปฮฟฯ
ฮบฮฑฮน ฮญฮบฯฯฮฑฯฮทฯ, ฯฮตฮพฮฟฯ
ฮฑฮปฮนฮบฮฎฯ ฯฯฮฟฯฮฏฮผฮทฯฮทฯ,
ฮฑฮฝฮฑฯฮทฯฮฏฮฑฯ, ฯฯฮผฮฑฯฮฟฯ, ฯฯ
ฮปฮฎฯ, ฮตฮธฮฝฮนฮบฯฯฮทฯฮฑฯ, ฮทฮปฮนฮบฮฏฮฑฯ, ฮธฯฮทฯฮบฮตฮฏฮฑฯ, ฮฎ ฮนฮธฮฑฮณฮญฮฝฮตฮนฮฑฯ.
ฮ ฮฑฯฮฑฮดฮตฮฏฮณฮผฮฑฯฮฑ ฮผฮท ฮฑฯฮฟฮดฮตฮบฯฮฎฯ ฯฯ
ฮผฯฮตฯฮนฯฮฟฯฮฌฯ ฮฑฯฯ ฯฮฟฯ
ฯ ฯฯ
ฮผฮผฮตฯฮญฯฮฟฮฝฯฮตฯ ฯฮตฯฮนฮปฮฑฮผฮฒฮฌฮฝฮฟฯ
ฮฝ:
* ฮคฮท ฯฯฮฎฯฮท ฯฮตฮพฮฟฯ
ฮฑฮปฮนฮบฮฟฯฮฟฮนฮทฮผฮญฮฝฮทฯ ฮณฮปฯฯฯฮฑฯ ฮฎ ฮตฮนฮบฯฮฝฮฑฯ
* ฮ ฯฮฟฯฯฯฮนฮบฮญฯ ฮตฯฮนฮธฮญฯฮตฮนฯ
* ฮคฯฮฟฮปฮฌฯฮนฯฮผฮฑ ฮฎ ฯ
ฮฒฯฮนฯฯฮนฮบฮฌ/ฯ
ฯฮฟฯฮนฮผฮทฯฮนฮบฮฌ ฯฯฯฮปฮนฮฑ
* ฮฮทฮผฯฯฮนฮฑ ฮฎ ฮนฮดฮนฯฯฮนฮบฮฎ ฯฮฑฯฮตฮฝฯฯฮปฮทฯฮท
* ฮฮทฮผฮฟฯฮนฮฟฯฮฟฮฏฮทฯฮท ฯฯฮฟฯฯฯฮนฮบฯฮฝ ฯฮปฮทฯฮฟฯฮฟฯฮนฯฮฝ ฮฌฮปฮปฯฮฝ, ฯฯฯฯ ฯฯ
ฯฮนฮบฮญฯ
ฮฎ ฮทฮปฮตฮบฯฯฮฟฮฝฮนฮบฮญฯ ฮดฮนฮตฯ
ฮธฯฮฝฯฮตฮนฯ, ฯฯฯฮฏฯ ฯฮทฯฮฎ ฮฌฮดฮตฮนฮฑ
* ฮฮนฮฑฮดฮฎฯฮฟฯฮต ฮฑฮฝฮฎฮธฮนฮบฮท ฮท ฮฑฮฝฯฮนฮตฯฮฑฮณฮณฮตฮปฮผฮฑฯฮนฮบฮฎ ฯฯ
ฮผฯฮตฯฮนฯฮฟฯฮฌ
ฮฮน ฯฯ
ฮฝฯฮทฯฮทฯฮญฯ ฯฮฟฯ
ฮญฯฮณฮฟฯ
ฮญฯฮฟฯ
ฮฝ ฯฮฟ ฮดฮนฮบฮฑฮฏฯฮผฮฑ ฮบฮฑฮน ฯฮทฮฝ ฮตฯ
ฮธฯฮฝฮท ฮฝฮฑ ฮฑฯฮฑฮนฯฮญฯฮฟฯ
ฮฝ, ฮฝฮฑ ฮตฯฮตฮพฮตฯฮณฮฑฯฯฮฟฯฮฝ,
ฮฎ ฮฝฮฑ ฮฑฯฮฟฯฯฮฏฯฮฟฯ
ฮฝ ฯฯฯฮปฮนฮฑ, commits, ฮบฯฮดฮนฮบฮฑ, ฮตฯฮตฮพฮตฯฮณฮฑฯฮฏฮฑ ฯฯฮฝ wikis, issues, ฮบฮฑฮน ฮฌฮปฮปฮตฯ ฯฯ
ฮฝฮตฮนฯฯฮฟฯฮญฯ
ฯฮฟฯ
ฮดฮตฮฝ ฯฯ
ฮฝฮฌฮดฮฟฯ
ฮฝ ฮผฮต ฮฑฯ
ฯฯฮฝ ฯฮฟฮฝ ฮฯฮดฮนฮบฮฑ ฮฮตฮฟฮฝฯฮฟฮปฮฟฮณฮฏฮฑฯ, ฮฎ ฮฝฮฑ ฮฑฯฮฑฮณฮฟฯฮตฯฯฮฟฯ
ฮฝ ฯฮทฮฝ ฯฯฯฯฮฒฮฑฯฮท ฯฯฮฟฯฯฯฮนฮฝฮฌ ฮฎ
ฮผฯฮฝฮนฮผฮฑ ฯฮต ฮฟฯฮฟฮนฮฟฮฝฮดฮฎฯฮฟฯฮต ฯฯ
ฮฝฮตฮนฯฯฮญฯฮฟฮฝฯฮฑ ฮณฮนฮฑ ฮฌฮปฮปฮตฯ ฯฯ
ฮผฯฮตฯฮนฯฮฟฯฮญฯ ฯฮฟฯ
ฮธฮตฯฯฮฟฯฮฝ ฮฑฮบฮฑฯฮฌฮปฮปฮทฮปฮตฯ, ฮฑฯฮตฮนฮปฮทฯฮนฮบฮญฯ,
ฯฯฮฟฯฮฒฮปฮทฯฮนฮบฮญฯ, ฮฎ ฮตฯฮนฮฒฮปฮฑฮฒฮตฮฏฯ.
ฮฅฮนฮฟฮธฮตฯฯฮฝฯฮฑฯ ฯฮฟฮฝ ฮฯฮดฮนฮบฮฑ ฮฮตฮฟฮฝฯฮฟฮปฮฟฮณฮฏฮฑฯ, ฮฟฮน ฯฯ
ฮฝฯฮทฯฮทฯฮญฯ ฯฮฟฯ
ฮญฯฮณฮฟฯ
ฮดฮตฯฮผฮตฯฮฟฮฝฯฮฑฮน ฮฝฮฑ ฮตฯฮฑฯฮผฯฮถฮฟฯ
ฮฝ ฮดฮฏฮบฮฑฮนฮฑ
ฮบฮฑฮน ฮผฮต ฯฯ
ฮฝฮญฯฮตฮนฮฑ ฮฑฯ
ฯฮญฯ ฯฮนฯ ฮฑฯฯฮญฯ ฯฮต ฮบฮฌฮธฮต ฯฯฯ
ฯฮฎ ฯฮทฯ ฮดฮนฮฑฯฮตฮฏฯฮนฯฮทฯ ฮฑฯ
ฯฮฟฯ ฯฮฟฯ
ฮญฯฮณฮฟฯ
. ฮฮน ฯฯ
ฮฝฯฮทฯฮทฯฮญฯ ฯฮฟฯ
ฮญฯฮณฮฟฯ
ฯฮฟฯ
ฮดฮตฮฝ ฮฑฮบฮฟฮปฮฟฯ
ฮธฮฟฯฮฝ ฮฎ ฮตฯฮนฮฒฮฌฮปฮปฮฟฯ
ฮฝ ฯฮทฮฝ ฮตฯฮฑฯฮผฮฟฮณฮฎ ฯฮฟฯ
ฮฯฮดฮนฮบฮฑ ฮฮตฮฟฮฝฯฮฟฮปฮฟฮณฮฏฮฑฯ ฮตฮฝฮดฮญฯฮตฯฮฑฮน ฮฝฮฑ ฮฑฯฮฑฮนฯฮตฮธฮฟฯฮฝ ฮผฯฮฝฮนฮผฮฑ
ฮฑฯฯ ฯฮทฮฝ ฮฟฮผฮฌฮดฮฑ.
ฮฯ
ฯฯฯ ฮฟ ฮบฯฮดฮนฮบฮฑฯ ฮดฮตฮฟฮฝฯฮฟฮปฮฟฮณฮฏฮฑฯ ฮนฯฯฯฮตฮน ฯฯฯฮฟ ฯฮต ฯฯฯฮฟฯ
ฯ ฯฮฟฯ
ฮญฯฮณฮฟฯ
ฯฯฮฟ ฮบฮฑฮน ฯฮต ฮดฮทฮผฯฯฮนฮฟฯ
ฯ ฯฯฯฮฟฯ
ฯ ฯฯฮฑฮฝ ฮญฮฝฮฑ ฮฌฯฮฟฮผฮฟ
ฮตฮบฯฯฮฟฯฯฯฮตฮฏ ฯฮฟ ฮญฯฮณฮฟ ฮฎ ฯฮทฮฝ ฮบฮฟฮนฮฝฯฯฮทฯฮฌ ฯฮฟฯ
.
ฮ ฮตฯฮนฯฯฯฯฮตฮนฯ ฮบฮฑฯฮฑฯฯฮทฯฯฮนฮบฮฎฯ, ฮตฮฝฮฟฯฮปฮทฯฮนฮบฮฎฯ, ฮฎ ฮณฮตฮฝฮนฮบฮฌ ฮฑฯฮฑฯฮฌฮดฮตฮบฯฮทฯ ฯฯ
ฮผฯฮตฯฮนฯฮฟฯฮฌฯ ฮผฯฮฟฯฮตฮฏ ฮฝฮฑ ฮฑฮฝฮฑฯฮตฯฮธฮตฮฏ ฮตฯฮนฮบฮฟฮนฮฝฯฮฝฯฮฝฯฮฑฯ
ฮญฮฝฮฑฮฝ ฯฯ
ฮฝฯฮทฯฮทฯฮฎ ฯฯฮฟ victorfelder at gmail.com. ฮฮปฮฑ ฯฮฑ ฯฮฑฯฮฌฯฮฟฮฝฮฑ ฮธฮฑ ฮตฯฮนฮธฮตฯฯฮทฮธฮฟฯฮฝ ฮบฮฑฮน ฮธฮฑ ฮตฯฮตฯ
ฮฝฮทฮธฮฟฯฮฝ ฮบฮฑฮน ฮธฮฑ ฮฟฮดฮทฮณฮฎฯฮฟฯ
ฮฝ
ฯฮต ฮผฮนฮฑ ฮฑฯฮฌฮฝฯฮทฯฮท ฮท ฮฟฯฮฟฮฏฮฑ ฮธฮตฯฯฮตฮฏฯฮฑฮน ฮฑฯฮฑฯฮฑฮฏฯฮทฯฮท ฮบฮฑฮน ฮบฮฑฯฮฌฮปฮปฮทฮปฮท ฯฯฮนฯ ฯฮตฯฮนฯฯฮฌฯฮตฮนฯ. ฮฮน ฯฯ
ฮฝฯฮทฯฮทฯฮญฯ ฮตฮฏฮฝฮฑฮน ฯ
ฯฮฟฯฯฮตฯฮผฮญฮฝฮฟฮน ฮฝฮฑ
ฮดฮนฮฑฯฮทฯฮฟฯฮฝ ฯฮปฮฎฯฮท ฮตฮผฯฮนฯฯฮตฯ
ฯฮนฮบฯฯฮทฯฮฑ ฯฮต ฯ,ฯฮน ฮฑฯฮฟฯฮฌ ฯฮฟ ฮฌฯฮฟฮผฮฟ ฯฮฟฯ
ฯ
ฯฮฟฮฒฮฌฮปฮตฮน ฯฮทฮฝ ฮฑฮฝฮฑฯฮฟฯฮฌ ฮณฮนฮฑ ฮญฮฝฮฑ ฯฯ
ฮผฮฒฮฌฮฝ.
ฮฯ
ฯฯฯ ฮฟ ฮฯฮดฮนฮบฮฑฯ ฮฮตฮฟฮฝฯฮฟฮปฮฟฮณฮฏฮฑฯ ฯฯฮฟฯฮฑฯฮผฯฯฯฮทฮบฮต ฮฑฯฯ ฯฮฟ [Contributor Covenant][homepage],
ฮฮบฮดฮฟฯฮท 1.3.0, ฮดฮนฮฑฮธฮญฯฮนฮผฮท ฯฯฮฟ https://contributor-covenant.org/version/1/3/0/
[homepage]: https://contributor-covenant.org
[Translations](README.md#translations)
| free-programming-books/docs/CODE_OF_CONDUCT-el.md/0 | {
"file_path": "free-programming-books/docs/CODE_OF_CONDUCT-el.md",
"repo_id": "free-programming-books",
"token_count": 2774
} | 71 |
# Kodeks postฤpowania wspรณลtwรณrcy
Jako wspรณลtwรณrcy i opiekunowie tego projektu oraz w celu wspierania otwartej i przyjaznej spoลecznoลci, zobowiฤ
zujemy siฤ szanowaฤ wszystkich ludzi, ktรณrzy przyczyniajฤ
siฤ do zgลaszania problemรณw, publikowania prรณลb o nowe funkcje, aktualizowania dokumentacji, przesyลania ลผฤ
daล lub poprawek oraz innych dziaลaล.
Zaleลผy nam na tym, aby udziaล w tym projekcie byล doลwiadczeniem wolnym od nฤkania dla wszystkich, niezaleลผnie od poziomu doลwiadczenia, pลci, toลผsamoลci i ekspresji pลciowej, orientacji seksualnej, niepeลnosprawnoลci, wyglฤ
du osobistego, budowy ciaลa, rasy, pochodzenia etnicznego, wieku, religii, lub narodowoลฤ.
Przykลady niedopuszczalnego zachowania uczestnikรณw obejmujฤ
:
* Uลผywanie jฤzyka lub obrazรณw o charakterze seksualnym
* Ataki osobiste
* Trolling lub obraลบliwe/uwลaczajฤ
ce komentarze
* Nฤkanie publiczne lub prywatne
* Publikowanie prywatnych informacji innych osรณb, takich jak adresy fizyczne lub elektroniczne, bez wyraลบnej zgody
* Inne nieetyczne lub nieprofesjonalne zachowanie
Opiekunowie projektรณw majฤ
prawo i odpowiedzialnoลฤ za usuwanie, edytowanie lub odrzucanie komentarzy, zatwierdzeล, kodu, edycji wiki, problemรณw i innych wkลadรณw, ktรณre nie sฤ
zgodne z niniejszym *Kodeksem postฤpowania*, lub do tymczasowego lub staลego zablokowania wszelkich wspรณลtwรณrcรณw za inne zachowania, ktรณre uwaลผajฤ
za niewลaลciwe, groลบne, obraลบliwe lub szkodliwe.
Przyjmujฤ
c niniejszy *Kodeks postฤpowania*, opiekunowie projektu zobowiฤ
zujฤ
siฤ do uczciwego i konsekwentnego stosowania tych zasad w kaลผdym aspekcie zarzฤ
dzania tym projektem. Opiekunowie projektรณw, ktรณrzy nie przestrzegajฤ
lub nie egzekwujฤ
*Kodeksu postฤpowania*, mogฤ
zostaฤ na staลe usuniฤci z zespoลu projektowego.
Ten *Kodeks postฤpowania* ma zastosowanie zarรณwno w przestrzeniach projektowych, jak i w przestrzeniach publicznych, gdy dana osoba reprezentuje projekt lub jego spoลecznoลฤ.
Przypadki obraลบliwego, nฤkajฤ
cego lub w inny sposรณb niedopuszczalnego zachowania moลผna zgลaszaฤ, kontaktujฤ
c siฤ z opiekunem projektu pod adresem **victorfelder na gmail.com**. Wszystkie skargi zostanฤ
rozpatrzone i zbadane, a ich wynikiem bฤdzie odpowiedลบ uznana za niezbฤdnฤ
i odpowiedniฤ
do okolicznoลci. Opiekunowie sฤ
zobowiฤ
zani do zachowania poufnoลci w stosunku do zgลaszajฤ
cego incydent.
Niniejszy *Kodeks postฤpowania* zostaล zaadaptowany z [Contributor Covenant][homepage],
wersja 1.3.0, dostฤpna pod adresem https://contributor-covenant.org/version/1/3/0/
[homepage]: https://contributor-covenant.org
[Translations](README.md#translations)
| free-programming-books/docs/CODE_OF_CONDUCT-pl.md/0 | {
"file_path": "free-programming-books/docs/CODE_OF_CONDUCT-pl.md",
"repo_id": "free-programming-books",
"token_count": 1324
} | 72 |
*[Lea esto en otros idiomas][translations-list-link]*
<!----><a id="contributor-license-agreement"></a>
## Acuerdo de Licencia
Al contribuir, acepta la [LICENCIA][license] de este repositorio.
<!----><a id="contributor-code-of-conduct"></a>
## Cรณdigo de Conducta como Colaborador
Al contribuir, acepta respetar el [Cรณdigo de Conducta][coc] ([traducciones / otros idiomas][translations-list-link]) presente en el repositorio.
<!----><a id="in-a-nutshell"></a>
## Breve resumen
1. "Un enlace para descargar fรกcilmente un libro" no siempre es un enlace a un libro *gratuito*. Por favor, contribuya solo con contenido gratuito. Asegรบrese de que se ofrezca gratis. No se aceptan enlaces a pรกginas que *requieran* de direcciones de correo electrรณnico para la obtenciรณn de libros, pero sรญ damos la bienvenida a aquellos listados que asรญ se soliciten.
2. No es necesario conocer Git: si encontrรณ algo de interรฉs que *no estรฉ ya en este repositorio*, tenga el gusto de abrir una [Issue][issues] con su propuesta de enlaces.
- Si ya maneja Git, haga un Fork del repositorio y envรญe su contribuciรณn mediante Pull Request (PR).
3. Dispone de 6 categorรญas. Seleccione aquel listado que crea conveniente segรบn:
- *Libros* : PDF, HTML, ePub, un recurso alojado en gitbook.io, un repositorio Git, etc.
- *Cursos* : Un curso es aquel material de aprendizaje que no es un libro. [Esto es un curso](http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/).
- *Tutoriales interactivos* : Un sitio web se considera interactivo si permite al usuario escribir cรณdigo o comandos y evaluar su resultado ("evaluar" no significa "obtener una calificaciรณn"). Por ejemplo: [Pruebe Haskell](http://tryhaskell.org), [Pruebe GitHub](http://try.github.io).
- *Playgrounds* : se tratan de sitios en lรญnea interactivos, juegos o software de escritorio cuyo fin es el de aprender programaciรณn. Permiten escribir, compiar (o ejecutar), y compartir partes de cรณdigo fuente. A menudo, ofrecen la posibilidad de hacer bifurcaciones y ensuciarse las manos jugando con el cรณdigo generado hasta dicho instante.
- *Podcasts y Screencasts* : Son aquellas retransmisiones grabadas ya sea en audio y/o en vรญdeo, respectivamente.
- *Conjuntos de problemas & Programaciรณn competitiva* : Se trata de un sitio web o software que le permita evaluar sus habilidades de programaciรณn resolviendo problemas simples o complejos, con o sin revisiรณn de cรณdigo, con o sin comparar los resultados con otros usuarios.
4. Asegรบrese de seguir la [guรญa de pautas que mostramos a continuaciรณn][guidelines] asรญ como de respetar el [formato Markdown][formatting] de los ficheros.
5. GitHub Actions ejecutarรก pruebas para asegurarse de que **las listas esten ordenadas alfabรฉticamente** y de que se **siga dicha normalizaciรณn de formateo**. **Asegรบrese** de verificar que sus cambios pasen todas estas comprobaciones de calidad.
<!----><a id="guidelines"></a>
### Pautas
- Revise si el libro es gratuito. Hรกgalo las veces que sean necesarias. Ayude a los administradores comentando en las PR por quรฉ cree que el libro se ofrece gratis o es valioso.
- No se aceptan ficheros alojados en Google Drive, Dropbox, Mega, Scribd, Issuu u otras plataformas de almacenamiento y/o descarga similares.
- Inserte los enlaces ordenados alfabรฉticamente, tal y como se describe [mรกs abajo](#alphabetical-order).
- Use el enlace que apunte a la fuente mรกs fidedigna. Esto es, el sitio web del autor es mejor que el del editor y รฉste a su vez mejor que uno de terceros.
- No use servicios de almacenamiento en la nube. Esto incluye, aunque sin limitar, enlaces a Dropbox y Google Drive.
- Es siempre preferible el uso de enlaces con protocolo `https` en vez de `http` si ambos se refieren al mismo dominio y sirven el mismo contenido.
- En los dominios raรญz, elimine la barra inclinada del final: `http://example.com` en lugar de `http://example.com/`.
- Utilice preferentemente la forma corta de los hipervรญnculos: `http://example.com/dir/` es mejor que `http://example.com/dir/index.html`.
- No se admiten acortadores de enlaces URL.
- Por lo general, se prefiere el enlace "actual" sobre el de "versiรณn": `http://example.com/dir/book/current/` es mรกs asequible que `http://example.com/dir/book/v1.0.0/index.html`.
- Si en un enlace se encuentra con algรบn problema de certificados, ya sea caducado, autofirmado o de cualquier otro tipo:
1. *Reemplรกcelo* con su anรกlogo `http` si fuera posible (porque aceptar excepciones puede ser complicado en dispositivos mรณviles).
2. *Mantรฉngalo* si no existe versiรณn `http` pero el enlace aรบn es accesible a travรฉs de `https` agregando una excepciรณn al navegador o ignorando la advertencia.
3. *Elimรญnelo* en cualquier otro caso.
- Si existe un mismo enlace con varios formatos, anexe enlaces aparte con una nota sobre cada formato.
- Si un recurso existe en diferentes lugares de Internet:
- Use aquella fuente mรกs fidedigna (lo que significa que el sitio web del propio autor es mรกs asequible que el sitio web del editor y a su vez รฉste es mejor que una fuente de terceros).
- Si apuntan a diferentes ediciones y considera que estas ediciones son lo suficientemente dispares como para que valga la pena conservarlas, agregue por separado un nuevo enlace haciendo alusiรณn a cada ediciรณn. Dirรญjase al [Issue #2353](https://github.com/EbookFoundation/free-programming-books/issues/2353) si desea contribuir en la discusiรณn acerca del formateo que deben seguir dichos registros.
- Es preferible realizar commits atรณmicos (un commit por cada adiciรณn/eliminaciรณn/modificaciรณn) frente a unos con mayor calado. No es necesario realizar un squash de todos ellos antes de enviar una PR. (Nunca aplicaremos esta regla, ya que solamente es una cuestiรณn de conveniencia para quien mantiene el proyecto).
- Si se trata de un libro mรกs antiguo, incluya su fecha de publicaciรณn dentro del tรญtulo.
- Incluya el nombre o nombres de autor/es cuando corresponda. Puede valerse de "`et al.`" para acortar esa enumeraciรณn de autores.
- Si el libro no estรก terminado y aรบn se estรก trabajando en รฉl, agregue la anotaciรณn de "`in process`", tal y como se describe [a continuaciรณn][in_process].
- En el caso de que decida recuperar un recurso usando servicios como [*Internet Archive's Wayback Machine*](https://web.archive.org), anexe la anotaciรณn "`archived`" (en consonancia con el idioma) tal y como se describe [a continuaciรณn][archived]. Use como mejor versiรณn aquella que sea la mรกs reciente y completa.
- Si se solicita una direcciรณn de correo electrรณnico o configuraciรณn de cuenta antes de habilitar la descarga, agregue entre parรฉntesis dichas notas y en consonancia con el idioma. Por ejemplo: `(*se solicita* email, no requerido...)`.
<!----><a id="formatting"></a>
### Formato normalizado
- Como podrรก observar, los listados tienen `.md` como extensiรณn de fichero. Intente aprender la sintaxis [Markdown][markdown_guide]. ยกEs bastante simple!
- Dichos listados comienzan con una Tabla de Contenidos (TOC). Este รญndice permite enumerar y vincular todas las secciones y subsecciones en las que se clasifica cada recurso. Mantรฉngalo tambiรฉn en orden alfabรฉtico.
- Las secciones utilizan encabezados de nivel 3 (`###`) y las subsecciones de nivel 4 (`####`).
La idea es tener:
- `2` lรญneas vacรญas entre el รบltimo enlace de una secciรณn y el tรญtulo de la siguiente secciรณn.
- `1` lรญnea vacรญa entre la cabecera y el primer enlace de una determinada secciรณn.
- `0` lรญneas en blanco entre los distintos enlaces.
- `1` lรญnea en blanco al final de cada fichero `.md`.
Ejemplo:
```text
[...]
* [Un libro increรญble](http://example.com/example.html)
(lรญnea en blanco)
(lรญnea en blanco)
### Secciรณn de ejemplo
(lรญnea en blanco)
* [Otro libro fascinante](http://example.com/book.html)
* [Otro libro mรกs](http://example.com/other.html)
```
- Omita los espacios entre `]` y `(`:
```text
INCORRECTO: * [Otro libro fascinante] (http://example.com/book.html)
CORRECTO : * [Otro libro fascinante](http://example.com/book.html)
```
- Si en el registro decide incluir al autor, emplee ` - ` (un guiรณn rodeado de espacios simples) como separador:
```text
INCORRECTO: * [Un libro sencillamente fabuloso](http://example.com/book.html)- John Doe
CORRECTO : * [Un libro sencillamente fabuloso](http://example.com/book.html) - John Doe
```
- Ponga un solo espacio entre el enlace al contenido y su formato:
```text
INCORRECTO: * [Un libro muy interesante](https://example.org/book.pdf)(PDF)
CORRECTO : * [Un libro muy interesante](https://example.org/book.pdf) (PDF)
```
- El autor se antepone al formato:
```text
INCORRECTO: * [Un libro muy interesante](https://example.org/book.pdf)- (PDF) Jane Roe
CORRECTO : * [Un libro muy interesante](https://example.org/book.pdf) - Jane Roe (PDF)
```
- Mรบltiples formatos:
```text
INCORRECTO: * [Otro libro interesante](http://example.com/) - John Doe (HTML)
INCORRECTO: * [Otro libro interesante](https://downloads.example.org/book.html) - John Doe (sitio de descarga)
CORRECTO : * [Otro libro interesante](http://example.com/) - John Doe (HTML) [(PDF, EPUB)](https://downloads.example.org/book.html)
```
Preferimos un solo enlace por cada recurso. Tener varios enlaces cobra sentido cuando este รบnico enlace no engloba un fรกcil acceso a los diferentes formatos existentes.
Tenga en cuenta tambiรฉn que, cada enlace que agregamos crea una carga de mantenimiento, por lo que, en general, trataremos de evitarlos.
- Incluya el aรฑo de publicaciรณn como parte del tรญtulo de los libros mรกs antiguos:
```text
INCORRECTO: * [Un libro bastante especial](https://example.org/book.html) - Jane Roe - 1970
CORRECTO : * [Un libro bastante especial (1970)](https://example.org/book.html) - Jane Roe
```
- <a id="in_process"></a>Libros en proceso / no acabados aรบn:
```text
CORRECTO : * [A punto de ser un libro fascinante](http://example.com/book2.html) - John Doe (HTML) *(:construction: en proceso)*
```
- <a id="archived"></a>Enlaces archivados:
```text
CORRECTO : * [Un recurso recuperado a partir de su lรญnea de tiempo](https://web.archive.org/web/20211016123456/http://example.com/) - John Doe (HTML) *(:card_file_box: archivado)*
```
<!----><a id="alphabetical-order"></a>
### Ordenaciรณn alfabรฉtica
- Cuando hay varios tรญtulos comenzando por la misma letra, ordene por la segunda, ... y asรญ consecutivamente. Por ejemplo:
- `aa` va antes de `ab`.
- `one two` va antes que `onetwo`.
En cualquier caso o si por casualidad encontrase un enlace fuera de lugar, compruebe el mensaje de error que facilita nuestro linter. Le permitirรก saber las lรญneas de cรณdigo que debe intercambiar.
<!----><a id="notes"></a>
### Anotaciones
Si bien los conceptos bรกsicos son relativamente simples, existe una gran diversidad entre los recursos que enumeramos. Aquรญ hay algunas notas sobre cรณmo nos ocupamos de esta diversidad.
<!----><a id="metadata"></a>
#### Metadatos
Nuestros listados proporcionan un conjunto mรญnimo de metadatos: tรญtulos, URL, autores, formato, plataformas y notas de acceso.
<!----><a id="titles"></a>
##### Tรญtulos
- Sin tรญtulos inventados: Intentamos tomar el texto de los propios recursos; se advierte a los colaboradores que, si puede evitarse, no inventen tรญtulos ni los utilicen editorialmente. Una excepciรณn es para obras mรกs antiguas: si son principalmente de interรฉs histรณrico, un aรฑo entre parรฉntesis adjunto al tรญtulo ayuda a los usuarios a saber si estos son de interรฉs.
- Sin tรญtulos TODO EN MAYรSCULAS: Por lo general, es apropiado tener cada primera letra de palabra en mayรบsculas, pero en caso de duda, use siempre el estilo tal y como viene en la fuente original.
- Evite usar emoticonos.
<!----><a id="urls"></a>
##### Direcciones URL
- No se permiten acortadores de URLs para los enlaces.
- Los parรกmetros de consulta o cรณdigos referentes al seguimiento o campaรฑas de marketing deben eliminarse de la URL.
- Las URL internacionales deben escaparse. Las barras del navegador suelen representar los caracteres en Unicode, pero utilice copiar y pegar, por favor; es la forma mรกs rรกpida de construir un hipervรญnculo vรกlido.
- Las URL seguras (`https`) siempre son mejor opciรณn frente a las no seguras (`http`) donde se ha implementado el protocolo de comunicaciรณn encriptado HTTPS.
- No nos gustan las URL que apuntan a pรกginas web que no alojen el recurso mencionado, enlazando por el contrario a otra parte.
<!----><a id="creators"></a>
##### Atribuciones
- Queremos dar crรฉdito a los creadores de recursos gratuitos cuando sea apropiado, ยกincluso traductores!
- En el caso de obras traducidas, se debe acreditar tambiรฉn al autor original. Recomendamos usar [MARC relators](https://loc.gov/marc/relators/relaterm.html) para dar presencia al resto de creadores diferentes al autor original, tal y como se muestra en este ejemplo:
```markdown
* [Un libro traducido](http://example.com/book-es.html) - John Doe, `trl.:` Mike Traduce
```
donde, la anotaciรณn `trl.:` incluye el cรณdigo MARC relator para "traductor".
- Utilice comas `,` para separar cada elemento de la lista de autores.
- Cuando sean muchas, puedes valerte de "`et al.`" para acortar dicha lista.
- No permitimos enlaces directos al creador.
- En el caso de recopilaciones u obras remezcladas, el "creador" puede necesitar una descripciรณn. Por ejemplo, los libros de "GoalKicker" o "RIP Tutorial" se acreditan como "`Creado a partir de la documentaciรณn de StackOverflow`" (en inglรฉs: "`Compiled from StackOverflow documentation`").
- No incluiremos tรญtulos honorรญficos tales como "`Prof.`" o "`Dr.`".
<!----><a id="time-limited-courses-and-trials"></a>
##### Cursos y pruebas de tiempo limitado
- No enumeramos cosas que tengamos que eliminar en seis meses.
- Si un curso tiene un perรญodo de inscripciรณn o una duraciรณn limitada, no lo incluiremos en las listas.
- No podemos enumerar aquellos recursos que son gratuitos durante un perรญodo limitado.
<!----><a id="platforms-and-access-notes"></a>
##### Plataformas y Notas de Acceso
- Cursos. Especialmente para nuestras listas de cursos, la plataforma es una parte importante de la descripciรณn del recurso. Esto se debe a que las plataformas de cursos tienen diferentes prestaciones y modelos de acceso. Si bien generalmente no incluimos un libro que requiere de registro previo, muchas plataformas de cursos tienen la casualidad de no funcionar sin algรบn tipo de cuenta. Un ejemplo de plataformas de cursos podrรญan ser: Coursera, EdX, Udacity y Udemy. Cuando un curso depende de una plataforma, el nombre de dicha plataforma debe aparecer entre parรฉntesis.
- YouTube. Tenemos muchos cursos que consisten en listas de reproducciรณn de YouTube. No incluimos YouTube como plataforma, sino que tratamos de incluir al creador de YouTube, el cuรกl es a menudo una sub-plataforma en sรญ.
- Vรญdeos de YouTube. Por lo general, no vinculamos a vรญdeos individuales de YouTube a menos que tengan mรกs de una hora de duraciรณn y estรฉn estructurados como un curso o un tutorial. Si este es el caso, asegรบrese de anotarlo en la descripciรณn de la PR.
- ยกEvite tambiรฉn enlaces acortados (es decir, `youtu.be/xxxx`)!
- Leanpub. Leanpub aloja libros con una amplia variedad de modelos de acceso. A veces, un libro se puede leer sin registrarse; en otras, un libro requiere una cuenta Leanpub para tener acceso gratuito. Dada la calidad de los libros y la mezcla y fluidez de los modelos de acceso Leanpub, damos validez a estos รบltimos anexando la nota de acceso: `*(cuenta Leanpub o email vรกlido requerido)*`.
<!----><a id="genres"></a>
#### Gรฉneros
La primera regla para decidir en quรฉ listado encaja un determinado recurso es ver cรณmo se describe a sรญ mismo. Si por ejemplo se retrata a sรญ mismo como un libro, entonces tal vez es que lo sea.
<!----><a id="genres-we-dont-list"></a>
##### Gรฉneros no aceptados
Ya que en Internet podemos encontrar una variedad infinita de recursos, no incluimos en nuestro registro:
- blogs
- publicaciones de blogs
- artรญculos
- Sitios web (excepto aquellos que alberguen MUCHOS elementos que podamos incluir en los listados).
- vรญdeos que no sean cursos o screencasts (retrasmisiones)
- capรญtulos sueltos a libros
- muestras o introducciones de libros
- Canales/grupos de IRC, Telegram...
- Canales/salas de Slack... o listas de correo
El [listado donde incluimos sitios o software de programaciรณn competitiva][programming_playgrounds_list] no es tan restrictivo. El alcance de este repositorio es determinado por la comunidad; si desea sugerir un cambio o extender el alcance, utilice los [issues][issues] para registrar dicha sugerencia.
<!----><a id="books-vs-other-stuff"></a>
##### Libros vs. Otro Material
No somos tan quisquillosos con lo que consideramos como libro. A continuaciรณn, se muestran algunas propiedades que un recurso pueda encajar como libro:
- tiene un ISBN (International Standard Book Number)
- tiene una Tabla de Contenidos (TOC)
- se ofrece una versiรณn para su descarga electrรณnica, especialmente ePub.
- tiene diversas ediciones
- no depende de un contenido interactivo extra o vรญdeos
- trata de abordar un tema de manera integral
- es autosuficiente
Hay muchos libros que enumeramos los cuรกles no poseen estos atributos; esto puede depender del contexto.
<!----><a id="books-vs-courses"></a>
##### Libros vs. Cursos
ยกA veces distinguir puede ser dificultoso!
Los cursos suelen tener libros de texto asociados, que incluirรญamos en nuestras listas de libros. Ademรกs, los cursos tienen conferencias, ejercicios, pruebas, apuntes u otras ayudas didรกcticas. Una sola conferencia o vรญdeo por sรญ solo no es un curso. Un presentaciรณn de PowerPoint tampoco puede ser catalogado como curso.
<!----><a id="interactive-tutorials-vs-other-stuff"></a>
##### Tutoriales interactivos vs. Otro Material
Si es posible imprimirlo y conservar su esencia, no es un Tutorial Interactivo.
<!----><a id="automation"></a>
### Automatizaciรณn
- El cumplimiento de las reglas de formateado se automatiza vรญa [GitHub Actions](https://docs.github.com/en/actions) usando [fpb-lint](https://github.com/vhf/free-programming-books-lint) (ver [`.github/workflows/fpb-lint.yml`](../.github/workflows/fpb-lint.yml))
- La validaciรณn de URLs se realiza mediante [awesome_bot](https://github.com/dkhamsing/awesome_bot)
- Para activar esta validaciรณn de URL, envรญe un commit que incluya como mensaje de confirmaciรณn `check_urls=fichero_a_comprobar`:
```properties
check_urls=free-programming-books.md free-programming-books-es.md
```
- Es posible especificar mรกs de un fichero a comprobar. Simplemente use un espacio para separar cada entrada.
- Si especifica mรกs de un archivo, los resultados obtenidos se basan en el estado del รบltimo archivo verificado. Debe tenerlo en cuenta ya que, debido a esto, puede obtener falsos positivos al finalizar el proceso. Asรญ que tras el envรญo de la Pull Request asegรบrese de inspeccionar el registro de compilaciรณn haciendo clic en "Show all checks" -> "Details".
[license]: ../LICENSE
[coc]: CODE_OF_CONDUCT-es.md
[translations-list-link]: README.md#translations
[issues]: https://github.com/EbookFoundation/free-programming-books/issues
[formatting]: #formato-normalizado
[guidelines]: #pautas
[in_process]: #in_process
[archived]: #archived
[markdown_guide]: https://guides.github.com/features/mastering-markdown/
[programming_playgrounds_list]: https://github.com/EbookFoundation/free-programming-books/blob/main/more/free-programming-playgrounds.md
| free-programming-books/docs/CONTRIBUTING-es.md/0 | {
"file_path": "free-programming-books/docs/CONTRIBUTING-es.md",
"repo_id": "free-programming-books",
"token_count": 7371
} | 73 |
*[้ฑ่ฎๅ
ถไป่ช่จ็ๆฌ็ๆไปถ](README.md#nslations)*
## ่ฒข็ป่
่จฑๅฏๅ่ญฐ
่ซ้ตๅพชๆญค [่จฑๅฏๅ่ญฐ](../LICENSE) ๅ่่ฒข็ปใ
## ่ฒข็ป่
่ก็บๆบๅ
่ซๅๆไธฆ้ตๅพชๆญค [่ก็บๆบๅ](CODE_OF_CONDUCT.md) ๅ่่ฒข็ปใ([translations](README.md#nslations))
## ๆฆ่ฆ
1. "ไธๅๅฏไปฅ่ผๆไธ่ผไธๆฌๆธ็้ฃ็ต" ไธฆไธไปฃ่กจๅฎๅฐๅ็ๅฐฑๆฏ *ๅ
่ฒป* ๆธ็ฑใ ่ซๅชๆไพๅ
่ฒปๅ
งๅฎนใ ็ขบไฟกไฝ ๆๆไพ็ๆธ็ฑๆฏๅ
่ฒป็ใๆๅไธๆฅๅๅฐๅ *้่ฆ* ๅทฅไฝ้ปๅญ้ตไปถๅฐๅๆ่ฝ็ฒๅๆธ็ฑ้ ้ข็้ฃ็ต๏ผไฝๆๅๆญก่ฟๆ้ๆฑ้ไบ้ฃ็ต็ๅ่กจใ
2. ไฝ ไธ้่ฆๆ Git๏ผๅฆๆไฝ ็ผ็พไบไธไบๆ่ถฃ็ๆฑ่ฅฟ *ๅฐๆชๅบ็พๅจๆญค repo* ไธญ๏ผ่ซ้ไธๅ [Issue](https://github.com/EbookFoundation/free-programming-books/issues) ้ฒ่กไธป้ก่จ่ซใ
* ๅฆๆไฝ ๅทฒ็ถ็ฅ้ Git๏ผ่ซ Fork ๆญค repo ไธฆๆไบค Pull Request (PR)ใ
3. ้่ฃกๆๅ
ญ็จฎๅ่กจ๏ผ่ซ้ธๆๆญฃ็ขบ็ไธ้
๏ผ
* *Books* ๏ผPDFใHTMLใePubใๅบๆผ gitbook.io ็็ถฒ็ซใGit ็ repo ็ญใ
* *Courses* ๏ผ่ชฒ็จๆฏไธ็จฎๅญธ็ฟ็ด ๆ๏ผ่ไธๆฏไธๆฌๆธ [This is a course](http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/)ใ
* *Interactive Tutorials* ๏ผไธๅไบๅๅผ็ถฒ็ซ๏ผๅ
่จฑ็จๆถ่ผธๅ
ฅ็จๅผ็ขผๆๆไปคไธฆๅท่ก็ตๆใไพๅฆ๏ผ[Try Haskell](http://tryhaskell.org)๏ผ[Try GitHub](http://try.github.io)ใ
* *Playgrounds* : Playgrounds ๆฏๅญธ็ฟ็จๅผ่จญ่จ็็ทไธไบๅๅผ็ถฒ็ซใ้ๆฒๆๆก้ข่ป้ซใไฝ ๅฏไปฅๅจไธ้ข็ทจๅฏซใ็ทจ่ญฏใ้่กๆๅไบซ็จๅผ็ขผ็ๆฎตใ Playgrounds ้ๅธธๅ
่จฑไฝ fork ็จๅผ็ขผ็ถๅพๅจๅ
ถไธญ็กๆ
็็ทจๅฏซ็จๅผ็ขผใ
* *Podcasts and Screencasts* ๏ผPodcast ๅๅฝฑ้ณใ
* *Problem Sets & Competitive Programming* ๏ผไธๅ็ถฒ็ซๆ่ป้ซ๏ผ่ฎไฝ ้้่งฃๆฑบ็ฐกๅฎๆ่ค้็ๅ้กไพ่ฉไผฐไฝ ็็จๅผๆ่ฝ๏ผๅฏ่ฝๆ็จๅผ็ขผๆชขๆฅ๏ผๆ่ๅ
ถไป็จๆถๆฏๅฐ็ปๆใ
4. ็ขบไฟ้ตๅพชไธๆน็ [ๅบๆฌๆบๅ](#ๅบๆฌๆบๅ)๏ผไธฆ้ตๅพชๆญค repo ๆไปถ็ [Markdown ่ฆๅฎๆ ผๅผ](#่ฆๅฎๆ ผๅผ)ใ
5. GitHub Actions ๅฐ้่กๆธฌ่ฉฆ๏ผไปฅ็ขบไฟไฝ ็ๅ่กจๆฏ **ๆๅญๆฏ้กบๅบๆๅ** ็๏ผไธฆ **้ตๅพชๆ ผๅผๅ่ฆๅ**ใ่ซ **็ขบไฟ** ไฝ ็ๆดๆน้้่ฉฒๆธฌ่ฉฆใ
### ๅบๆฌๆบๅ
* ็ขบไฟไฝ ๆไบค็ๆฏไธๆฌๆธ้ฝๆฏๅ
่ฒป็ใๅฆๆ้่ฆ่ซ Double-checkใๅฆๆไฝ ๅจ PR ไธญ่จปๆ็บไป้บผไฝ ่ช็บ้ๆฌๆธๆฏๅ
่ฒป็๏ผ้ๅฐ็ฎก็ๅกๆฏๅพๆๅนซๅฉ็ใ
* ๆๅไธๆฅๅๅฒๅญๅจ Google DriveใDropboxใMegaใScribdใIssuu ๅๅ
ถไป้กไผผๆไปถไธๅณๅนณๅฐไธ็ๆไปถใ
* ่ซๆ็
งๅญๆฏ้ ๅบๆๅ
ฅ้ฃ็ต, ๅฆ [ไธๆนๆ่ฟฐ](#alphabetical-order).
* ไฝฟ็จๆๆฌๅจไพๆบ็้ฃ็ต(ๆๆๆฏๅไฝ่
็็ถฒ็ซๆฏ็ทจ่ผฏ็็ถฒ็ซๅฅฝ๏ผๆฏ็ฌฌไธๆน็ถฒ็ซๅฅฝ)ใ
* ๆฒๆๆไปถ่จ็ฎกๆๅ(ๅ
ๆฌ(ไฝไธ้ๆผ) Dropbox ๅ Google Drive ้ฃ็ต)ใ
* ๅชๅ
้ธๆไฝฟ็จ `https` ้ฃ็ต๏ผ่ไธๆฏ `http` ้ฃ็ต -- ๅช่ฆๅฎๅไฝๆผ็ธๅ็็ถฒๅไธฆๆไพ็ธๅ็ๅ
ๅฎนใ
* ๅจ็ถฒๅๆ น็ฎ้ไธ๏ผๅปๆๅฐพๆซ็ๆๆง๏ผไฝฟ็จ `http://example.com` ไปฃๆฟ `http://example.com/`ใ
* ๅชๅ
้ธๆๆ็ญ็้ฃ็ต๏ผไฝฟ็จ `http://example.com/dir/` ๆฏไฝฟ็จ `http://example.com/dir/index.html` ๆดๅฅฝใ
* ไธ่ฆๆไพ็ญ้ฃ็ต
* ๅชๅ
้ธๆไฝฟ็จ "current" ้ฃ็ตไปฃๆฟๆ "version" ้ฃ็ต๏ผไฝฟ็จ `http://example.com/dir/book/current/` ๆฏไฝฟ็จ `http://example.com/dir/book/v1.0.0/index.html` ๆดๅฅฝใ
* ๅฆๆไธๅ้ฃ็ตๅญๅจ้ๆ็่ญๆธ/่ช็ฐฝๅ่ญๆธ/SSLๅ้ก็ไปปไฝๅ
ถไป้กๅ๏ผ
1. *replace it* ๏ผๅฆๆๅฏ่ฝ็่ฉฑ๏ผๅฐๅ
ถ *ๆฟๆ* ็บๅฐๆ็ `http` (ๅ ็บๅจ็งปๅ่จญๅไธๆฅๅ็ฐๅธธๅฏ่ฝๆฏ่ผ่ค้)ใ
2. *leave it* ๏ผๅฆๆๆฒๆ`http`็ๆฌ๏ผไฝไป็ถๅฏไปฅ้้`https`้ ่จช้ฃ็ต๏ผๅๅจ็่ฆฝๅจไธญๆทปๅ ็ฐๅธธๆๅฟฝ็ฅ่ญฆๅใ
3. *remove it* ๏ผไธ่ฟฐ็ๆณไปฅๅคๅๅช้คๆๅฎใ
* ๅฆๆไธๅ้ฃ็ตไปฅๅค็จฎๆ ผๅผๅญๅจ๏ผ่ซๆทปๅ ไธๅๅฎ็จ็้ฃ็ต๏ผไธฆ่จปๆๆฏ็จฎๆ ผๅผใ
* ๅฆๆไธๅ่ณๆบๅญๅจๆผInternetไธ็ไธๅไฝ็ฝฎ
* ไฝฟ็จๆๆฌๅจไพๆบ็้ฃ็ต(ๆๆๆฏๅๅงไฝ่
็็ถฒ็ซๆฏ็ทจ่ผฏ็็ถฒ็ซๅฅฝ๏ผๆฏ็ฌฌไธๆน็ถฒ็ซๅฅฝ)ใ
* ๅฆๆๅฎๅ้ฃ็ตๅฐไธๅ็็ๆฌ๏ผไฝ ่ช็บ้ไบ็ๆฌๅทฎ็ฐๅพๅคง๏ผๅผๅพไฟ็๏ผ้ฃ้บผๆทปๅ ไธๅๅฎ็จ็้ฃ็ต๏ผไธฆๅฐๆฏๅ็ๆฌๅ่ชชๆ(ๅ่ [Issue #2353](https://github.com/EbookFoundation/free-programming-books/issues/2353) ๆๅฉๆผๆ ผๅผๅๅ้ก็่จ่ซ)ใ
* ็ธ่ผไธๅๆฏ่ผๅคง็ๆไบค๏ผๆๅๆดๅพๅๆผๅๅญๆไบค(้้ๆทปๅ /ๅ ้ค/ไฟฎๆน้ฒ่กไธๆฌกๆไบค)ใๅจๆไบคPRไนๅๆฒกๆๅฟ
่ฆๅฃ็ธฎไฝ ็ๆไบคใ(็บไบ็ถญ่ญทไบบๅก็ๆนไพฟ๏ผๆๅๆฐธ้ ไธๆๅท่ก้ๅ่ฆๅ)ใ
* ๅฆๆไธๆฌๆธๆฏ่ผ่๏ผ่ซๅจๆธๅไธญ่จปๆๅบ็ๆฅๆใ
* ๅ
ๅซไฝ่
็ๅๅญๆ้ฉ็ถ็ๅๅญใไธญๆ็ๆฌๅฏไปฅ็จ โ`็ญ`โ (โ`et al.`โ) ็ธฎ็ญไฝ่
ๅ่กจใ
* ๅฆๆไธๆฌๆธ้ๆฒกๆๅฎๆ๏ผไธฆไธไปๅจ็ทจๅฏซไธญ๏ผๅ้ๆทปๅ โ`in process`โ ็ฌฆ่๏ผๅ่ [ไธๆ](#in_process) ๆ่ฟฐใ
- if a resource is restored using the [*Internet Archive's Wayback Machine*](https://web.archive.org) (or similar), add the "`archived`" notation, as described [below](#archived). The best versions to use are recent and complete.
* ๅฆๆๅจ้ๅงไธ่ผไนๅ้่ฆ้ปๅญ้ตไปถๅฐๅๆๅธณๆท่จญ็ฝฎ๏ผ่ซๅจๆฌ่ไธญๆทปๅ ๅ้ฉ็่ช่จๆ่ฟฐ๏ผไพๅฆ๏ผ`(*้่ฆ* ้ปๅญ้ตไปถ๏ผไฝไธๆฏๅฟ
้็)`ใ
### ่ฆๅฎๆ ผๅผ
* ๆๆๅ่กจ้ฝๆฏ `.md` ๆไปถใ่ฉฆ็ๅญธ็ฟ [Markdown](https://guides.github.com/features/mastering-markdown/) ่ชๆณใๅฎๅพๅฎนๆไธๆ๏ผ
* ๆๆ็ๅ่กจ้ฝไปฅ็ดขๅผ้ๅงใๅฎ็ไฝ็จๆฏๅๅบไธฆ้ฃ็ตๆๆ็ sections (็ซ ็ฏ/ๆฎต่ฝ)ๆ subsections (ๅญๆฎต่ฝ/ๅญ็ซ ็ฏ)ใๅๅฟ
้ตๅพชๅญๆฏ้ ๅบๆๅใ
* Sections (็ซ ็ฏ/ๆฎต่ฝ)ไฝฟ็จ3็ดๆจ้ก(`###`)๏ผsubsections (ๅญๆฎต่ฝ/ๅญ็ซ ็ฏ)ไฝฟ็จ4็ดๆจ้ก (`####`)ใ
ๆด้ซๆ็ถญ็บ๏ผ
* `2` ๏ผๆฐๆทปๅ ็ Section ่ๆซๅฐพ้ฃ็ต้ๅฟ
้็ๆ `2` ๅ็ฉบ่ก
* `1` ๏ผๆจ้กๅ็ฌฌไธๅ้ฃ็ตไน้ๅฟ
้็ๆ `1` ๅ็ฉบ่ก็็ฉบ่ก
* `0` ๏ผไปปไฝๅ
ฉๅ้ฃ็ตไน้ไธ่ฝ็ๆไปปไฝ็ฉบ่ก
* `1` ๏ผๆฏๅ `.md` ๆไปถๆซๅฐพๅฟ
้็ๆ `1` ๅ็ฉบ่ก
่ไพ๏ผ
```text
[...]
* [ไธๆฌๅพๆ็จ็ๆธ](http://example.com/example.html)
(็ฉบ่ก)
(็ฉบ่ก)
### ้ปๅญๆธ็จฎ้กๆจ้ก
(็ฉบ่ก)
* [Another ๅพๆ็จ็ๆธ](http://example.com/book.html)
* [Other ๆ็จ็ๆธ](http://example.com/other.html)
```
* ๅจ `]` ๅ `(` ไน้ไธ่ฆ็ๆ็ฉบๆ ผ๏ผ
```text
้ฏ่ชค๏ผ* [ไธๆฌๅพๆ็จ็ๆธ] (http://example.com/book.html)
ๆญฃ็ขบ๏ผ* [ไธๆฌๅพๆ็จ็ๆธ](http://example.com/book.html)
```
* ๅฆๆๅ
ๆฌไฝ่
๏ผ่ซไฝฟ็จ' - '(็ฑๅฎๅ็ฉบๆ ผ(่ฑๆๅๅ)ๅ
ๅ็็ ดๆ่)๏ผ
```text
้ฏ่ชค๏ผ* [ไธๆฌๅพๆ็จ็ๆธ](http://example.com/book.html)- ๅผต้กฏๅฎ
ๆญฃ็ขบ๏ผ* [ไธๆฌๅพๆ็จ็ๆธ](http://example.com/book.html) - ๅผต้กฏๅฎ
```
* ๅจ้ฃ็ตๅ้ปๅญๆธๆ ผๅผไน้ๆพไธๅ็ฉบๆ ผ๏ผ
```text
้ฏ่ชค๏ผ* [ไธๆฌๅพๆ็จ็ๆธ](https://example.org/book.pdf)(PDF)
ๆญฃ็ขบ๏ผ* [ไธๆฌๅพๆ็จ็ๆธ](https://example.org/book.pdf) (PDF)
```
* ๅฆ้ๅๆณจๆๆณจ่งฃ๏ผ่ซไฝฟ็จ่ฑๆๅๅๆฌ่`( )`๏ผ
```text
้ฏ่ชค๏ผ* [ไธๆฌๅพๆ็จ็ๆธ](https://example.org/book.pdf) ๏ผ็น้ซไธญๆ๏ผ
ๆญฃ็ขบ๏ผ* [ไธๆฌๅพๆ็จ็ๆธ](https://example.org/book.pdf) (็น้ซไธญๆ)
```
* ไฝ่
ๅจ้ปๅญๆธๆ ผๅผไนๅ๏ผ
```text
้ฏ่ชค๏ผ* [ไธๆฌๅพๆ็จ็ๆธ](https://example.org/book.pdf)- (PDF) ๅผต้กฏๅฎ
ๆญฃ็ขบ๏ผ* [ไธๆฌๅพๆ็จ็ๆธ](https://example.org/book.pdf) - ๅผต้กฏๅฎ (PDF)
```
* ๅค้ๆ ผๅผ๏ผ
```text
้ฏ่ชค๏ผ* [ไธๆฌๅพๆ็จ็ๆธ](http://example.com/)- ๅผต้กฏๅฎ (HTML)
้ฏ่ชค๏ผ* [ไธๆฌๅพๆ็จ็ๆธ](https://downloads.example.org/book.html)- ๅผต้กฏๅฎ (download site)
ๆญฃ็ขบ๏ผ* [ไธๆฌๅพๆ็จ็ๆธ](http://example.com/) - ๅผต้กฏๅฎ (HTML) [(PDF, EPUB)](https://downloads.example.org/book.html)
```
* ๅคไฝ่
๏ผๅค่ญฏ่
ๆ๏ผ่ซไฝฟ็จไธญๆ `ใ` ้ฒ่กๅ้๏ผๅจ่ญฏ่
ๅๅญๅพ่ซไฝฟ็จ่ฑๆๅๅๆฌ่ๅ
ๅ็ `(็ฟป่ญฏ)`๏ผๅฏไปฅ็จ โ็ญโ ็ธฎ็ญไฝ่
ๅ่กจ๏ผ
```text
้ฏ่ชค๏ผ* [ไธๆฌๅพๆ็จ็ๆธ](https://example.org/book.pdf) - ๅผต้กฏๅฎ๏ผๅฒณ็ถบ็พ
ๆญฃ็ขบ๏ผ* [ไธๆฌๅพๆ็จ็ๆธ](https://example.org/book.pdf) - ๅผต้กฏๅฎใๅฒณ็ถบ็พ
(็ฟป่ญฏ)
ๆญฃ็ขบ๏ผ* [ไธๆฌๅพๆ็จ็ๆธ](https://example.org/book.pdf) - ๅผต้กฏๅฎใๅฒณ็ถบ็พ
ใ้กง็ๆญฆใๅบๅกตๅญ ็ญ
```
* ๅจ่ๆธ็ๆจ้กไธญๅ
ๆฌๅบ็ๅนดไปฝ๏ผ
```text
้ฏ่ชค๏ผ* [ไธๆฌๅพๆ็จ็ๆธ](https://example.org/book.html) - ๅผต้กฏๅฎ - 1970
ๆญฃ็ขบ๏ผ* [ไธๆฌๅพๆ็จ็ๆธ (1970)](https://example.org/book.html) - ๅผต้กฏๅฎ
```
* <a id="in_process"></a>็ทจๅฏซ(็ฟป่ญฏ)ไธญ็ๆธ็ฑ๏ผ
```text
ๆญฃ็ขบ๏ผ* [ๅณๅฐๅบ็็ไธๆฌๆธ](http://example.com/book2.html) - ๅผต้กฏๅฎ (HTML) *(:construction: ็ทจๅฏซไธญ)*
ๆญฃ็ขบ๏ผ* [ๅณๅฐๅบ็็ไธๆฌๆธ](http://example.com/book2.html) - ๅผต้กฏๅฎ (HTML) *(:construction: ็ฟป่ญฏไธญ)*
```
- <a id="archived"></a>Archived link:
```text
ๆญฃ็ขบ: * [A Way-backed Interesting Book](https://web.archive.org/web/20211016123456/http://example.com/) - John Doe (HTML) *(:card_file_box: archived)*
```
<!----><a id="alphabetical-order"></a>
### ไพ็
งๅญๆฏๆๅบ
- ็ถๅบ็พๅคๅ็ธๅๅญๆฏ้้ ญ็ๆจ้กๆ๏ผๅ็
ง็ฌฌไบๅๅญๆฏๆๅบ๏ผไปฅๆญค้กๆจใไพๅฆ๏ผ`aa` ๆๅจ `ab` ๅ้ข
- `one two` ๆๅจ `onetwo` ๅ้ข
ๅฆๆไฝ ็ๅฐ้ฏ่ชค็้ฃ็ต๏ผ่ซๆชขๆฅ linter ็้ฏ่ชค่จๆฏไพๆพๅฐๅชไธ่ก้ ๅบ้่ฆไบคๆ
### Notes
While the basics are relatively simple, there is a great diversity in the resources we list. Here are some notes on how we deal with this diversity.
#### Metadata
Our lists provide a minimal set of metadata: titles, URLs, creators, platforms, and access notes.
##### Titles
- No invented titles. We try to take titles from the resources themselves; contributors are admonished not to invent titles or use them editorially if this can be avoided. An exception is for older works; if they are primarily of historical interest, a year in parentheses appended to the title helps users know if they are of interest.
- No ALLCAPS titles. Usually title case is appropriate, but when doubt use the capitalization from the source
- No emojis.
##### URLs
- We don't permit shortened URLs.
- Tracking codes must be removed from the URL.
- International URLs should be escaped. Browser bars typically render these to Unicode, but use copy and paste, please.
- Secure (`https`) URLs are always preferred over non-secure (`http`) urls where HTTPS has been implemented.
- We don't like URLs that point to webpages that don't host the listed resource, but instead point elsewhere.
##### Creators
- We want to credit the creators of free resources where appropriate, including translators!
- For translated works the original author should be credited. We recommend using [MARC relators](https://loc.gov/marc/relators/relaterm.html) to credit creators other than authors, as in this example:
```markdown
* [A Translated Book](http://example.com/book-zh.html) - John Doe, `trl.:` Mike The Translator
```
here, the annotation `trl.:` uses the MARC relator code for "translator".
- Use a comma `,` to delimit each item in the author list.
- You can shorten author lists with "`et al.`".
- We do not permit links for Creators.
- For compilation or remixed works, the "creator" may need a description. For example, "GoalKicker" or "RIP Tutorial" books are credited as "`Compiled from StackOverflow documentation`".
##### Platforms and Access Notes
- Courses. Especially for our course lists, the platform is an important part of the resource description. This is because course platforms have different affordances and access models. While we usually won't list a book that requires a registration, many course platforms have affordances that don't work without some sort of account. Example course platforms include Coursera, EdX, Udacity, and Udemy. When a course depends on a platform, the platform name should be listed in parentheses.
- YouTube. We have many courses which consist of YouTube playlists. We do not list YouTube as a platform, we try to list the YouTube creator, which is often a sub-platform.
- YouTube videos. We usually don't link to individual YouTube videos unless they are more than an hour long and are structured like a course or a tutorial.
- Leanpub. Leanpub hosts books with a variety of access models. Sometimes a book can be read without registration; sometimes a book requires a Leanpub account for free access. Given quality of the books and the mixture and fluidity of Leanpub access models, we permit listing of the latter with the access note `*(Leanpub account or valid email requested)*`.
#### Genres
The first rule in deciding which list a resource belongs in is to see how the resource describes itself. If it calls itself a book, then maybe it's a book.
##### Genres we don't list
Because the Internet is vast, we don't include in our lists:
- blogs
- blog posts
- articles
- websites (except for those that host LOTS of items that we list).
- videos that aren't courses or screencasts.
- book chapters
- teaser samples from books
- IRC or Telegram channels
- Slacks or mailing lists
Our competitive programming lists are not as strict about these exclusions. The scope of the repo is determined by the community; if you want to suggest a change or addition to the scope, please use an issue to make the suggestion.
##### Books vs. Other Stuff
We're not that fussy about book-ness. Here are some attributes that signify that a resource is a book:
- it has an ISBN (International Standard Book Number)
- it has a Table of Contents
- a downloadable version is offered, especially ePub files.
- it has editions
- it doesn't depend on interactive content or videos
- it tries to comprehensively cover a topic
- it's self-contained
There are lots of books that we list that don't have these attributes; it can depend on context.
##### Books vs. Courses
Sometimes these can be hard to distinguish!
Courses often have associated textbooks, which we would list in our books lists. Courses have lectures, exercises, tests, notes or other didactic aids. A single lecture or video by itself is not a course. A powerpoint is not a course.
##### Interactive Tutorials vs. Other stuff
If you can print it out and retain its essence, it's not an Interactive Tutorial.
### Automation
- ่ฆๅฎๆ ผๅผ้ฉ่ญๆฏ็ฑ [GitHub Actions](https://docs.github.com/en/actions) ่ชๅๅ้ฒ่ก๏ผไฝฟ็จ [fpb-lint](https://github.com/vhf/free-programming-books-lint) ๅฅไปถ (ๅ้ฑ [`.github/workflows/fpb-lint.yml`](../.github/workflows/fpb-lint.yml))ใ
- ไฝฟ็จ [awesome_bot](https://github.com/dkhamsing/awesome_bot) ้ฒ่ก้ฃ็ต้ฉ่ญใ
- ๅฏไปฅ่็ฑๆไบคไธๅๅ
งๅฎนๅ
ๅซ`check_urls=file_to_check`ไพ่งธ็ผ้ฃ็ต้ฉ่ญ:
```properties
check_urls=free-programming-books.md free-programming-books-zh.md
```
- ๆจๅฏไปฅไปฅไธๅ็ฉบ็ฝๅ้ๅบๆณ่ฆ้ฒ่ก้ฉ่ญ็ๆชๆกๅ็จฑไพไธๆฌก้ฉ่ญๅคๅๆชๆกใ
- ๅฆๆๆจไธๆฌก้ฉ่ญๅคๅๆชๆก๏ผ่ชๅๅๆธฌ่ฉฆ็็ตๆๆๆฏๅบๆผๆๅพไธๅ้ฉ่ญ็ๆชๆกใๆจ็ๆธฌ่ฉฆๅฏ่ฝๆๅ ๆญค้้๏ผๅ ๆญค่ซ่ฉณๅ ็ขบ่ชๆธฌ่ฉฆๆฅ่ชใๅฏไปฅๅจ Pull Request ็ตๆไธญ้ป้ธ"Show all checks" -> "Details" ไพๆฅ็ใ
| free-programming-books/docs/CONTRIBUTING-zh_TW.md/0 | {
"file_path": "free-programming-books/docs/CONTRIBUTING-zh_TW.md",
"repo_id": "free-programming-books",
"token_count": 7730
} | 74 |
# How-To at a glance
<div align="right" markdown="1">
*[แขแถแแแถแแถแแถแแแแแแ](README.md#translations)*
</div>
**แแแแถแแแแแแแแถแแ `Free-Programming-Books`!**
แแพแแแธแแแถแ แแแผแ contributors แแแแธแ; แแแแแธแแถแแถแแถแPull Request (PR) แแถแแพแแแแแผแแแแแแขแแแแแแแแ แแ
GitHub แ. แแพแขแแแแแพแแแแ
แถแแแแแแพแ contibute แแแแผแ , แแแแถแแแถแแแแแแแขแถแ
แแฝแแขแแแแแถแ:
* [แขแแแธแแถ Pull Requests](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests) *(in english)*
* [แแแแแแแแแพแ pull request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request) *(in english)*
* [แแแแแ GitHub Hello World](https://docs.github.com/en/get-started/quickstart/hello-world) *(in english)*
* [YouTube - GitHub แแแแแถแแแขแแแแแพแแ
แถแแแแแแพแ](https://www.youtube.com/watch?v=0fKg7e37bQE) *(in english)*
* [YouTube - แแแแ Fork A GitHub Repo and Submit A Pull Request](https://www.youtube.com/watch?v=G1I3HF4YWEw) *(in english)*
* [YouTube - แแแแแแแแพ Markdown Crash Course](https://www.youtube.com/watch?v=HUBNt18RFbo) *(in english)*
แแปแแแแแถแ
แแแแปแแแถแแแฝแ; แแฝแแแพแแแถแแแขแแแแแแถแ
แถแแแแแแพแแแธแแถแแแแแแพแ PR แแแแผแ. แขแแแแแแขแถแ
แแถแขแแแแแธ แกแ แ แ แแแแแ! So... why not join our [large, growing](https://www.apiseven.com/en/contributor-graph?chart=contributorOverTime&repo=ebookfoundation/free-programming-books) community.
<details align="center" markdown="1">
<summary>Click to see the growth users vs. time graphs.</summary>
[](https://www.apiseven.com/en/contributor-graph?chart=contributorOverTime&repo=ebookfoundation/free-programming-books)
[](https://www.apiseven.com/en/contributor-graph?chart=contributorMonthlyActivity&repo=ebookfoundation/free-programming-books)
</details>
Even if you're an experienced open source contributor, there are things that might trip you up. แแแแขแแแแแแแแพแ PR แแแแผแ ***GitHub Actions* แแนแแแแแฝแแแทแแทแแแแขแแแขแแแแแแแแแแพ *linter*, often finding little issues with spacing or alphabetization**แ. แแแแแถแ
แแแแแแแแแแถแแแแแแถแขแแแแขแถแ
แแแแแพแ PR แแถแ แแแแปแแแ
แแทแแขแแแแแแแผแแแแแถแแปแแแทแแแพแแแแธแแแแแพแ PR แแแแ
แปแ
แแพแแถแแแ "Detailแ
แ
แปแแแแแ
แแ แแพแขแแแแขแแแ
แแแถแแแแถ แแแแถแแแแแแขแแแ แแถ `Free-Programming-Books` แฌแขแแ แ
แผแแขแแแแขแถแแแแแแแแแธแแแ [CONTRIBUTING](CONTRIBUTING.md)แ ([translations](README.md#translations))
| free-programming-books/docs/HOWTO-km.md/0 | {
"file_path": "free-programming-books/docs/HOWTO-km.md",
"repo_id": "free-programming-books",
"token_count": 2201
} | 75 |
# How-To at a glance
<div align="right" markdown="1">
*[Diฤer dillerde okumak iรงin](README.md#translations)*
</div>
**`Free-Programming-Books` Hoล Geldiniz!**
GitHub'da ilk Pull Request (PR) yapanlardan olsanฤฑz bile Katkฤฑda bulunmak iรงin yeni gelenleri memnuniyetle karลฤฑlฤฑyoruz. Eฤer onlardan biriyseniz, iลte size yardฤฑmcฤฑ olabilecek bazฤฑ kaynaklar:
* [รekme ฤฐstekleri Hakkฤฑnda](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests) *(iรงinde ingilizce dilinde)*
* [รekme isteฤi oluลturma](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request) *(iรงinde ingilizce dilinde)*
* [GitHub Merhaba Dรผnya](https://docs.github.com/en/get-started/quickstart/hello-world) *(iรงinde ingilizce dilinde)*
* [YouTube - Yeni Baลlayanlar ฤฐรงin GitHub Eฤitimi](https://www.youtube.com/watch?v=0fKg7e37bQE) *(iรงinde ingilizce dilinde)*
* [YouTube - Bir GitHub Repo Nasฤฑl รatallanฤฑr ve Bir รekme Talebi Nasฤฑl Gรถnderilir](https://www.youtube.com/watch?v=G1I3HF4YWEw) *(iรงinde ingilizce dilinde)*
* [YouTube - Markdown Crash Course](https://www.youtube.com/watch?v=HUBNt18RFbo) *(iรงinde ingilizce dilinde)*
Soru sormaktan รงekinmeyin; her katฤฑlฤฑmcฤฑ ilk bir PR ile baลladฤฑ. Binincimiz olabilirsin! So... why not join our [large, growing](https://www.apiseven.com/en/contributor-graph?chart=contributorOverTime&repo=ebookfoundation/free-programming-books) community.
<details align="center" markdown="1">
<summary>Click to see the growth users vs. time graphs.</summary>
[](https://www.apiseven.com/en/contributor-graph?chart=contributorOverTime&repo=ebookfoundation/free-programming-books)
[](https://www.apiseven.com/en/contributor-graph?chart=contributorMonthlyActivity&repo=ebookfoundation/free-programming-books)
</details>
Deneyimli bir aรงฤฑk kaynak katฤฑlฤฑmcฤฑsฤฑ olsanฤฑz bile, sizi rahatsฤฑz edebilecek ลeyler var. PR'nizi gรถnderdikten sonra,
***GitHub Actions*, genellikle boลluk veya alfabetik sฤฑralama ile ilgili kรผรงรผk sorunlar bularak bir *linter* รงalฤฑลtฤฑrฤฑr**. Yeลil bir dรผฤme alฤฑrsanฤฑz, her ลey gรถzden geรงirilmeye hazฤฑrdฤฑr, ancak deฤilse, linter'in neyi sevmediฤini bulmak iรงin baลarฤฑsฤฑz olan kontrolรผn altฤฑndaki "Details" ฤฑ tฤฑklayฤฑn. Sorunu dรผzeltin ve PR'nize bir taahhรผt ekleyin.
Nihayet, Eklemek istediฤiniz kaynaฤฤฑn `Free-Programming-Books` iรงin uygun olduฤundan emin deฤilseniz, [CONTRIBUTING](CONTRIBUTING.md) bรถlรผmรผndeki yรถnergeleri okuyun. ([translations](README.md#translations))
| free-programming-books/docs/HOWTO-tr.md/0 | {
"file_path": "free-programming-books/docs/HOWTO-tr.md",
"repo_id": "free-programming-books",
"token_count": 1234
} | 76 |
### Index
* [Competitive Programming](#competitive-programming)
* [CTF Capture the Flag](#capture-the-flag)
* [Data science](#data-science)
* [HTML and CSS](#html-and-css)
* [Ladders](#ladders)
* [Problem Sets](#problem-sets)
### Competitive Programming
* [A Way to Practice Competitive Programming](https://github.com/E869120/Competitive-Programming/blob/master/%5BTutorial%5D%20A%20Way%20to%20Practice%20Competitive%20Programming.pdf) - Masataka Yoneda (PDF)
* [A2 Online Judge](https://a2oj.netlify.app)
* [Algorithms for Competitive Programming](https://cp-algorithms.com)
* [APL Problem Solving Competition](https://contest.dyalog.com)
* [AtCoder](https://atcoder.jp)
* [beecrowd](https://www.beecrowd.com.br)
* [COCI](https://hsin.hr/coci/)
* [Codeabbey](http://www.codeabbey.com)
* [Codechef](https://www.codechef.com/contests)
* [Codecombat](https://codecombat.com)
* [Codeeval](https://www.codeeval.com)
* [CodeFights](https://codefights.com)
* [Codeforces](http://codeforces.com/contests)
* [Codeground](https://www.codeground.org)
* [Coderbyte](https://coderbyte.com)
* [Codewars](http://www.codewars.com)
* [Codingame](https://www.codingame.com/start)
* [Competitive Programming Cheat Sheet](https://medium.com/cheat-sheets/cheat-sheet-for-competitive-programming-with-c-f2e8156d5aa9)
* [CSES Problem Set](https://cses.fi/problemset)
* [Dimik](https://dimikoj.com)
* [DMOJ](https://dmoj.ca)
* [E-olymp](https://www.e-olymp.com/en/)
* [Exercism](https://exercism.org)
* [HackerEarth](https://www.hackerearth.com)
* [Hackerrank](https://www.hackerrank.com)
* [Internet Problem Solving Contest](http://ipsc.ksp.sk)
* [Just another Golf Coding](http://jagc.org)
* [Kattis](https://open.kattis.com)
* [Last Moment DSA Sheet(79) โ Ace Interviews](https://takeuforward.org/interview-sheets/strivers-79-last-moment-dsa-sheet-ace-interviews) - Striver
* [LeetCode](https://leetcode.com)
* [LightOJ](https://lightoj.com)
* [Meta Hackercup](https://www.facebook.com/codingcompetitions/hacker-cup/)
* [Newton School](https://my.newtonschool.co/contest/all)
* [oj.uz](https://oj.uz)
* [Sigmageek](https://sigmageek.com)
* [Sphere Online Judge](http://www.spoj.com/contests)
* [Techgig](https://www.techgig.com)
* [Top Coding Interview Problems](https://takeuforward.org/interviews/strivers-sde-sheet-top-coding-interview-problems/) - Striver
* [Topcoder](https://www.topcoder.com)
* [Toph](https://toph.co)
* [USACO.guide](https://usaco.guide)
### Capture the flag
* [รฅngstromCTF](https://angstromctf.com)
* [CTFlearn](https://ctflearn.com) (email address *requested*)
* [CTFtime](https://ctftime.org)
* [DamnVulnerableDefi](https://www.damnvulnerabledefi.xyz)
* [echoCTF](https://echoctf.red) (email address *requested*)
* [Google CTF](https://capturetheflag.withgoogle.com) (email address *requested*)
* [Hacker101](https://ctf.hacker101.com) (email address *requested*)
* [Hackthebox](https://www.hackthebox.eu) (email address *requested*)
* [HackThisSite](https://www.hackthissite.org) (email address *requested*)
* [InCTF](https://inctf.in)
* [Microcorruption](https://microcorruption.com/login)
* [Overthewire Wargames fungame to practice CTF](https://overthewire.org/wargames/bandit)
* [Picoctf](https://picoctf.org/resources.html) (email address *requested*)
* [ringzer0ctf](https://ringzer0ctf.com/home) (email address *required*)
* [ROP Wargame Repository](https://github.com/xelenonz/game)
* [SmashTheStack](http://www.smashthestack.org/main.html#wargames)
* [TryHackMe](https://tryhackme.com) (email address *requested*)
### Data science
* [AIcrowd](https://www.aicrowd.com)
* [CodaLab](https://codalab.lisn.upsaclay.fr)
* [CrowdANALYTIX](https://www.crowdanalytix.com/community)
* [DrivenData](https://www.drivendata.org)
* [Kaggle](https://www.kaggle.com)
* [Zindi](https://zindi.africa)
### HTML and CSS
* [Frontend Mentor](https://www.frontendmentor.io/challenges?languages=CSS&sort=difficulty%7Casc&type=free) *(email address requested)*
### Ladders
* [A2 Online Judge](https://a2oj.netlify.app)
* [Atcoder Problems](https://kenkoooo.com/atcoder/#/table)
* [C2 Ladders](https://c2-ladders-juol.onrender.com)
* [Striver's A2Z DSA Course/sheet](https://takeuforward.org/strivers-a2z-dsa-course/strivers-a2z-dsa-course-sheet-2)
* [Striverโs CP Sheet](https://takeuforward.org/interview-experience/strivers-cp-sheet/)
### Problem Sets
* [#C++](https://www.youtube.com/playlist?list=PLliXPok7ZonkJEe0cUbVZ3umyKbFA-Dd9) - Keerti Purswani
* [100 Days CSS Challenge](https://100dayscss.com) - Matthias Martin *(Codepen account requested, not required)*
* [500 Data structures and algorithms interview questions and their solutions in C++](https://www.quora.com/q/techiedelight/500-Data-Structures-and-Algorithms-interview-questions-and-their-solutions)
* [Abekus \| Free Practice Questions with Solutions](https://abekus.com)
* [Advent Of Code](http://adventofcode.com)
* [AdventJS - 25 dรญas de retos con JavaScript](https://adventjs.dev) - Miguel รngel Durรกn ยซmidudevยป *(GitHub account requested, not required)*
* [Anarchy Golf](http://golf.shinh.org)
* [APL Practice Problems](https://problems.tryapl.org)
* [BaekJoon Online Judge](http://www.acmicpc.net)
* [beecrowd](https://www.beecrowd.com.br)
* [CareerCup](http://www.careercup.com)
* [CheckIO](http://www.checkio.org)
* [Codechef](https://www.codechef.com/problems/school)
* [Codedrills](https://codedrills.io/competitive)
* [Codeforces](http://codeforces.com/problemset)
* [Codility](https://codility.com/programmers/)
* [Coding Bat](http://codingbat.com/java)
* [Coding Interview Questions and answers for practice \| Python, Java & C++](https://www.codingninjas.com/codestudio/problems) - CodingNinjas
* [Coding Ninjas Guided Paths](https://www.codingninjas.com/codestudio/guided-paths/data-structures-algorithms)
* [CSES Problem Set](https://cses.fi/problemset/)
* [DSA Learning Series](https://www.codechef.com/LEARNDSA)
* [Dynamic A2OJ Ladder](https://a2oj.herokuapp.com)
* [Edabit](https://edabit.com)
* [Exercism](http://exercism.io)
* [Geeks For Geeks](https://practice.geeksforgeeks.org)
* [Grind 75](https://www.techinterviewhandbook.org/grind75)
* [Hacker.org](http://www.hacker.org)
* [HackerEarth](https://www.hackerearth.com)
* [HDU Online Judge](http://acm.hdu.edu.cn)
* [IndiaBix](https://www.indiabix.com)
* [Interactive Coding Challenge](https://github.com/donnemartin/interactive-coding-challenges)
* [InterviewBit](https://www.interviewbit.com)
* [Kattis](https://open.kattis.com)
* [Mathproblem of the Month - Bilkent University](http://www.fen.bilkent.edu.tr/~cvmath/prob-month.html)
* [PEG Judge](http://wcipeg.com)
* [Pep Coding](https://www.pepcoding.com/resources)
* [PKU Online Judge](http://poj.org)
* [Ponder This!](https://www.research.ibm.com/haifa/ponderthis/index.shtml)
* [Practice Python](https://www.practicepython.org)
* [ProblemBook.NET](https://github.com/AndreyAkinshin/ProblemBook.NET)
* [Project Euler](https://projecteuler.net)
* [Python Practice Projects](http://pythonpracticeprojects.com)
* [Rosalind](http://rosalind.info/problems/locations/)
* [Sphere Online Judge](http://www.spoj.com/problems/classical)
* [TalentBuddy](http://www.talentbuddy.co/blog/)
* [The Ultimate Topic List(with Tutorials, Problems, and Templates)](https://blog.shahjalalshohag.com/topic-list/) - Shahjalal Shohag
* [Timus Online Judge](http://acm.timus.ru)
* [Top Interview 150](https://leetcode.com/studyplan/top-interview-150/) - LeetCode
* [Topic wise multiple choice questions in computer science](https://www.geeksforgeeks.org/quiz-corner-gq/#C%20Programming%20Mock%20Tests) - Geeks For Geeks
* [UVa Online Judge](https://uva.onlinejudge.org/index.php?Itemid=8&option=com_onlinejudge)
* [Vulnhub.com](https://www.vulnhub.com)
* [ะจะบะพะปะฐ ะฟัะพะณัะฐะผะผะธััะฐ](https://acmp.ru)
| free-programming-books/more/problem-sets-competitive-programming.md/0 | {
"file_path": "free-programming-books/more/problem-sets-competitive-programming.md",
"repo_id": "free-programming-books",
"token_count": 2951
} | 77 |
# JavaScript ์๊ณ ๋ฆฌ์ฆ ๋ฐ ์๋ฃ ๊ตฌ์กฐ
[](https://github.com/trekhleb/javascript-algorithms/actions?query=workflow%3ACI+branch%3Amaster)
[](https://codecov.io/gh/trekhleb/javascript-algorithms)
์ด ์ ์ฅ์์๋ ๋ง์ด ์๋ ค์ง ์๊ณ ๋ฆฌ์ฆ ๋ฐ ์๋ฃ ๊ตฌ์กฐ์ Javascript ๊ธฐ๋ฐ ์์ ๋ฅผ ๋ด๊ณ ์์ต๋๋ค.
๊ฐ ์๊ณ ๋ฆฌ์ฆ๊ณผ ์๋ฃ ๊ตฌ์กฐ์ ๋ํด ์ฐ๊ด๋์ด ์๋ ์ค๋ช
์ด README์ ์์ฑ๋์ด ์์ผ๋ฉฐ,
๋งํฌ๋ฅผ ํตํด ๋ ์์ธํ ์ค๋ช
์ ๋ง๋ ์ ์์ต๋๋ค. (๊ด๋ จ๋ YouTube ์์๋ ํฌํจ).
_Read this in other languages:_
[_English_](https://github.com/trekhleb/javascript-algorithms/),
[_็ฎไฝไธญๆ_](README.zh-CN.md),
[_็น้ซไธญๆ_](README.zh-TW.md),
[_ๆฅๆฌ่ช_](README.ja-JP.md),
[_Polski_](README.pl-PL.md),
[_Franรงais_](README.fr-FR.md),
[_Espaรฑol_](README.es-ES.md),
[_Portuguรชs_](README.pt-BR.md),
[_ะ ัััะบะธะน_](README.ru-RU.md),
[_Tรผrk_](README.tr-TR.md),
[_Italiana_](README.it-IT.md),
[_Bahasa Indonesia_](README.id-ID.md),
[_ะฃะบัะฐัะฝััะบะฐ_](README.uk-UA.md),
[_Arabic_](README.ar-AR.md),
[_Tiแบฟng Viแปt_](README.vi-VN.md),
[_Deutsch_](README.de-DE.md)
## ์๋ฃ ๊ตฌ์กฐ
์๋ฃ ๊ตฌ์กฐ๋ ๋ฐ์ดํฐ๋ฅผ ํน์ ๋ฐฉ์์ผ๋ก ๊ตฌ์ฑํ๊ณ ์ ์ฅํจ์ผ๋ก์จ ๋ ํจ์จ์ ์ผ๋ก
์ ๊ทผํ๊ณ ์์ ํ ์ ์๊ฒ ํด์ค๋๋ค. ๊ฐ๋จํ ๋งํด, ์๋ฃ ๊ตฌ์กฐ๋ ๋ฐ์ดํฐ ๊ฐ๋ค,
๋ฐ์ดํฐ ๊ฐ์ ๊ด๊ณ, ๊ทธ๋ฆฌ๊ณ ๋ฐ์ดํฐ๋ฅผ ๋ค๋ฃฐ ์ ์๋ ํจ์์ ์์
์ ๋ชจ์์
๋๋ค.
`B` - ์
๋ฌธ์, `A` - ์๋ จ์
* `B` [์ฐ๊ฒฐ ๋ฆฌ์คํธ](src/data-structures/linked-list)
* `B` [์ด์ค ์ฐ๊ฒฐ ๋ฆฌ์คํธ](src/data-structures/doubly-linked-list)
* `B` [ํ](src/data-structures/queue)
* `B` [์คํ](src/data-structures/stack)
* `B` [ํด์ ํ
์ด๋ธ](src/data-structures/hash-table)
* `B` [ํ](src/data-structures/heap)
* `B` [์ฐ์ ์์ ํ](src/data-structures/priority-queue)
* `A` [ํธ๋ผ์ด](src/data-structures/trie)
* `A` [ํธ๋ฆฌ](src/data-structures/tree)
* `A` [์ด์ง ํ์ ํธ๋ฆฌ](src/data-structures/tree/binary-search-tree)
* `A` [AVL ํธ๋ฆฌ](src/data-structures/tree/avl-tree)
* `A` [Red-Black ํธ๋ฆฌ](src/data-structures/tree/red-black-tree)
* `A` [์ธ๊ทธ๋จผํธ ํธ๋ฆฌ](src/data-structures/tree/segment-tree) - min/max/sum range ์ฟผ๋ฆฌ ์์ .
* `A` [Fenwick ํธ๋ฆฌ](src/data-structures/tree/fenwick-tree) (Binary Indexed Tree)
* `A` [๊ทธ๋ํ](src/data-structures/graph) (์ ๋ฐฉํฅ, ๋ฌด๋ฐฉํฅ)
* `A` [์๋ก์ ์งํฉ](src/data-structures/disjoint-set)
* `A` [๋ธ๋ฃธ ํํฐ](src/data-structures/bloom-filter)
## ์๊ณ ๋ฆฌ์ฆ
์๊ณ ๋ฆฌ์ฆ์ ์ด๋ค ์ข
๋ฅ์ ๋ฌธ์ ๋ฅผ ํ ์ ์๋ ์ ํํ ๋ฐฉ๋ฒ์ด๋ฉฐ,
์ผ๋ จ์ ์์
์ ์ ํํ๊ฒ ์ ์ํด ๋์ ๊ท์น๋ค์
๋๋ค.
`B` - ์
๋ฌธ์, `A` - ์๋ จ์
### ์ฃผ์ ๋ณ ์๊ณ ๋ฆฌ์ฆ
* **Math**
* `B` [Bit Manipulation](src/algorithms/math/bits) - set/get/update/clear bits, 2์ ๊ณฑ / ๋๋๊ธฐ, ์์๋ก ๋ง๋ค๊ธฐ etc.
* `B` [ํฉํ ๋ฆฌ์ผ](src/algorithms/math/factorial)
* `B` [ํผ๋ณด๋์น ์](src/algorithms/math/fibonacci)
* `B` [์์ ํ๋ณ](src/algorithms/math/primality-test) (trial division ๋ฐฉ์)
* `B` [์ ํด๋ฆฌ๋ ํธ์ ๋ฒ](src/algorithms/math/euclidean-algorithm) - ์ต๋๊ณต์ฝ์ (GCD)
* `B` [์ต์ ๊ณต๋ฐฐ์](src/algorithms/math/least-common-multiple) - LCM
* `B` [์๋ผํ ์คํ
๋ค์ค์ ์ฒด](src/algorithms/math/sieve-of-eratosthenes) - ํน์ ์ ์ดํ์ ๋ชจ๋ ์์ ์ฐพ๊ธฐ
* `B` [2์ ๊ฑฐ๋ญ์ ๊ณฑ ํ๋ณ๋ฒ](src/algorithms/math/is-power-of-two) - ์ด๋ค ์๊ฐ 2์ ๊ฑฐ๋ญ์ ๊ณฑ์ธ์ง ํ๋ณ (naive ์ bitwise ์๊ณ ๋ฆฌ์ฆ)
* `B` [ํ์ค์นผ ์ผ๊ฐํ](src/algorithms/math/pascal-triangle)
* `A` [์์ฐ์ ๋ถํ ](src/algorithms/math/integer-partition)
* `A` [๋ฆฌ์ฐ ํ์ด ฯ ์๊ณ ๋ฆฌ์ฆ](src/algorithms/math/liu-hui) - N-๊ฐํ์ ๊ธฐ๋ฐ์ผ๋ก ฯ ๊ทผ์ฌ์น ๊ตฌํ๊ธฐ
* **Sets**
* `B` [์นดํฐ์ง์ธ ํ๋ก๋ํธ](src/algorithms/sets/cartesian-product) - ๊ณฑ์งํฉ
* `B` [FisherโYates ์
ํ](src/algorithms/sets/fisher-yates) - ์ ํ ์ํ์ค์ ๋ฌด์์ ์์ด
* `A` [๋ฉฑ์งํฉ](src/algorithms/sets/power-set) - ์งํฉ์ ๋ชจ๋ ๋ถ๋ถ์งํฉ
* `A` [์์ด](src/algorithms/sets/permutations) (๋ฐ๋ณต ์ ,๋ฌด)
* `A` [์กฐํฉ](src/algorithms/sets/combinations) (๋ฐ๋ณต ์ ,๋ฌด)
* `A` [์ต์ฅ ๊ณตํต ๋ถ๋ถ์์ด](src/algorithms/sets/longest-common-subsequence) (LCS)
* `A` [์ต์ฅ ์ฆ๊ฐ ์์ด](src/algorithms/sets/longest-increasing-subsequence)
* `A` [Shortest Common Supersequence](src/algorithms/sets/shortest-common-supersequence) (SCS)
* `A` [๋ฐฐ๋ญ ๋ฌธ์ ](src/algorithms/sets/knapsack-problem) - "0/1" ๊ณผ "Unbound"
* `A` [์ต๋ ๊ตฌ๊ฐํฉ](src/algorithms/sets/maximum-subarray) - "๋ธ๋ฃจํธ ํฌ์ค" ๊ณผ "๋์ ๊ณํ๋ฒ" (Kadane's) ๋ฒ์
* `A` [์กฐํฉ ํฉ](src/algorithms/sets/combination-sum) - ํน์ ํฉ์ ๊ตฌ์ฑํ๋ ๋ชจ๋ ์กฐํฉ ์ฐพ๊ธฐ
* **Strings**
* `B` [ํด๋ฐ ๊ฑฐ๋ฆฌ](src/algorithms/string/hamming-distance) - ์ฌ๋ณผ์ด ๋ค๋ฅธ ์์น์ ๊ฐฏ์
* `A` [ํธ์ง ๊ฑฐ๋ฆฌ](src/algorithms/string/levenshtein-distance) - ๋ ์ํ์ค ๊ฐ์ ์ต์ ํธ์ง๊ฑฐ๋ฆฌ
* `A` [์ปค๋์ค-๋ชจ๋ฆฌ์ค-ํ๋ซ ์๊ณ ๋ฆฌ์ฆ](src/algorithms/string/knuth-morris-pratt) (KMP ์๊ณ ๋ฆฌ์ฆ) - ๋ถ๋ถ ๋ฌธ์์ด ํ์ (ํจํด ๋งค์นญ)
* `A` [Z ์๊ณ ๋ฆฌ์ฆ](src/algorithms/string/z-algorithm) - ๋ถ๋ถ ๋ฌธ์์ด ํ์ (ํจํด ๋งค์นญ)
* `A` [๋ผ๋น ์นดํ ์๊ณ ๋ฆฌ์ฆ](src/algorithms/string/rabin-karp) - ๋ถ๋ถ ๋ฌธ์์ด ํ์
* `A` [์ต์ฅ ๊ณตํต ๋ถ๋ถ ๋ฌธ์์ด](src/algorithms/string/longest-common-substring)
* `A` [์ ๊ท ํํ์ ๋งค์นญ](src/algorithms/string/regular-expression-matching)
* **Searches**
* `B` [์ ํ ํ์](src/algorithms/search/linear-search)
* `B` [์ ํ ํ์](src/algorithms/search/jump-search) (or Block Search) - ์ ๋ ฌ๋ ๋ฐฐ์ด์์ ํ์
* `B` [์ด์ง ํ์](src/algorithms/search/binary-search) - ์ ๋ ฌ๋ ๋ฐฐ์ด์์ ํ์
* `B` [๋ณด๊ฐ ํ์](src/algorithms/search/interpolation-search) - ๊ท ๋ฑํ ๋ถํฌ๋ฅผ ์ด๋ฃจ๋ ์ ๋ ฌ๋ ๋ฐฐ์ด์์ ํ์
* **Sorting**
* `B` [๊ฑฐํ ์ ๋ ฌ](src/algorithms/sorting/bubble-sort)
* `B` [์ ํ ์ ๋ ฌ](src/algorithms/sorting/selection-sort)
* `B` [์ฝ์
์ ๋ ฌ](src/algorithms/sorting/insertion-sort)
* `B` [ํ ์ ๋ ฌ](src/algorithms/sorting/heap-sort)
* `B` [๋ณํฉ ์ ๋ ฌ](src/algorithms/sorting/merge-sort)
* `B` [ํต ์ ๋ ฌ](src/algorithms/sorting/quick-sort) - ์ ์๋ฆฌ(in-place)์ ์ ์๋ฆฌ๊ฐ ์๋(non-in-place) ๊ตฌํ
* `B` [์
ธ ์ ๋ ฌ](src/algorithms/sorting/shell-sort)
* `B` [๊ณ์ ์ ๋ ฌ](src/algorithms/sorting/counting-sort)
* `B` [๊ธฐ์ ์ ๋ ฌ](src/algorithms/sorting/radix-sort)
* **Trees**
* `B` [๊น์ด ์ฐ์ ํ์](src/algorithms/tree/depth-first-search) (DFS)
* `B` [๋๋น ์ฐ์ ํ์](src/algorithms/tree/breadth-first-search) (BFS)
* **Graphs**
* `B` [๊น์ด ์ฐ์ ํ์](src/algorithms/graph/depth-first-search) (DFS)
* `B` [๋๋น ์ฐ์ ํ์](src/algorithms/graph/breadth-first-search) (BFS)
* `B` [ํฌ๋ฃจ์ค์นผ ์๊ณ ๋ฆฌ์ฆ](src/algorithms/graph/kruskal) - ์ต์ ์ ์ฅ ํธ๋ฆฌ ์ฐพ๊ธฐ (MST) ๋ฌด๋ฐฉํฅ ๊ฐ์ค ๊ทธ๋ํ
* `A` [๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ](src/algorithms/graph/dijkstra) - ํ ์ ์์ ๋ค๋ฅธ ๋ชจ๋ ์ ๊น์ง ์ต๋จ ๊ฑฐ๋ฆฌ ์ฐพ๊ธฐ
* `A` [๋ฒจ๋ง-ํฌ๋ ์๊ณ ๋ฆฌ์ฆ](src/algorithms/graph/bellman-ford) - ํ ์ ์์ ๋ค๋ฅธ ๋ชจ๋ ์ ๊น์ง ์ต๋จ ๊ฑฐ๋ฆฌ ์ฐพ๊ธฐ
* `A` [ํ๋ก์ด๋-์์
์๊ณ ๋ฆฌ์ฆ](src/algorithms/graph/floyd-warshall) - ๋ชจ๋ ์ข
๋จ ๊ฐ์ ์ต๋จ๊ฑฐ๋ฆฌ ์ฐพ๊ธฐ
* `A` [์ฌ์ดํด ํ์ง](src/algorithms/graph/detect-cycle) - ์ ๋ฐฉํฅ, ๋ฌด๋ฐฉํฅ ๊ทธ๋ํ (DFS ์ Disjoint Set ์ ๊ธฐ๋ฐํ ๋ฒ์ )
* `A` [ํ๋ฆผ ์๊ณ ๋ฆฌ์ฆ](src/algorithms/graph/prim) - ๋ฌด๋ฐฉํฅ ๊ฐ์ค์น ๊ทธ๋ํ์์ ์ต์ ์ ์ฅ ํธ๋ฆฌ (MST) ์ฐพ๊ธฐ
* `A` [์์ ์ ๋ ฌ](src/algorithms/graph/topological-sorting) - DFS ๋ฐฉ์
* `A` [๋จ์ ์ ](src/algorithms/graph/articulation-points) - ํ์์ ์๊ณ ๋ฆฌ์ฆ (DFS ๊ธฐ๋ฐ)
* `A` [๋จ์ ์ ](src/algorithms/graph/bridges) - DFS ๊ธฐ๋ฐ ์๊ณ ๋ฆฌ์ฆ
* `A` [์ค์ผ๋ฌ ๊ฒฝ๋ก ์ ์ค์ผ๋ฌ ํ๋ก](src/algorithms/graph/eulerian-path) - Fleury์ ์๊ณ ๋ฆฌ์ฆ - ๋ชจ๋ ์ฃ์ง๋ฅผ ํ๋ฒ๋ง ๋ฐฉ๋ฌธ
* `A` [ํด๋ฐํด ๊ฒฝ๋ก](src/algorithms/graph/hamiltonian-cycle) - ๋ชจ๋ ๊ผญ์ง์ ์ ํ๋ฒ๋ง ๋ฐฉ๋ฌธ
* `A` [๊ฐ๊ฒฐํฉ ์ปดํฌ๋ํธ](src/algorithms/graph/strongly-connected-components) - Kosaraju์ ์๊ณ ๋ฆฌ์ฆ
* `A` [์ธํ์ ๋ฌธ์ ](src/algorithms/graph/travelling-salesman) - ๊ฐ ๋์๋ฅผ ๋ค ๋ฐฉ๋ฌธํ๊ณ ๋ค์ ์ถ๋ฐ์ ์ผ๋ก ๋์์ค๋ ์ต๋จ ๊ฒฝ๋ก ์ฐพ๊ธฐ
* **Uncategorized**
* `B` [ํ๋
ธ์ด ํ](src/algorithms/uncategorized/hanoi-tower)
* `B` [์ ๋ฐฉ ํ๋ ฌ ํ์ ](src/algorithms/uncategorized/square-matrix-rotation) - ์ ์๋ฆฌ(in-place) ์๊ณ ๋ฆฌ์ฆ
* `B` [์ ํ ๊ฒ์](src/algorithms/uncategorized/jump-game) - ๋ฐฑํธ๋ํน, ๋์ ๊ณํ๋ฒ (top-down + bottom-up), ํ์ ์๊ณ ๋ฆฌ์ฆ ์์
* `B` [Unique ๊ฒฝ๋ก](src/algorithms/uncategorized/unique-paths) - ๋ฐฑํธ๋ํน, ๋์ ๊ณํ๋ฒ, ํ์ค์นผ ์ผ๊ฐํ์ ๊ธฐ๋ฐํ ์์
* `B` [๋น๋ฌผ ๋ด๊ธฐ ๋ฌธ์ ](src/algorithms/uncategorized/rain-terraces) - trapping rain water problem (๋์ ๊ณํ๋ฒ, ๋ธ๋ฃจํธํฌ์ค ๋ฒ์ )
* `A` [N-Queens ๋ฌธ์ ](src/algorithms/uncategorized/n-queens)
* `A` [๊ธฐ์ฌ์ ์ฌํ ๋ฌธ์ ](src/algorithms/uncategorized/knight-tour)
### ํจ๋ฌ๋ค์๋ณ ์๊ณ ๋ฆฌ์ฆ
์๊ณ ๋ฆฌ์ฆ ํจ๋ฌ๋ค์ ์ด๋, ์๊ณ ๋ฆฌ์ฆ์ด ์ฃผ์ด์ง ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด ์ฑํํ ๊ธฐ์ด๊ฐ ๋๋ ์ผ๋ฐ์ ์ธ ๋ฐฉ๋ฒ ํน์ ์ ๊ทผ๋ฒ์
๋๋ค. ์๊ณ ๋ฆฌ์ฆ์ด ํด๊ฒฐํ๋ ๋ฌธ์ ๋ ์๊ณ ๋ฆฌ์ฆ์ ๋์ ๋ฐฉ์์ด ์์ ํ ๋ค๋ฅด๋๋ผ๋,์๊ณ ๋ฆฌ์ฆ์ ๋์ ์์น์ด ๊ฐ์ผ๋ฉด ๊ฐ์ ํจ๋ฌ๋ค์์ ์ฌ์ฉํ๋ค๊ณ ๋งํ ์ ์์ผ๋ฉฐ, ์ฃผ๋ก ์๊ณ ๋ฆฌ์ฆ์ ๊ตฌ๋ถํ๋ ๊ธฐ์ค์ผ๋ก ์ฐ์ธ๋ค. ์๊ณ ๋ฆฌ์ฆ์ด ์ผ๋ฐ์ ์ธ ์ปดํจํฐ์ ํ๋ก๊ทธ๋จ์ ๋ํ ๊ฐ๋
๋ณด๋ค ๋ณด๋ค ๋ ์ถ์์ ์ธ ๊ฐ๋
์ธ ๊ฒ์ฒ๋ผ ์๊ณ ๋ฆฌ์ฆ์ ํจ๋ฌ๋ค์์ ๋ช
ํํ ์ ์๋ ์ํ์ ์ค์ฒด๊ฐ ์๋ ๊ฒ์ด ์๋๊ธฐ ๋๋ฌธ์ ๊ทธ ์ด๋ค ์๊ณ ๋ฆฌ์ฆ์ ๊ฐ๋
๋ณด๋ค๋ ํจ์ฌ ์ถ์์ ์ธ ๊ฐ๋
์
๋๋ค.
* **๋ธ๋ฃจํธ ํฌ์ค(Brute Force)** - ๊ฐ๋ฅํ ๋ชจ๋ ๊ฒฝ์ฐ๋ฅผ ํ์ํ ๋ค ์ต์ ์ ์ฐพ์๋ด๋ ๋ฐฉ์์
๋๋ค.
* `B` [์ ํ ํ์](src/algorithms/search/linear-search)
* `B` [๋น๋ฌผ ๋ด๊ธฐ ๋ฌธ์ ](src/algorithms/uncategorized/rain-terraces) - trapping rain water problem
* `A` [์ต๋ ๊ตฌ๊ฐํฉ](src/algorithms/sets/maximum-subarray)
* `A` [์ธํ์ ๋ฌธ์ ](src/algorithms/graph/travelling-salesman) - ๊ฐ ๋์๋ฅผ ๋ค ๋ฐฉ๋ฌธํ๊ณ ๋ค์ ์ถ๋ฐ์ ์ผ๋ก ๋์์ค๋ ์ต๋จ ๊ฒฝ๋ก ์ฐพ๊ธฐ
* **ํ์ ์๊ณ ๋ฆฌ์ฆ(Greedy)** - ์ดํ๋ฅผ ๊ณ ๋ คํ์ง ์๊ณ ํ์ฌ ์์ ์์ ๊ฐ์ฅ ์ต์ ์ธ ์ ํ์ ํ๋ ๋ฐฉ์์
๋๋ค.
* `B` [์ ํ ๊ฒ์](src/algorithms/uncategorized/jump-game)
* `A` [์ชผ๊ฐค์ ์๋ ๋ฐฐ๋ญ ๋ฌธ์ ](src/algorithms/sets/knapsack-problem)
* `A` [๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ](src/algorithms/graph/dijkstra) - ๋ชจ๋ ์ ๊น์ง์ ์ต๋จ๊ฑฐ๋ฆฌ ์ฐพ๊ธฐ
* `A` [ํ๋ฆผ ์๊ณ ๋ฆฌ์ฆ](src/algorithms/graph/prim) - ๋ฌด๋ฐฉํฅ ๊ฐ์ค์น ๊ทธ๋ํ์์ ์ต์ ์ ์ฐฝ ํธ๋ฆฌ (MST) ์ฐพ๊ธฐ
* `A` [ํฌ๋ฃจ์ค์นผ ์๊ณ ๋ฆฌ์ฆ](src/algorithms/graph/kruskal) - ๋ฌด๋ฐฉํฅ ๊ฐ์ค์น ๊ทธ๋ํ์์ ์ต์ ์ ์ฐฝ ํธ๋ฆฌ (MST) ์ฐพ๊ธฐ
* **๋ถํ ์ ๋ณต๋ฒ(Divide and Conquer)** - ๋ฌธ์ ๋ฅผ ์ฌ๋ฌ ์์ ๋ฌธ์ ๋ก ๋ถํ ํ ๋ค ํด๊ฒฐํ๋ ๋ฐฉ์์
๋๋ค.
* `B` [์ด์ง ํ์](src/algorithms/search/binary-search)
* `B` [ํ๋
ธ์ด ํ](src/algorithms/uncategorized/hanoi-tower)
* `B` [ํ์ค์นผ ์ผ๊ฐํ](src/algorithms/math/pascal-triangle)
* `B` [์ ํด๋ฆฌ๋ ํธ์ ๋ฒ](src/algorithms/math/euclidean-algorithm) - ์ต๋๊ณต์ฝ์ ๊ณ์ฐ (GCD)
* `B` [๋ณํฉ ์ ๋ ฌ](src/algorithms/sorting/merge-sort)
* `B` [ํต ์ ๋ ฌ](src/algorithms/sorting/quick-sort)
* `B` [ํธ๋ฆฌ ๊น์ด ์ฐ์ ํ์](src/algorithms/tree/depth-first-search) (DFS)
* `B` [๊ทธ๋ํ ๊น์ด ์ฐ์ ํ์](src/algorithms/graph/depth-first-search) (DFS)
* `B` [์ ํ ๊ฒ์](src/algorithms/uncategorized/jump-game)
* `A` [์์ด](src/algorithms/sets/permutations) (๋ฐ๋ณต ์ ,๋ฌด)
* `A` [์กฐํฉ](src/algorithms/sets/combinations) (๋ฐ๋ณต ์ ,๋ฌด)
* **๋์ ๊ณํ๋ฒ(Dynamic Programming)** - ์ด์ ์ ์ฐพ์ ๊ฒฐ๊ณผ๋ฅผ ์ด์ฉํ์ฌ ์ต์ข
์ ์ผ๋ก ํด๊ฒฐํ๋ ๋ฐฉ์์
๋๋ค.
* `B` [ํผ๋ณด๋์น ์](src/algorithms/math/fibonacci)
* `B` [์ ํ ๊ฒ์](src/algorithms/uncategorized/jump-game)
* `B` [Unique Paths](src/algorithms/uncategorized/unique-paths)
* `B` [๋น๋ฌผ ๋ด๊ธฐ ๋ฌธ์ ](src/algorithms/uncategorized/rain-terraces) - trapping rain water problem
* `A` [ํธ์ง ๊ฑฐ๋ฆฌ](src/algorithms/string/levenshtein-distance) - ๋ ์ํ์ค ๊ฐ์ ์ต์ ํธ์ง ๊ฑฐ๋ฆฌ
* `A` [์ต์ฅ ๊ณตํต ๋ถ๋ถ ์์ด](src/algorithms/sets/longest-common-subsequence) (LCS)
* `A` [์ต์ฅ ๊ณตํต ๋ถ๋ถ ๋ฌธ์์ด](src/algorithms/string/longest-common-substring)
* `A` [์ต์ฅ ์ฆ๊ฐ ์์ด](src/algorithms/sets/longest-increasing-subsequence)
* `A` [Shortest Common Supersequence](src/algorithms/sets/shortest-common-supersequence)
* `A` [0/1 ๋ฐฐ๋ญ ๋ฌธ์ ](src/algorithms/sets/knapsack-problem)
* `A` [์์ฐ์ ๋ถํ ](src/algorithms/math/integer-partition)
* `A` [์ต๋ ๊ตฌ๊ฐํฉ](src/algorithms/sets/maximum-subarray)
* `A` [๋ฒจ๋ง-ํฌ๋ ์๊ณ ๋ฆฌ์ฆ](src/algorithms/graph/bellman-ford) - ๋ชจ๋ ์ ๊น์ง์ ์ต๋จ ๊ฑฐ๋ฆฌ ์ฐพ๊ธฐ
* `A` [ํ๋ก์ด๋-์์
์๊ณ ๋ฆฌ์ฆ](src/algorithms/graph/floyd-warshall) - ๋ชจ๋ ์ข
๋จ ๊ฐ์ ์ต๋จ๊ฑฐ๋ฆฌ ์ฐพ๊ธฐ
* `A` [์ ๊ท ํํ์ ๋งค์นญ](src/algorithms/string/regular-expression-matching)
* **๋ฐฑํธ๋ํน(Backtracking)** - ๋ชจ๋ ๊ฐ๋ฅํ ๊ฒฝ์ฐ๋ฅผ ๊ณ ๋ คํ๋ค๋ ์ ์์ ๋ธ๋ฃจํธ ํฌ์ค์ ์ ์ฌํฉ๋๋ค. ํ์ง๋ง ๋ค์ ๋จ๊ณ๋ก ๋์ด๊ฐ๋ ๋ง๋ค ๋ชจ๋ ์กฐ๊ฑด์ ๋ง์กฑํ๋์ง ํ์ธํ๊ณ ์งํํฉ๋๋ค. ๋ง์ฝ ์กฐ๊ฑด์ ๋ง์กฑํ์ง ๋ชปํ๋ค๋ฉด ๋ค๋ก ๋์๊ฐ๋๋ค (๋ฐฑํธ๋ํน). ๊ทธ๋ฆฌ๊ณ ๋ค๋ฅธ ๊ฒฝ๋ก๋ฅผ ์ ํํฉ๋๋ค. ๋ณดํต ์ํ๋ฅผ ์ ์งํ DFS ํ์์ ๋ง์ด ์ฌ์ฉํฉ๋๋ค.
* `B` [์ ํ ๊ฒ์](src/algorithms/uncategorized/jump-game)
* `B` [Unique Paths](src/algorithms/uncategorized/unique-paths)
* `A` [ํด๋ฐํด ๊ฒฝ๋ก](src/algorithms/graph/hamiltonian-cycle) - ๋ชจ๋ ์ ์ ํ๋ฒ์ฉ ๋ฐฉ๋ฌธ
* `A` [N-Queens ๋ฌธ์ ](src/algorithms/uncategorized/n-queens)
* `A` [๊ธฐ์ฌ์ ์ฌํ](src/algorithms/uncategorized/knight-tour)
* `A` [์กฐํฉ ํฉ](src/algorithms/sets/combination-sum) - ํน์ ํฉ์ ๊ตฌ์ฑํ๋ ๋ชจ๋ ์กฐํฉ ์ฐพ๊ธฐ
* **๋ถ๊ธฐ ํ์ ๋ฒ** - ๋ฐฑํธ๋ํน์ผ๋ก ์ฐพ์ ๊ฐ ๋จ๊ณ์ ์ต์ ๋น์ฉ์ด ๋๋ ํด๋ฅผ ๊ธฐ์ตํด ๋๊ณ ์๋ค๊ฐ, ์ด ๋น์ฉ์ ์ด์ฉํด์ ๋ ๋ฎ์ ์ต์ ์ ํด๋ฅผ ์ฐพ์ต๋๋ค. ๊ธฐ์ตํด๋ ์ต์ ๋น์ฉ๋ค์ ์ด์ฉํด ๋ ๋์ ๋น์ฉ์ด ๋๋ ํด๊ฒฐ๋ฒ์ ํ์ ์ํจ์ผ๋ก์จ ๋ถํ์ํ ์๊ฐ ์๋ชจ๋ฅผ ์ค์
๋๋ค. ๋ณดํต ์ํ ๊ณต๊ฐ ํธ๋ฆฌ์ DFS ํ์์ ์ด์ฉํ BFS ํ์ ๋ฐฉ์์์ ์ฌ์ฉ๋ฉ๋๋ค.
## ์ด ์ ์ฅ์์ ์ฌ์ฉ๋ฒ
**๋ชจ๋ ์ข
์ ๋ชจ๋๋ค ์ค์น**
```
npm install
```
**ESLint ์คํ**
์ฝ๋์ ํ์ง์ ํ์ธ ํ ์ ์์ต๋๋ค.
```
npm run lint
```
**๋ชจ๋ ํ
์คํธ ์คํ**
```
npm test
```
**์ด๋ฆ์ ํตํด ํน์ ํ
์คํธ ์คํ**
```
npm test -- 'LinkedList'
```
**Playground**
`./src/playground/playground.js` ํ์ผ์ ํตํด ์๋ฃ ๊ตฌ์กฐ์ ์๊ณ ๋ฆฌ์ฆ์ ์์ฑํ๊ณ `./src/playground/__test__/playground.test.js`์ ํ
์คํธ๋ฅผ ์์ฑํ ์ ์์ต๋๋ค.
๊ทธ๋ฆฌ๊ณ ๊ฐ๋จํ๊ฒ ์๋ ๋ช
๋ น์ด๋ฅผ ํตํด ์๋ํ๋๋ก ๋์ํ๋์ง ํ์ธ ํ ์ ์์ต๋๋ค.:
```
npm test -- 'playground'
```
## ์ ์ฉํ ์ ๋ณด
### ์ฐธ๊ณ
[โถ Data Structures and Algorithms on YouTube](https://www.youtube.com/playlist?list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)
### Big O ํ๊ธฐ
Big O ํ๊ธฐ๋ก ํ์ํ ์๊ณ ๋ฆฌ์ฆ์ ์ฆ๊ฐ ์์์
๋๋ค.

Source: [Big O Cheat Sheet](http://bigocheatsheet.com/).
์๋๋ ๊ฐ์ฅ ๋ง์ด ์ฌ์ฉ๋๋ Big O ํ๊ธฐ์ ์
๋ ฅ ๋ฐ์ดํฐ ํฌ๊ธฐ์ ๋ฐ๋ฅธ ์ฑ๋ฅ์ ๋น๊ตํ ํ์
๋๋ค.
| Big O ํ๊ธฐ | 10 ๊ฐ ์ผ๋ | 100 ๊ฐ ์ผ๋ | 1000 ๊ฐ ์ผ๋ |
| -------------- | ---------------------------- | ----------------------------- | ------------------------------- |
| **O(1)** | 1 | 1 | 1 |
| **O(log N)** | 3 | 6 | 9 |
| **O(N)** | 10 | 100 | 1000 |
| **O(N log N)** | 30 | 600 | 9000 |
| **O(N^2)** | 100 | 10000 | 1000000 |
| **O(2^N)** | 1024 | 1.26e+29 | 1.07e+301 |
| **O(N!)** | 3628800 | 9.3e+157 | 4.02e+2567 |
### ์๋ฃ ๊ตฌ์กฐ ์์
๋ณ ๋ณต์ก๋
| ์๋ฃ ๊ตฌ์กฐ | ์ ๊ทผ | ๊ฒ์ | ์ฝ์
| ์ญ์ | ๋น๊ณ |
| ------------------------ | :-------: | :-------: | :-------: | :-------: | :-------- |
| **๋ฐฐ์ด** | 1 | n | n | n | |
| **์คํ** | n | n | 1 | 1 | |
| **ํ** | n | n | 1 | 1 | |
| **์ฐ๊ฒฐ ๋ฆฌ์คํธ** | n | n | 1 | 1 | |
| **ํด์ ํ
์ด๋ธ** | - | n | n | n | ์๋ฒฝํ ํด์ ํจ์์ ๊ฒฝ์ฐ O(1) |
| **์ด์ง ํ์ ํธ๋ฆฌ** | n | n | n | n | ๊ท ํ ํธ๋ฆฌ์ ๊ฒฝ์ฐ O(log(n)) |
| **B-ํธ๋ฆฌ** | log(n) | log(n) | log(n) | log(n) | |
| **Red-Black ํธ๋ฆฌ** | log(n) | log(n) | log(n) | log(n) | |
| **AVL ํธ๋ฆฌ** | log(n) | log(n) | log(n) | log(n) | |
| **Bloom Filter** | - | 1 | 1 | - | ๊ฑฐ์ง ์์ฑ์ด ํ์ ์ค ๋ฐ์ ๊ฐ๋ฅ |
### ์ ๋ ฌ ์๊ณ ๋ฆฌ์ฆ ๋ณต์ก๋
| ์ด๋ฆ | ์ต์ | ํ๊ท | ์ต์
| ๋ฉ๋ชจ๋ฆฌ | ๋์ผ๊ฐ ์์์ ์ง | ๋น๊ณ |
| --------------------- | :-------------: | :-----------------: | :-----------------: | :-------: | :--------------: | :-------- |
| **๊ฑฐํ ์ ๋ ฌ** | n | n<sup>2</sup> | n<sup>2</sup> | 1 | Yes | |
| **์ฝ์
์ ๋ ฌ** | n | n<sup>2</sup> | n<sup>2</sup> | 1 | Yes | |
| **์ ํ ์ ๋ ฌ** | n<sup>2</sup> | n<sup>2</sup> | n<sup>2</sup> | 1 | No | |
| **ํ ์ ๋ ฌ** | n log(n) | n log(n) | n log(n) | 1 | No | |
| **๋ณํฉ ์ ๋ ฌ** | n log(n) | n log(n) | n log(n) | n | Yes | |
| **ํต ์ ๋ ฌ** | n log(n) | n log(n) | n<sup>2</sup> | log(n) | No | ํต ์ ๋ ฌ์ ๋ณดํต ์ ์๋ฆฌ(in-place)๋ก O(log(n)) ์คํ๊ณต๊ฐ์ผ๋ก ์ํ๋ฉ๋๋ค. |
| **์
ธ ์ ๋ ฌ** | n log(n) | ๊ฐ๊ฒฉ ์์์ ์ํฅ์ ๋ฐ์ต๋๋ค. | n (log(n))<sup>2</sup> | 1 | No | |
| **๊ณ์ ์ ๋ ฌ** | n + r | n + r | n + r | n + r | Yes | r - ๋ฐฐ์ด๋ด ๊ฐ์ฅ ํฐ ์ |
| **๊ธฐ์ ์ ๋ ฌ** | n * k | n * k | n * k | n + k | Yes | k - ํค๊ฐ์ ์ต๋ ๊ธธ์ด |
> โน๏ธ A few more [projects](https://trekhleb.dev/projects/) and [articles](https://trekhleb.dev/blog/) about JavaScript and algorithms on [trekhleb.dev](https://trekhleb.dev)
| javascript-algorithms/README.ko-KR.md/0 | {
"file_path": "javascript-algorithms/README.ko-KR.md",
"repo_id": "javascript-algorithms",
"token_count": 13632
} | 78 |
import { caesarCipherEncrypt, caesarCipherDecrypt } from '../caesarCipher';
describe('caesarCipher', () => {
it('should not change a string with zero shift', () => {
expect(caesarCipherEncrypt('abcd', 0)).toBe('abcd');
expect(caesarCipherDecrypt('abcd', 0)).toBe('abcd');
});
it('should cipher a string with different shifts', () => {
expect(caesarCipherEncrypt('abcde', 3)).toBe('defgh');
expect(caesarCipherDecrypt('defgh', 3)).toBe('abcde');
expect(caesarCipherEncrypt('abcde', 1)).toBe('bcdef');
expect(caesarCipherDecrypt('bcdef', 1)).toBe('abcde');
expect(caesarCipherEncrypt('xyz', 1)).toBe('yza');
expect(caesarCipherDecrypt('yza', 1)).toBe('xyz');
});
it('should be case insensitive', () => {
expect(caesarCipherEncrypt('ABCDE', 3)).toBe('defgh');
});
it('should correctly handle an empty strings', () => {
expect(caesarCipherEncrypt('', 3)).toBe('');
});
it('should not cipher unknown chars', () => {
expect(caesarCipherEncrypt('ab2cde', 3)).toBe('de2fgh');
expect(caesarCipherDecrypt('de2fgh', 3)).toBe('ab2cde');
});
it('should encrypt and decrypt full phrases', () => {
expect(caesarCipherEncrypt('THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG', 23))
.toBe('qeb nrfzh yoltk clu grjmp lsbo qeb ixwv ald');
expect(caesarCipherDecrypt('qeb nrfzh yoltk clu grjmp lsbo qeb ixwv ald', 23))
.toBe('the quick brown fox jumps over the lazy dog');
});
});
| javascript-algorithms/src/algorithms/cryptography/caesar-cipher/__test__/caesarCipher.test.js/0 | {
"file_path": "javascript-algorithms/src/algorithms/cryptography/caesar-cipher/__test__/caesarCipher.test.js",
"repo_id": "javascript-algorithms",
"token_count": 560
} | 79 |
# BellmanโFord Algorithm
The BellmanโFord algorithm is an algorithm that computes shortest
paths from a single source vertex to all of the other vertices
in a weighted digraph. It is slower than Dijkstra's algorithm
for the same problem, but more versatile, as it is capable of
handling graphs in which some of the edge weights are negative
numbers.

## Complexity
Worst-case performance `O(|V||E|)`
Best-case performance `O(|E|)`
Worst-case space complexity `O(|V|)`
## References
- [Wikipedia](https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm)
- [On YouTube by Michael Sambol](https://www.youtube.com/watch?v=obWXjtg0L64&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)
| javascript-algorithms/src/algorithms/graph/bellman-ford/README.md/0 | {
"file_path": "javascript-algorithms/src/algorithms/graph/bellman-ford/README.md",
"repo_id": "javascript-algorithms",
"token_count": 282
} | 80 |
import depthFirstSearch from '../depth-first-search/depthFirstSearch';
/**
* Detect cycle in directed graph using Depth First Search.
*
* @param {Graph} graph
*/
export default function detectDirectedCycle(graph) {
let cycle = null;
// Will store parents (previous vertices) for all visited nodes.
// This will be needed in order to specify what path exactly is a cycle.
const dfsParentMap = {};
// White set (UNVISITED) contains all the vertices that haven't been visited at all.
const whiteSet = {};
// Gray set (VISITING) contains all the vertices that are being visited right now
// (in current path).
const graySet = {};
// Black set (VISITED) contains all the vertices that has been fully visited.
// Meaning that all children of the vertex has been visited.
const blackSet = {};
// If we encounter vertex in gray set it means that we've found a cycle.
// Because when vertex in gray set it means that its neighbors or its neighbors
// neighbors are still being explored.
// Init white set and add all vertices to it.
/** @param {GraphVertex} vertex */
graph.getAllVertices().forEach((vertex) => {
whiteSet[vertex.getKey()] = vertex;
});
// Describe BFS callbacks.
const callbacks = {
enterVertex: ({ currentVertex, previousVertex }) => {
if (graySet[currentVertex.getKey()]) {
// If current vertex already in grey set it means that cycle is detected.
// Let's detect cycle path.
cycle = {};
let currentCycleVertex = currentVertex;
let previousCycleVertex = previousVertex;
while (previousCycleVertex.getKey() !== currentVertex.getKey()) {
cycle[currentCycleVertex.getKey()] = previousCycleVertex;
currentCycleVertex = previousCycleVertex;
previousCycleVertex = dfsParentMap[previousCycleVertex.getKey()];
}
cycle[currentCycleVertex.getKey()] = previousCycleVertex;
} else {
// Otherwise let's add current vertex to gray set and remove it from white set.
graySet[currentVertex.getKey()] = currentVertex;
delete whiteSet[currentVertex.getKey()];
// Update DFS parents list.
dfsParentMap[currentVertex.getKey()] = previousVertex;
}
},
leaveVertex: ({ currentVertex }) => {
// If all node's children has been visited let's remove it from gray set
// and move it to the black set meaning that all its neighbors are visited.
blackSet[currentVertex.getKey()] = currentVertex;
delete graySet[currentVertex.getKey()];
},
allowTraversal: ({ nextVertex }) => {
// If cycle was detected we must forbid all further traversing since it will
// cause infinite traversal loop.
if (cycle) {
return false;
}
// Allow traversal only for the vertices that are not in black set
// since all black set vertices have been already visited.
return !blackSet[nextVertex.getKey()];
},
};
// Start exploring vertices.
while (Object.keys(whiteSet).length) {
// Pick fist vertex to start BFS from.
const firstWhiteKey = Object.keys(whiteSet)[0];
const startVertex = whiteSet[firstWhiteKey];
// Do Depth First Search.
depthFirstSearch(graph, startVertex, callbacks);
}
return cycle;
}
| javascript-algorithms/src/algorithms/graph/detect-cycle/detectDirectedCycle.js/0 | {
"file_path": "javascript-algorithms/src/algorithms/graph/detect-cycle/detectDirectedCycle.js",
"repo_id": "javascript-algorithms",
"token_count": 1108
} | 81 |
# ํฌ๋ฃจ์ค์นผ ์๊ณ ๋ฆฌ์ฆ
ํฌ๋ฃจ์ค์นผ ์๊ณ ๋ฆฌ์ฆ์ ๋ ํธ๋ฆฌ๋ฅผ ์ฐ๊ฒฐํ๋ ์ต์ ๊ฐ์ ๊ฐ์ค์น๋ฅผ ์ฐพ๋ ์ต์ ์ ์ฅ ํธ๋ฆฌ ์๊ณ ๋ฆฌ์ฆ์
๋๋ค.
๊ฐ ๋จ๊ณ์์ ๋น์ฉ์ ๋ํ๋ ์ฐ๊ฒฐ๋ ๊ฐ์ค ๊ทธ๋ํ์ ๋ํ ์ต์ ์ ์ฅ ํธ๋ฆฌ๋ฅผ ์ฐพ๊ธฐ ๋๋ฌธ์ ๊ทธ๋ํ ์ด๋ก ์์์ ๊ทธ๋ฆฌ๋ ์๊ณ ๋ฆฌ์ฆ์
๋๋ค. ์ฆ, ํธ๋ฆฌ์ ๋ชจ๋ ๊ฐ์ ์ ์ด ๊ฐ์ค์น๊ฐ ์ต์ํ๋๋ ๋ชจ๋ ์ ์ ์ ํฌํจํ๋ ํธ๋ฆฌ๋ฅผ ํ์ฑํ๋ ๊ฐ์ ์ ํ์ ์งํฉ์ ์ฐพ์ต๋๋ค. ๊ทธ๋ํ๊ฐ ์ฐ๊ฒฐ๋์ด ์์ง ์์ผ๋ฉด ์ต์ ์ ์ฅ ํฌ๋ ์คํธ(์ฐ๊ฒฐ๋ ๊ฐ ๊ตฌ์ฑ ์์์ ์ต์ ์ ์ฅ ํธ๋ฆฌ)๋ฅผ ์ฐพ์ต๋๋ค.


์ ํด๋ฆฌ๋ ๊ฑฐ๋ฆฌ๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ํ ํฌ๋ฃจ์ค์นผ ์๊ณ ๋ฆฌ์ฆ์ ๋ฐ๋ชจ์
๋๋ค.
## ์ต์ ์ ์ฅ ํธ๋ฆฌ
**์ต์ ์ ์ฅ ํธ๋ฆฌ(MST)** ๋๋ ์ต์ ๊ฐ์ค์น ์ ์ฅ ํธ๋ฆฌ๋ ์ฐ๊ฒฐ๋ ๊ฐ์ ๊ฐ์ค์น ๋ฌด ๋ฐฉํฅ ๊ทธ๋ํ์ ๊ฐ์ ์ ํ์ ์งํฉ์ผ๋ก, ์ฌ์ดํด ์์ด ๊ฐ๋ฅํ ์ต์ ์ด ๊ฐ์ ๊ฐ์ค์น๋ก ๋ชจ๋ ์ ์ ์ ์ฐ๊ฒฐํฉ๋๋ค. ์ฆ, ๊ฐ์ ๊ฐ์ค์น์ ํฉ์ด ๊ฐ๋ฅํ ์์ ์ ์ฅ ํธ๋ฆฌ์
๋๋ค. ๋ณด๋ค ์ผ๋ฐ์ ์ผ๋ก, ๊ฐ์ -๊ฐ์ค์น ๋น๋ฐฉํฅ ๊ทธ๋ํ(๊ผญ ์ฐ๊ฒฐ๋์ง๋ ์์)์๋ ์ฐ๊ฒฐ๋ ๊ตฌ์ฑ ์์์ ๋ํ ์ต์ ์ ์ฅ ํธ๋ฆฌ์ ๊ฒฐํฉ์ธ ์ต์ ์ ์ฅ ํฌ๋ ์คํธ(minimum spanning forest)๊ฐ ์์ต๋๋ค.

ํ๋ฉด ๊ทธ๋ํ์ ํด๋น ์ต์ ์ ์ฅ ํธ๋ฆฌ์
๋๋ค. ๊ฐ ๊ฐ์ ์ ๊ฐ์ค์น๋ก ๋ ์ด๋ธ์ด ์ง์ ๋๋ฉฐ, ์ด ๊ฐ์ ๊ธธ์ด์ ๊ฑฐ์ ๋น๋กํฉ๋๋ค.

์ด ๊ทธ๋ฆผ์ ๊ทธ๋ํ์ ์ต์ ์ ์ฅ ํธ๋ฆฌ๊ฐ ๋ ๊ฐ ์ด์ ์์ ์ ์์์ ๋ณด์ฌ ์ค๋๋ค. ๊ทธ๋ฆผ์์ ๊ทธ๋ํ ์๋์ ๋ ํธ๋ฆฌ๋ ์ฃผ์ด์ง ๊ทธ๋ํ์์ ์ต์ ์ ์ฅ ํธ๋ฆฌ๊ฐ ๋ ์ ์๋ ๋ ๊ฐ์ง ๊ฒฝ์ฐ์
๋๋ค.
## ์ฐธ์กฐ
- [Minimum Spanning Tree on Wikipedia](https://en.wikipedia.org/wiki/Minimum_spanning_tree)
- [Kruskal's Algorithm on Wikipedia](https://en.wikipedia.org/wiki/Kruskal%27s_algorithm)
- [Kruskal's Algorithm on YouTube by Tushar Roy](https://www.youtube.com/watch?v=fAuF0EuZVCk&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)
- [Kruskal's Algorithm on YouTube by Michael Sambol](https://www.youtube.com/watch?v=71UQH7Pr9kU&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)
| javascript-algorithms/src/algorithms/graph/kruskal/README.ko-KR.md/0 | {
"file_path": "javascript-algorithms/src/algorithms/graph/kruskal/README.ko-KR.md",
"repo_id": "javascript-algorithms",
"token_count": 1873
} | 82 |
# Content-aware image resizing in JavaScript

> There is an [interactive version of this post](https://trekhleb.dev/blog/2021/content-aware-image-resizing-in-javascript/) available where you can upload and resize your custom images.
## TL;DR
There are many great articles written about the *Seam Carving algorithm* already, but I couldn't resist the temptation to explore this elegant, powerful, and *yet simple* algorithm on my own, and to write about my personal experience with it. Another point that drew my attention (as a creator of [javascript-algorithms](https://github.com/trekhleb/javascript-algorithms) repo) was the fact that *Dynamic Programming (DP)* approach might be smoothly applied to solve it. And, if you're like me and still on your "learning algorithms" journey, this algorithmic solution may enrich your personal DP arsenal.
So, with this article I want to do three things:
1. Provide you with an interactive **content-aware resizer** so that you could play around with resizing your own images
2. Explain the idea behind the **Seam Carving algorithm**
3. Explain the **dynamic programming approach** to implement the algorithm (we'll be using TypeScript for it)
### Content-aware image resizing
*Content-aware image resizing* might be applied when it comes to changing the image proportions (i.e. reducing the width while keeping the height) and when losing some parts of the image is not desirable. Doing the straightforward image scaling in this case would distort the objects in it. To preserve the proportions of the objects while changing the image proportions we may use the [Seam Carving algorithm](https://perso.crans.org/frenoy/matlab2012/seamcarving.pdf) that was introduced by *Shai Avidan* and *Ariel Shamir*.
The example below shows how the original image width was reduced by 50% using *content-aware resizing* (left image) and *straightforward scaling* (right image). In this particular case, the left image looks more natural since the proportions of the balloons were preserved.

The Seam Carving algorithm's idea is to find the *seam* (continuous sequence of pixels) with the lowest contribution to the image content and then *carve* (remove) it. This process repeats over and over again until we get the required image width or height. In the example below you may see that the hot air balloon pixels contribute more to the content of the image than the sky pixels. Thus, the sky pixels are being removed first.

Finding the seam with the lowest energy is a computationally expensive task (especially for large images). To make the seam search faster the *dynamic programming* approach might be applied (we will go through the implementation details below).
### Objects removal
The importance of each pixel (so-called pixel's energy) is being calculated based on its color (`R`, `G`, `B`, `A`) difference between two neighbor pixels. Now, if we set the pixel energy to some really low level artificially (i.e. by drawing a mask on top of them), the Seam Carving algorithm would perform an **object removal** for us for free.

### JS IMAGE CARVER demo
I've created the [JS IMAGE CARVER](https://trekhleb.dev/js-image-carver/) web-app (and also [open-sourced it on GitHub](https://github.com/trekhleb/js-image-carver)) that you may use to play around with resizing of your custom images.
### More examples
Here are some more examples of how the algorithm copes with more complex backgrounds.
Mountains on the background are being shrunk smoothly without visible seams.

The same goes for the ocean waves. The algorithm preserved the wave structure without distorting the surfers.

We need to keep in mind that the Seam Carving algorithm is not a silver bullet, and it may fail to resize the images where *most of the pixels are edges* (look important to the algorithm). In this case, it starts distorting even the important parts of the image. In the example below the content-aware image resizing looks pretty similar to a straightforward scaling since for the algorithm all the pixels look important, and it is hard for it to distinguish Van Gogh's face from the background.

## How Seam Carving algorithms works
Imagine we have a `1000 x 500 px` picture, and we want to change its size to `500 x 500 px` to make it square (let's say the square ratio would better fit the Instagram feed). We might want to set up several **requirements to the resizing process** in this case:
- *Preserve the important parts of the image* (i.e. if there were 5 trees before the resizing we want to have 5 trees after resizing as well).
- *Preserve the proportions* of the important parts of the image (i.e. circle car wheels should not be squeezed to the ellipse wheels)
To avoid changing the important parts of the image we may find the **continuous sequence of pixels (the seam)**, that goes from top to bottom and has *the lowest contribution to the content* of the image (avoids important parts) and then remove it. The seam removal will shrink the image by 1 pixel. We will then repeat this step until the image will get the desired width.
The question is how to define *the importance of the pixel* and its contribution to the content (in the original paper the authors are using the term **energy of the pixel**). One of the ways to do it is to treat all the pixels that form the edges as important ones. In case if a pixel is a part of the edge its color would have a greater difference between the neighbors (left and right pixels) than the pixel that isn't a part of the edge.

Assuming that the color of a pixel is represented by *4* numbers (`R` - red, `G` - green, `B` - blue, `A` - alpha) we may use the following formula to calculate the color difference (the pixel energy):

Where:
- `mEnergy` - *Energy* (importance) of the *middle* pixel (`[0..626]` if rounded)
- `lR` - *Red* channel value for the *left* pixel (`[0..255]`)
- `mR` - *Red* channel value for the *middle* pixel (`[0..255]`)
- `rR` - *Red* channel value for the *right* pixel (`[0..255]`)
- `lG` - *Green* channel value for the *left* pixel (`[0..255]`)
- and so on...
In the formula above we're omitting the alpha (transparency) channel, for now, assuming that there are no transparent pixels in the image. Later we will use the alpha channel for masking and for object removal.

Now, since we know how to find the energy of one pixel, we can calculate, so-called, **energy map** which will contain the energies of each pixel of the image. On each resizing step the energy map should be re-calculated (at least partially, more about it below) and would have the same size as the image.
For example, on the 1st resizing step we will have a `1000 x 500` image and a `1000 x 500` energy map. On the 2nd resizing step we will remove the seam from the image and re-calculate the energy map based on the new shrunk image. Thus, we will get a `999 x 500` image and a `999 x 500` energy map.
The higher the energy of the pixel the more likely it is a part of an edge, and it is important for the image content and the less likely that we need to remove it.
To visualize the energy map we may assign a brighter color to the pixels with the higher energy and darker colors to the pixels with the lower energy. Here is an artificial example of how the random part of the energy map might look like. You may see the bright line which represents the edge and which we want to preserve during the resizing.

Here is a real example of the energy map for the demo image you saw above (with hot air balloons).

You may play around with your custom images and see how the energy map would look like in the [interactive version of the post](https://trekhleb.dev/blog/2021/content-aware-image-resizing-in-javascript/).
We may use the energy map to find the seams (one after another) with the lowest energy and by doing this to decide which pixels should be ultimately deleted.

Finding the seam with the lowest energy is not a trivial task and requires exploring many possible pixel combinations before making the decision. We will apply the dynamic programming approach to speed it up.
In the example below, you may see the energy map with the first lowest energy seam that was found for it.

In the examples above we were reducing the width of the image. A similar approach may be taken to reduce the image height. We need to "rotate" the approach though:
- start using *top* and *bottom* pixel neighbors (instead of *left* and *right* ones) to calculate the pixel energy
- when searching for a seam we need to move from *left* to *right* (instead of from *up* to *bottom*)
## Implementation in TypeScript
> You may find the source code, and the functions mentioned below in the [js-image-carver](https://github.com/trekhleb/js-image-carver) repository.
To implement the algorithm we will be using TypeScript. If you want a JavaScript version, you may ignore (remove) type definitions and their usages.
For simplicity reasons let's implement the seam carving algorithm only for the image *width* reduction.
### Content-aware width resizing (the entry function)
First, let's define some common types that we're going to use while implementing the algorithm.
```typescript
// Type that describes the image size (width and height).
type ImageSize = { w: number, h: number };
// The coordinate of the pixel.
type Coordinate = { x: number, y: number };
// The seam is a sequence of pixels (coordinates).
type Seam = Coordinate[];
// Energy map is a 2D array that has the same width and height
// as the image the map is being calculated for.
type EnergyMap = number[][];
// Type that describes the image pixel's RGBA color.
type Color = [
r: number, // Red
g: number, // Green
b: number, // Blue
a: number, // Alpha (transparency)
] | Uint8ClampedArray;
```
On the high level the algorithm consists of the following steps:
1. Calculate the **energy map** for the current version of the image.
2. Find the **seam** with the lowest energy based on the energy map (this is where we will apply Dynamic Programming).
3. **Delete the seam** with the lowest energy seam from the image.
4. **Repeat** until the image width is reduced to the desired value.
```typescript
type ResizeImageWidthArgs = {
img: ImageData, // Image data we want to resize.
toWidth: number, // Final image width we want the image to shrink to.
};
type ResizeImageWidthResult = {
img: ImageData, // Resized image data.
size: ImageSize, // Resized image size (w x h).
};
// Performs the content-aware image width resizing using the seam carving method.
export const resizeImageWidth = (
{ img, toWidth }: ResizeImageWidthArgs,
): ResizeImageWidthResult => {
// For performance reasons we want to avoid changing the img data array size.
// Instead we'll just keep the record of the resized image width and height separately.
const size: ImageSize = { w: img.width, h: img.height };
// Calculating the number of pixels to remove.
const pxToRemove = img.width - toWidth;
if (pxToRemove < 0) {
throw new Error('Upsizing is not supported for now');
}
let energyMap: EnergyMap | null = null;
let seam: Seam | null = null;
// Removing the lowest energy seams one by one.
for (let i = 0; i < pxToRemove; i += 1) {
// 1. Calculate the energy map for the current version of the image.
energyMap = calculateEnergyMap(img, size);
// 2. Find the seam with the lowest energy based on the energy map.
seam = findLowEnergySeam(energyMap, size);
// 3. Delete the seam with the lowest energy seam from the image.
deleteSeam(img, seam, size);
// Reduce the image width, and continue iterations.
size.w -= 1;
}
// Returning the resized image and its final size.
// The img is actually a reference to the ImageData, so technically
// the caller of the function already has this pointer. But let's
// still return it for better code readability.
return { img, size };
};
```
The image that needs to be resized is being passed to the function in [ImageData](https://developer.mozilla.org/en-US/docs/Web/API/ImageData) format. You may draw the image on the canvas and then extract the ImageData from the canvas like this:
```javascript
const ctx = canvas.getContext('2d');
const imgData = ctx.getImageData(0, 0, imgWidth, imgHeight);
```
> The way of uploading and drawing images in JavaScript is out of scope for this article, but you may find the complete source code of how it may be done using React in [js-image-carver](https://github.com/trekhleb/js-image-carver) repo.
Let's break down each step ony be one and implement the `calculateEnergyMap()`, `findLowEnergySeam()` and `deleteSeam()` functions.
### Calculating the pixel's energy
Here we apply the color difference formula described above. For the left and right borders (when there are no left or right neighbors), we ignore the neighbors and don't take them into account during the energy calculation.
```typescript
// Calculates the energy of a pixel.
const getPixelEnergy = (left: Color | null, middle: Color, right: Color | null): number => {
// Middle pixel is the pixel we're calculating the energy for.
const [mR, mG, mB] = middle;
// Energy from the left pixel (if it exists).
let lEnergy = 0;
if (left) {
const [lR, lG, lB] = left;
lEnergy = (lR - mR) ** 2 + (lG - mG) ** 2 + (lB - mB) ** 2;
}
// Energy from the right pixel (if it exists).
let rEnergy = 0;
if (right) {
const [rR, rG, rB] = right;
rEnergy = (rR - mR) ** 2 + (rG - mG) ** 2 + (rB - mB) ** 2;
}
// Resulting pixel energy.
return Math.sqrt(lEnergy + rEnergy);
};
```
### Calculating the energy map
The image we're working with has the [ImageData](https://developer.mozilla.org/en-US/docs/Web/API/ImageData) format. It means that all the pixels (and their colors) are stored in a flat (*1D*) [Uint8ClampedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) array. For readability purposes let's introduce the couple of helper functions that will allow us to work with the Uint8ClampedArray array as with a *2D* matrix instead.
```typescript
// Helper function that returns the color of the pixel.
const getPixel = (img: ImageData, { x, y }: Coordinate): Color => {
// The ImageData data array is a flat 1D array.
// Thus we need to convert x and y coordinates to the linear index.
const i = y * img.width + x;
const cellsPerColor = 4; // RGBA
// For better efficiency, instead of creating a new sub-array we return
// a pointer to the part of the ImageData array.
return img.data.subarray(i * cellsPerColor, i * cellsPerColor + cellsPerColor);
};
// Helper function that sets the color of the pixel.
const setPixel = (img: ImageData, { x, y }: Coordinate, color: Color): void => {
// The ImageData data array is a flat 1D array.
// Thus we need to convert x and y coordinates to the linear index.
const i = y * img.width + x;
const cellsPerColor = 4; // RGBA
img.data.set(color, i * cellsPerColor);
};
```
To calculate the energy map we go through each image pixel and call the previously described `getPixelEnergy()` function against it.
```typescript
// Helper function that creates a matrix (2D array) of specific
// size (w x h) and fills it with specified value.
const matrix = <T>(w: number, h: number, filler: T): T[][] => {
return new Array(h)
.fill(null)
.map(() => {
return new Array(w).fill(filler);
});
};
// Calculates the energy of each pixel of the image.
const calculateEnergyMap = (img: ImageData, { w, h }: ImageSize): EnergyMap => {
// Create an empty energy map where each pixel has infinitely high energy.
// We will update the energy of each pixel.
const energyMap: number[][] = matrix<number>(w, h, Infinity);
for (let y = 0; y < h; y += 1) {
for (let x = 0; x < w; x += 1) {
// Left pixel might not exist if we're on the very left edge of the image.
const left = (x - 1) >= 0 ? getPixel(img, { x: x - 1, y }) : null;
// The color of the middle pixel that we're calculating the energy for.
const middle = getPixel(img, { x, y });
// Right pixel might not exist if we're on the very right edge of the image.
const right = (x + 1) < w ? getPixel(img, { x: x + 1, y }) : null;
energyMap[y][x] = getPixelEnergy(left, middle, right);
}
}
return energyMap;
};
```
> The energy map is going to be recalculated on every resize iteration. It means that it will be recalculated, let's say, 500 times if we need to shrink the image by 500 pixels which is not optimal. To speed up the energy map calculation on the 2nd, 3rd, and further steps, we may re-calculate the energy only for those pixels that are placed around the seam that is going to be removed. For simplicity reasons this optimization is omitted here, but you may find the example source-code in [js-image-carver](https://github.com/trekhleb/js-image-carver) repo.
### Finding the seam with the lowest energy (Dynamic Programming approach)
> I've described some Dynamic Programming basics in [Dynamic Programming vs Divide-and-Conquer](https://trekhleb.dev/blog/2018/dynamic-programming-vs-divide-and-conquer/) article before. There is a DP example based on the minimum edit distance problem. You might want to check it out to get some more context.
The issue we need to solve now is to find the path (the seam) on the energy map that goes from top to bottom and has the minimum sum of pixel energies.
#### The naive approach
The naive approach would be to check all possible paths one after another.

Going from top to bottom, for each pixel, we have 3 options (โ๏ธ go down-left, โ go down, โ๏ธ go down-right). This gives us the time complexity of `O(w * 3^h)` or simply `O(3^h)`, where `w` and `h` are the width and the height of the image. This approach looks slow.
#### The greedy approach
We may also try to choose the next pixel as a pixel with the lowest energy, hoping that the resulting seam energy will be the smallest one.

This approach gives not the worst solution, but it cannot guarantee that we will find the best available solution. On the image above you may see how the greedy approach chose `5` instead of `10` at first and missed the chain of optimal pixels.
The good part about this approach is that it is fast, and it has a time complexity of `O(w + h)`, where `w` and `h` are the width and the height of the image. In this case, the cost of the speed is the low quality of resizing. We need to find a minimum value in the first row (traversing `w` cells) and then we explore only 3 neighbor pixels for each row (traversing `h` rows).
#### The dynamic programming approach
You might have noticed that in the naive approach we summed up the same pixel energies over and over again while calculating the resulting seams' energy.

In the example above you see that for the first two seams we are re-using the energy of the shorter seam (which has the energy of `235`). Instead of doing just one operation `235 + 70` to calculate the energy of the 2nd seam we're doing four operations `(5 + 0 + 80 + 150) + 70`.
> This fact that we're re-using the energy of the previous seam to calculate the current seam's energy might be applied recursively to all the shorter seams up to the very top 1st row seam. When we have such overlapping sub-problems, [it is a sign](https://trekhleb.dev/blog/2018/dynamic-programming-vs-divide-and-conquer/) that the general problem *might* be optimized by dynamic programming approach.
So, we may **save the energy of the current seam** at the particular pixel in an additional `seamsEnergies` table to make it re-usable for calculating the next seams faster (the `seamsEnergies` table will have the same size as the energy map and the image itself).
Let's also keep in mind that for one particular pixel on the image (i.e. the bottom left one) we may have *several* values of the previous seams energies.

Since we're looking for a seam with the lowest resulting energy it would make sense to pick the previous seam with the lowest resulting energy as well.

In general, we have three possible previous seems to choose from:

You may think about it this way:
- The cell `[1][x]`: contains the lowest possible energy of the seam that starts somewhere on the row `[0][?]` and ends up at cell `[1][x]`
- **The current cell** `[2][3]`: contains the lowest possible energy of the seam that starts somewhere on the row `[0][?]` and ends up at cell `[2][3]`. To calculate it we need to sum up the energy of the current pixel `[2][3]` (from the energy map) with the `min(seam_energy_1_2, seam_energy_1_3, seam_energy_1_4)`
If we fill the `seamsEnergies` table completely, then the minimum number in the lowest row would be the lowest possible seam energy.
Let's try to fill several cells of this table to see how it works.

After filling out the `seamsEnergies` table we may see that the lowest energy pixel has an energy of `50`. For convenience, during the `seamsEnergies` generation for each pixel, we may save not only the energy of the seam but also the coordinates of the previous lowest energy seam. This will give us the possibility to reconstruct the seam path from the bottom to the top easily.
The time complexity of DP approach would be `O(w * h)`, where `w` and `h` are the width and the height of the image. We need to calculate energies for *every* pixel of the image.
Here is an example of how this logic might be implemented:
```typescript
// The metadata for the pixels in the seam.
type SeamPixelMeta = {
energy: number, // The energy of the pixel.
coordinate: Coordinate, // The coordinate of the pixel.
previous: Coordinate | null, // The previous pixel in a seam.
};
// Finds the seam (the sequence of pixels from top to bottom) that has the
// lowest resulting energy using the Dynamic Programming approach.
const findLowEnergySeam = (energyMap: EnergyMap, { w, h }: ImageSize): Seam => {
// The 2D array of the size of w and h, where each pixel contains the
// seam metadata (pixel energy, pixel coordinate and previous pixel from
// the lowest energy seam at this point).
const seamsEnergies: (SeamPixelMeta | null)[][] = matrix<SeamPixelMeta | null>(w, h, null);
// Populate the first row of the map by just copying the energies
// from the energy map.
for (let x = 0; x < w; x += 1) {
const y = 0;
seamsEnergies[y][x] = {
energy: energyMap[y][x],
coordinate: { x, y },
previous: null,
};
}
// Populate the rest of the rows.
for (let y = 1; y < h; y += 1) {
for (let x = 0; x < w; x += 1) {
// Find the top adjacent cell with minimum energy.
// This cell would be the tail of a seam with lowest energy at this point.
// It doesn't mean that this seam (path) has lowest energy globally.
// Instead, it means that we found a path with the lowest energy that may lead
// us to the current pixel with the coordinates x and y.
let minPrevEnergy = Infinity;
let minPrevX: number = x;
for (let i = (x - 1); i <= (x + 1); i += 1) {
if (i >= 0 && i < w && seamsEnergies[y - 1][i].energy < minPrevEnergy) {
minPrevEnergy = seamsEnergies[y - 1][i].energy;
minPrevX = i;
}
}
// Update the current cell.
seamsEnergies[y][x] = {
energy: minPrevEnergy + energyMap[y][x],
coordinate: { x, y },
previous: { x: minPrevX, y: y - 1 },
};
}
}
// Find where the minimum energy seam ends.
// We need to find the tail of the lowest energy seam to start
// traversing it from its tail to its head (from the bottom to the top).
let lastMinCoordinate: Coordinate | null = null;
let minSeamEnergy = Infinity;
for (let x = 0; x < w; x += 1) {
const y = h - 1;
if (seamsEnergies[y][x].energy < minSeamEnergy) {
minSeamEnergy = seamsEnergies[y][x].energy;
lastMinCoordinate = { x, y };
}
}
// Find the lowest energy energy seam.
// Once we know where the tail is we may traverse and assemble the lowest
// energy seam based on the "previous" value of the seam pixel metadata.
const seam: Seam = [];
if (!lastMinCoordinate) {
return seam;
}
const { x: lastMinX, y: lastMinY } = lastMinCoordinate;
// Adding new pixel to the seam path one by one until we reach the top.
let currentSeam = seamsEnergies[lastMinY][lastMinX];
while (currentSeam) {
seam.push(currentSeam.coordinate);
const prevMinCoordinates = currentSeam.previous;
if (!prevMinCoordinates) {
currentSeam = null;
} else {
const { x: prevMinX, y: prevMinY } = prevMinCoordinates;
currentSeam = seamsEnergies[prevMinY][prevMinX];
}
}
return seam;
};
```
### Removing the seam with the lowest energy
Once we found the lowest energy seam, we need to remove (to carve) the pixels that form it from the image. The removal is happening by shifting the pixels to the right of the seam by `1px` to the left. For performance reasons, we don't actually delete the last columns. Instead, the rendering component will just ignore the part of the image that lays beyond the resized image width.

```typescript
// Deletes the seam from the image data.
// We delete the pixel in each row and then shift the rest of the row pixels to the left.
const deleteSeam = (img: ImageData, seam: Seam, { w }: ImageSize): void => {
seam.forEach(({ x: seamX, y: seamY }: Coordinate) => {
for (let x = seamX; x < (w - 1); x += 1) {
const nextPixel = getPixel(img, { x: x + 1, y: seamY });
setPixel(img, { x, y: seamY }, nextPixel);
}
});
};
```
## Objects removal
The Seam Carving algorithm tries to remove the seams which consist of low energy pixels first. We could leverage this fact and by assigning low energy to some pixels manually (i.e. by drawing on the image and masking out some areas of it) we could make the Seam Carving algorithm to do *objects removal* for us for free.
Currently, in `getPixelEnergy()` function we were using only the `R`, `G`, `B` color channels to calculate the pixel's energy. But there is also the `A` (alpha, transparency) parameter of the color that we didn't use yet. We may use the transparency channel to tell the algorithm that transparent pixels are the pixels we want to remove. You may check the [source-code of the energy function](https://github.com/trekhleb/js-image-carver/blob/main/src/utils/contentAwareResizer.ts#L54) that takes transparency into account.
Here is how the algorithm works for object removal.

## Issues and what's next
The [JS IMAGE CARVER](https://github.com/trekhleb/js-image-carver) web app is far from being a production ready resizer of course. Its main purpose was to experiment with the Seam Carving algorithm interactively. So the plan for the future is to continue experimentation.
The [original paper](https://perso.crans.org/frenoy/matlab2012/seamcarving.pdf) describes how the Seam Carving algorithm might be used not only for the downscaling but also for the **upscaling of the images**. The upscaling, in turn, might be used to **upscale the image back to its original width after the objects' removal**.
Another interesting area of experimentation might be to make the algorithm work in a **real-time**.
> Those are the plans for the future, but for now, I hope that the example with image downsizing was interesting and useful for you. I also hope that you've got the idea of using dynamic programming to implement it.
>
> So, good luck with your own experiments!
| javascript-algorithms/src/algorithms/image-processing/seam-carving/README.md/0 | {
"file_path": "javascript-algorithms/src/algorithms/image-processing/seam-carving/README.md",
"repo_id": "javascript-algorithms",
"token_count": 9280
} | 83 |
import LinkedList from '../../../../data-structures/linked-list/LinkedList';
import traversal from '../traversal';
describe('traversal', () => {
it('should traverse linked list', () => {
const linkedList = new LinkedList();
linkedList
.append(1)
.append(2)
.append(3);
const traversedNodeValues = [];
const traversalCallback = (nodeValue) => {
traversedNodeValues.push(nodeValue);
};
traversal(linkedList, traversalCallback);
expect(traversedNodeValues).toEqual([1, 2, 3]);
});
});
| javascript-algorithms/src/algorithms/linked-list/traversal/__test__/traversal.test.js/0 | {
"file_path": "javascript-algorithms/src/algorithms/linked-list/traversal/__test__/traversal.test.js",
"repo_id": "javascript-algorithms",
"token_count": 199
} | 84 |
import countSetBits from '../countSetBits';
describe('countSetBits', () => {
it('should return number of set bits', () => {
expect(countSetBits(0)).toBe(0);
expect(countSetBits(1)).toBe(1);
expect(countSetBits(2)).toBe(1);
expect(countSetBits(3)).toBe(2);
expect(countSetBits(4)).toBe(1);
expect(countSetBits(5)).toBe(2);
expect(countSetBits(21)).toBe(3);
expect(countSetBits(255)).toBe(8);
expect(countSetBits(1023)).toBe(10);
expect(countSetBits(-1)).toBe(32);
expect(countSetBits(-21)).toBe(30);
expect(countSetBits(-255)).toBe(25);
expect(countSetBits(-1023)).toBe(23);
expect(countSetBits(-4294967296)).toBe(0);
});
});
| javascript-algorithms/src/algorithms/math/bits/__test__/countSetBits.test.js/0 | {
"file_path": "javascript-algorithms/src/algorithms/math/bits/__test__/countSetBits.test.js",
"repo_id": "javascript-algorithms",
"token_count": 303
} | 85 |
/**
* @param {number} originalNumber
* @return {number}
*/
export default function countSetBits(originalNumber) {
let setBitsCount = 0;
let number = originalNumber;
while (number) {
// Add last bit of the number to the sum of set bits.
setBitsCount += number & 1;
// Shift number right by one bit to investigate other bits.
number >>>= 1;
}
return setBitsCount;
}
| javascript-algorithms/src/algorithms/math/bits/countSetBits.js/0 | {
"file_path": "javascript-algorithms/src/algorithms/math/bits/countSetBits.js",
"repo_id": "javascript-algorithms",
"token_count": 127
} | 86 |
import ComplexNumber from '../ComplexNumber';
describe('ComplexNumber', () => {
it('should create complex numbers', () => {
const complexNumber = new ComplexNumber({ re: 1, im: 2 });
expect(complexNumber).toBeDefined();
expect(complexNumber.re).toBe(1);
expect(complexNumber.im).toBe(2);
const defaultComplexNumber = new ComplexNumber();
expect(defaultComplexNumber.re).toBe(0);
expect(defaultComplexNumber.im).toBe(0);
});
it('should add complex numbers', () => {
const complexNumber1 = new ComplexNumber({ re: 1, im: 2 });
const complexNumber2 = new ComplexNumber({ re: 3, im: 8 });
const complexNumber3 = complexNumber1.add(complexNumber2);
const complexNumber4 = complexNumber2.add(complexNumber1);
expect(complexNumber3.re).toBe(1 + 3);
expect(complexNumber3.im).toBe(2 + 8);
expect(complexNumber4.re).toBe(1 + 3);
expect(complexNumber4.im).toBe(2 + 8);
});
it('should add complex and natural numbers', () => {
const complexNumber = new ComplexNumber({ re: 1, im: 2 });
const realNumber = new ComplexNumber({ re: 3 });
const complexNumber3 = complexNumber.add(realNumber);
const complexNumber4 = realNumber.add(complexNumber);
const complexNumber5 = complexNumber.add(3);
expect(complexNumber3.re).toBe(1 + 3);
expect(complexNumber3.im).toBe(2);
expect(complexNumber4.re).toBe(1 + 3);
expect(complexNumber4.im).toBe(2);
expect(complexNumber5.re).toBe(1 + 3);
expect(complexNumber5.im).toBe(2);
});
it('should subtract complex numbers', () => {
const complexNumber1 = new ComplexNumber({ re: 1, im: 2 });
const complexNumber2 = new ComplexNumber({ re: 3, im: 8 });
const complexNumber3 = complexNumber1.subtract(complexNumber2);
const complexNumber4 = complexNumber2.subtract(complexNumber1);
expect(complexNumber3.re).toBe(1 - 3);
expect(complexNumber3.im).toBe(2 - 8);
expect(complexNumber4.re).toBe(3 - 1);
expect(complexNumber4.im).toBe(8 - 2);
});
it('should subtract complex and natural numbers', () => {
const complexNumber = new ComplexNumber({ re: 1, im: 2 });
const realNumber = new ComplexNumber({ re: 3 });
const complexNumber3 = complexNumber.subtract(realNumber);
const complexNumber4 = realNumber.subtract(complexNumber);
const complexNumber5 = complexNumber.subtract(3);
expect(complexNumber3.re).toBe(1 - 3);
expect(complexNumber3.im).toBe(2);
expect(complexNumber4.re).toBe(3 - 1);
expect(complexNumber4.im).toBe(-2);
expect(complexNumber5.re).toBe(1 - 3);
expect(complexNumber5.im).toBe(2);
});
it('should multiply complex numbers', () => {
const complexNumber1 = new ComplexNumber({ re: 3, im: 2 });
const complexNumber2 = new ComplexNumber({ re: 1, im: 7 });
const complexNumber3 = complexNumber1.multiply(complexNumber2);
const complexNumber4 = complexNumber2.multiply(complexNumber1);
const complexNumber5 = complexNumber1.multiply(5);
expect(complexNumber3.re).toBe(-11);
expect(complexNumber3.im).toBe(23);
expect(complexNumber4.re).toBe(-11);
expect(complexNumber4.im).toBe(23);
expect(complexNumber5.re).toBe(15);
expect(complexNumber5.im).toBe(10);
});
it('should multiply complex numbers by themselves', () => {
const complexNumber = new ComplexNumber({ re: 1, im: 1 });
const result = complexNumber.multiply(complexNumber);
expect(result.re).toBe(0);
expect(result.im).toBe(2);
});
it('should calculate i in power of two', () => {
const complexNumber = new ComplexNumber({ re: 0, im: 1 });
const result = complexNumber.multiply(complexNumber);
expect(result.re).toBe(-1);
expect(result.im).toBe(0);
});
it('should divide complex numbers', () => {
const complexNumber1 = new ComplexNumber({ re: 2, im: 3 });
const complexNumber2 = new ComplexNumber({ re: 4, im: -5 });
const complexNumber3 = complexNumber1.divide(complexNumber2);
const complexNumber4 = complexNumber1.divide(2);
expect(complexNumber3.re).toBe(-7 / 41);
expect(complexNumber3.im).toBe(22 / 41);
expect(complexNumber4.re).toBe(1);
expect(complexNumber4.im).toBe(1.5);
});
it('should return complex number in polar form', () => {
const complexNumber1 = new ComplexNumber({ re: 3, im: 3 });
expect(complexNumber1.getPolarForm().radius).toBe(Math.sqrt((3 ** 2) + (3 ** 2)));
expect(complexNumber1.getPolarForm().phase).toBe(Math.PI / 4);
expect(complexNumber1.getPolarForm(false).phase).toBe(45);
const complexNumber2 = new ComplexNumber({ re: -3, im: 3 });
expect(complexNumber2.getPolarForm().radius).toBe(Math.sqrt((3 ** 2) + (3 ** 2)));
expect(complexNumber2.getPolarForm().phase).toBe(3 * (Math.PI / 4));
expect(complexNumber2.getPolarForm(false).phase).toBe(135);
const complexNumber3 = new ComplexNumber({ re: -3, im: -3 });
expect(complexNumber3.getPolarForm().radius).toBe(Math.sqrt((3 ** 2) + (3 ** 2)));
expect(complexNumber3.getPolarForm().phase).toBe(-3 * (Math.PI / 4));
expect(complexNumber3.getPolarForm(false).phase).toBe(-135);
const complexNumber4 = new ComplexNumber({ re: 3, im: -3 });
expect(complexNumber4.getPolarForm().radius).toBe(Math.sqrt((3 ** 2) + (3 ** 2)));
expect(complexNumber4.getPolarForm().phase).toBe(-1 * (Math.PI / 4));
expect(complexNumber4.getPolarForm(false).phase).toBe(-45);
const complexNumber5 = new ComplexNumber({ re: 5, im: 7 });
expect(complexNumber5.getPolarForm().radius).toBeCloseTo(8.60);
expect(complexNumber5.getPolarForm().phase).toBeCloseTo(0.95);
expect(complexNumber5.getPolarForm(false).phase).toBeCloseTo(54.46);
const complexNumber6 = new ComplexNumber({ re: 0, im: 0.25 });
expect(complexNumber6.getPolarForm().radius).toBeCloseTo(0.25);
expect(complexNumber6.getPolarForm().phase).toBeCloseTo(1.57);
expect(complexNumber6.getPolarForm(false).phase).toBeCloseTo(90);
const complexNumber7 = new ComplexNumber({ re: 0, im: -0.25 });
expect(complexNumber7.getPolarForm().radius).toBeCloseTo(0.25);
expect(complexNumber7.getPolarForm().phase).toBeCloseTo(-1.57);
expect(complexNumber7.getPolarForm(false).phase).toBeCloseTo(-90);
const complexNumber8 = new ComplexNumber();
expect(complexNumber8.getPolarForm().radius).toBeCloseTo(0);
expect(complexNumber8.getPolarForm().phase).toBeCloseTo(0);
expect(complexNumber8.getPolarForm(false).phase).toBeCloseTo(0);
const complexNumber9 = new ComplexNumber({ re: -0.25, im: 0 });
expect(complexNumber9.getPolarForm().radius).toBeCloseTo(0.25);
expect(complexNumber9.getPolarForm().phase).toBeCloseTo(Math.PI);
expect(complexNumber9.getPolarForm(false).phase).toBeCloseTo(180);
const complexNumber10 = new ComplexNumber({ re: 0.25, im: 0 });
expect(complexNumber10.getPolarForm().radius).toBeCloseTo(0.25);
expect(complexNumber10.getPolarForm().phase).toBeCloseTo(0);
expect(complexNumber10.getPolarForm(false).phase).toBeCloseTo(0);
});
});
| javascript-algorithms/src/algorithms/math/complex-number/__test__/ComplexNumber.test.js/0 | {
"file_path": "javascript-algorithms/src/algorithms/math/complex-number/__test__/ComplexNumber.test.js",
"repo_id": "javascript-algorithms",
"token_count": 2540
} | 87 |
import factorial from '../factorial';
describe('factorial', () => {
it('should calculate factorial', () => {
expect(factorial(0)).toBe(1);
expect(factorial(1)).toBe(1);
expect(factorial(5)).toBe(120);
expect(factorial(8)).toBe(40320);
expect(factorial(10)).toBe(3628800);
});
});
| javascript-algorithms/src/algorithms/math/factorial/__test__/factorial.test.js/0 | {
"file_path": "javascript-algorithms/src/algorithms/math/factorial/__test__/factorial.test.js",
"repo_id": "javascript-algorithms",
"token_count": 121
} | 88 |
/**
* Calculate fibonacci number at specific position using Dynamic Programming approach.
*
* @param n
* @return {number}
*/
export default function fibonacciNth(n) {
let currentValue = 1;
let previousValue = 0;
if (n === 1) {
return 1;
}
let iterationsCounter = n - 1;
while (iterationsCounter) {
currentValue += previousValue;
previousValue = currentValue - previousValue;
iterationsCounter -= 1;
}
return currentValue;
}
| javascript-algorithms/src/algorithms/math/fibonacci/fibonacciNth.js/0 | {
"file_path": "javascript-algorithms/src/algorithms/math/fibonacci/fibonacciNth.js",
"repo_id": "javascript-algorithms",
"token_count": 144
} | 89 |
# Integer Partition
In number theory and combinatorics, a partition of a positive
integer `n`, also called an **integer partition**, is a way of
writing `n` as a sum of positive integers.
Two sums that differ only in the order of their summands are
considered the same partition. For example, `4` can be partitioned
in five distinct ways:
```
4
3 + 1
2 + 2
2 + 1 + 1
1 + 1 + 1 + 1
```
The order-dependent composition `1 + 3` is the same partition
as `3 + 1`, while the two distinct
compositions `1 + 2 + 1` and `1 + 1 + 2` represent the same
partition `2 + 1 + 1`.
Young diagrams associated to the partitions of the positive
integers `1` through `8`. They are arranged so that images
under the reflection about the main diagonal of the square
are conjugate partitions.

## References
- [Wikipedia](https://en.wikipedia.org/wiki/Partition_(number_theory))
- [YouTube](https://www.youtube.com/watch?v=ZaVM057DuzE&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)
| javascript-algorithms/src/algorithms/math/integer-partition/README.md/0 | {
"file_path": "javascript-algorithms/src/algorithms/math/integer-partition/README.md",
"repo_id": "javascript-algorithms",
"token_count": 355
} | 90 |
import * as mtrx from '../Matrix';
describe('Matrix', () => {
it('should throw when trying to add matrices of invalid shapes', () => {
expect(
() => mtrx.dot([0], [1]),
).toThrowError('Invalid matrix format');
expect(
() => mtrx.dot([[0]], [1]),
).toThrowError('Invalid matrix format');
expect(
() => mtrx.dot([[[0]]], [[1]]),
).toThrowError('Matrix is not of 2D shape');
expect(
() => mtrx.dot([[0]], [[1], [2]]),
).toThrowError('Matrices have incompatible shape for multiplication');
});
it('should calculate matrices dimensions', () => {
expect(mtrx.shape([])).toEqual([0]);
expect(mtrx.shape([
[],
])).toEqual([1, 0]);
expect(mtrx.shape([
[0],
])).toEqual([1, 1]);
expect(mtrx.shape([
[0, 0],
])).toEqual([1, 2]);
expect(mtrx.shape([
[0, 0],
[0, 0],
])).toEqual([2, 2]);
expect(mtrx.shape([
[0, 0, 0],
[0, 0, 0],
])).toEqual([2, 3]);
expect(mtrx.shape([
[0, 0],
[0, 0],
[0, 0],
])).toEqual([3, 2]);
expect(mtrx.shape([
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
])).toEqual([3, 3]);
expect(mtrx.shape([
[0],
[0],
[0],
])).toEqual([3, 1]);
expect(mtrx.shape([
[[0], [0], [0]],
[[0], [0], [0]],
[[0], [0], [0]],
])).toEqual([3, 3, 1]);
expect(mtrx.shape([
[[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]],
])).toEqual([3, 3, 3]);
});
it('should generate the matrix of zeros', () => {
expect(mtrx.zeros([1, 0])).toEqual([
[],
]);
expect(mtrx.zeros([1, 1])).toEqual([
[0],
]);
expect(mtrx.zeros([1, 3])).toEqual([
[0, 0, 0],
]);
expect(mtrx.zeros([3, 3])).toEqual([
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
]);
expect(mtrx.zeros([3, 3, 1])).toEqual([
[[0], [0], [0]],
[[0], [0], [0]],
[[0], [0], [0]],
]);
});
it('should generate the matrix with custom values', () => {
expect(mtrx.generate([1, 0], () => 1)).toEqual([
[],
]);
expect(mtrx.generate([1, 1], () => 1)).toEqual([
[1],
]);
expect(mtrx.generate([1, 3], () => 1)).toEqual([
[1, 1, 1],
]);
expect(mtrx.generate([3, 3], () => 1)).toEqual([
[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
]);
expect(mtrx.generate([3, 3, 1], () => 1)).toEqual([
[[1], [1], [1]],
[[1], [1], [1]],
[[1], [1], [1]],
]);
});
it('should generate a custom matrix based on specific cell indices', () => {
const indicesCallback = jest.fn((indices) => {
return indices[0] * 10 + indices[1];
});
const m = mtrx.generate([3, 3], indicesCallback);
expect(indicesCallback).toHaveBeenCalledTimes(3 * 3);
expect(indicesCallback.mock.calls[0][0]).toEqual([0, 0]);
expect(indicesCallback.mock.calls[1][0]).toEqual([0, 1]);
expect(indicesCallback.mock.calls[2][0]).toEqual([0, 2]);
expect(indicesCallback.mock.calls[3][0]).toEqual([1, 0]);
expect(indicesCallback.mock.calls[4][0]).toEqual([1, 1]);
expect(indicesCallback.mock.calls[5][0]).toEqual([1, 2]);
expect(indicesCallback.mock.calls[6][0]).toEqual([2, 0]);
expect(indicesCallback.mock.calls[7][0]).toEqual([2, 1]);
expect(indicesCallback.mock.calls[8][0]).toEqual([2, 2]);
expect(m).toEqual([
[0, 1, 2],
[10, 11, 12],
[20, 21, 22],
]);
});
it('should multiply two matrices', () => {
let c;
c = mtrx.dot(
[
[1, 2],
[3, 4],
],
[
[5, 6],
[7, 8],
],
);
expect(mtrx.shape(c)).toEqual([2, 2]);
expect(c).toEqual([
[19, 22],
[43, 50],
]);
c = mtrx.dot(
[
[1, 2],
[3, 4],
],
[
[5],
[6],
],
);
expect(mtrx.shape(c)).toEqual([2, 1]);
expect(c).toEqual([
[17],
[39],
]);
c = mtrx.dot(
[
[1, 2, 3],
[4, 5, 6],
],
[
[7, 8],
[9, 10],
[11, 12],
],
);
expect(mtrx.shape(c)).toEqual([2, 2]);
expect(c).toEqual([
[58, 64],
[139, 154],
]);
c = mtrx.dot(
[
[3, 4, 2],
],
[
[13, 9, 7, 5],
[8, 7, 4, 6],
[6, 4, 0, 3],
],
);
expect(mtrx.shape(c)).toEqual([1, 4]);
expect(c).toEqual([
[83, 63, 37, 45],
]);
});
it('should transpose matrices', () => {
expect(mtrx.t([[1, 2, 3]])).toEqual([
[1],
[2],
[3],
]);
expect(mtrx.t([
[1],
[2],
[3],
])).toEqual([
[1, 2, 3],
]);
expect(mtrx.t([
[1, 2, 3],
[4, 5, 6],
])).toEqual([
[1, 4],
[2, 5],
[3, 6],
]);
expect(mtrx.t([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
])).toEqual([
[1, 4, 7],
[2, 5, 8],
[3, 6, 9],
]);
});
it('should throw when trying to transpose non 2D matrix', () => {
expect(() => {
mtrx.t([[[1]]]);
}).toThrowError('Matrix is not of 2D shape');
});
it('should add two matrices', () => {
expect(mtrx.add([[1]], [[2]])).toEqual([[3]]);
expect(mtrx.add(
[[1, 2, 3]],
[[4, 5, 6]],
))
.toEqual(
[[5, 7, 9]],
);
expect(mtrx.add(
[[1], [2], [3]],
[[4], [5], [6]],
))
.toEqual(
[[5], [7], [9]],
);
expect(mtrx.add(
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
],
[
[10, 11, 12],
[13, 14, 15],
[16, 17, 18],
],
))
.toEqual(
[
[11, 13, 15],
[17, 19, 21],
[23, 25, 27],
],
);
expect(mtrx.add(
[
[[1], [2], [3]],
[[4], [5], [6]],
[[7], [8], [9]],
],
[
[[10], [11], [12]],
[[13], [14], [15]],
[[16], [17], [18]],
],
))
.toEqual(
[
[[11], [13], [15]],
[[17], [19], [21]],
[[23], [25], [27]],
],
);
});
it('should throw when trying to add matrices of different shape', () => {
expect(() => mtrx.add([[0]], [[[0]]])).toThrowError(
'Matrices have different dimensions',
);
expect(() => mtrx.add([[0]], [[0, 0]])).toThrowError(
'Matrices have different shapes',
);
});
it('should do element wise multiplication two matrices', () => {
expect(mtrx.mul([[2]], [[3]])).toEqual([[6]]);
expect(mtrx.mul(
[[1, 2, 3]],
[[4, 5, 6]],
))
.toEqual(
[[4, 10, 18]],
);
expect(mtrx.mul(
[[1], [2], [3]],
[[4], [5], [6]],
))
.toEqual(
[[4], [10], [18]],
);
expect(mtrx.mul(
[
[1, 2],
[3, 4],
],
[
[5, 6],
[7, 8],
],
))
.toEqual(
[
[5, 12],
[21, 32],
],
);
expect(mtrx.mul(
[
[[1], [2]],
[[3], [4]],
],
[
[[5], [6]],
[[7], [8]],
],
))
.toEqual(
[
[[5], [12]],
[[21], [32]],
],
);
});
it('should throw when trying to multiply matrices element-wise of different shape', () => {
expect(() => mtrx.mul([[0]], [[[0]]])).toThrowError(
'Matrices have different dimensions',
);
expect(() => mtrx.mul([[0]], [[0, 0]])).toThrowError(
'Matrices have different shapes',
);
});
it('should do element wise subtraction two matrices', () => {
expect(mtrx.sub([[3]], [[2]])).toEqual([[1]]);
expect(mtrx.sub(
[[10, 12, 14]],
[[4, 5, 6]],
))
.toEqual(
[[6, 7, 8]],
);
expect(mtrx.sub(
[[[10], [12], [14]]],
[[[4], [5], [6]]],
))
.toEqual(
[[[6], [7], [8]]],
);
expect(mtrx.sub(
[
[10, 20],
[30, 40],
],
[
[5, 6],
[7, 8],
],
))
.toEqual(
[
[5, 14],
[23, 32],
],
);
expect(mtrx.sub(
[
[[10], [20]],
[[30], [40]],
],
[
[[5], [6]],
[[7], [8]],
],
))
.toEqual(
[
[[5], [14]],
[[23], [32]],
],
);
});
it('should throw when trying to subtract matrices element-wise of different shape', () => {
expect(() => mtrx.sub([[0]], [[[0]]])).toThrowError(
'Matrices have different dimensions',
);
expect(() => mtrx.sub([[0]], [[0, 0]])).toThrowError(
'Matrices have different shapes',
);
});
});
| javascript-algorithms/src/algorithms/math/matrix/__tests__/Matrix.test.js/0 | {
"file_path": "javascript-algorithms/src/algorithms/math/matrix/__tests__/Matrix.test.js",
"repo_id": "javascript-algorithms",
"token_count": 5017
} | 91 |
/**
* @param {number} degree
* @return {number}
*/
export default function degreeToRadian(degree) {
return degree * (Math.PI / 180);
}
| javascript-algorithms/src/algorithms/math/radian/degreeToRadian.js/0 | {
"file_path": "javascript-algorithms/src/algorithms/math/radian/degreeToRadian.js",
"repo_id": "javascript-algorithms",
"token_count": 45
} | 92 |
# Binary Search
_Read this in other languages:_
[Portuguรชs brasileiro](README.pt-BR.md).
In computer science, binary search, also known as half-interval
search, logarithmic search, or binary chop, is a search algorithm
that finds the position of a target value within a sorted
array. Binary search compares the target value to the middle
element of the array; if they are unequal, the half in which
the target cannot lie is eliminated and the search continues
on the remaining half until it is successful. If the search
ends with the remaining half being empty, the target is not
in the array.

## Complexity
**Time Complexity**: `O(log(n))` - since we split search area by two for every
next iteration.
## References
- [Wikipedia](https://en.wikipedia.org/wiki/Binary_search_algorithm)
- [YouTube](https://www.youtube.com/watch?v=P3YID7liBug&index=29&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)
| javascript-algorithms/src/algorithms/search/binary-search/README.md/0 | {
"file_path": "javascript-algorithms/src/algorithms/search/binary-search/README.md",
"repo_id": "javascript-algorithms",
"token_count": 314
} | 93 |
/**
* Generates Cartesian Product of two sets.
* @param {*[]} setA
* @param {*[]} setB
* @return {*[]}
*/
export default function cartesianProduct(setA, setB) {
// Check if input sets are not empty.
// Otherwise return null since we can't generate Cartesian Product out of them.
if (!setA || !setB || !setA.length || !setB.length) {
return null;
}
// Init product set.
const product = [];
// Now, let's go through all elements of a first and second set and form all possible pairs.
for (let indexA = 0; indexA < setA.length; indexA += 1) {
for (let indexB = 0; indexB < setB.length; indexB += 1) {
// Add current product pair to the product set.
product.push([setA[indexA], setB[indexB]]);
}
}
// Return cartesian product set.
return product;
}
| javascript-algorithms/src/algorithms/sets/cartesian-product/cartesianProduct.js/0 | {
"file_path": "javascript-algorithms/src/algorithms/sets/cartesian-product/cartesianProduct.js",
"repo_id": "javascript-algorithms",
"token_count": 267
} | 94 |
import MergeSort from '../../sorting/merge-sort/MergeSort';
export default class Knapsack {
/**
* @param {KnapsackItem[]} possibleItems
* @param {number} weightLimit
*/
constructor(possibleItems, weightLimit) {
this.selectedItems = [];
this.weightLimit = weightLimit;
this.possibleItems = possibleItems;
}
sortPossibleItemsByWeight() {
this.possibleItems = new MergeSort({
/**
* @var KnapsackItem itemA
* @var KnapsackItem itemB
*/
compareCallback: (itemA, itemB) => {
if (itemA.weight === itemB.weight) {
return 0;
}
return itemA.weight < itemB.weight ? -1 : 1;
},
}).sort(this.possibleItems);
}
sortPossibleItemsByValue() {
this.possibleItems = new MergeSort({
/**
* @var KnapsackItem itemA
* @var KnapsackItem itemB
*/
compareCallback: (itemA, itemB) => {
if (itemA.value === itemB.value) {
return 0;
}
return itemA.value > itemB.value ? -1 : 1;
},
}).sort(this.possibleItems);
}
sortPossibleItemsByValuePerWeightRatio() {
this.possibleItems = new MergeSort({
/**
* @var KnapsackItem itemA
* @var KnapsackItem itemB
*/
compareCallback: (itemA, itemB) => {
if (itemA.valuePerWeightRatio === itemB.valuePerWeightRatio) {
return 0;
}
return itemA.valuePerWeightRatio > itemB.valuePerWeightRatio ? -1 : 1;
},
}).sort(this.possibleItems);
}
// Solve 0/1 knapsack problem
// Dynamic Programming approach.
solveZeroOneKnapsackProblem() {
// We do two sorts because in case of equal weights but different values
// we need to take the most valuable items first.
this.sortPossibleItemsByValue();
this.sortPossibleItemsByWeight();
this.selectedItems = [];
// Create knapsack values matrix.
const numberOfRows = this.possibleItems.length;
const numberOfColumns = this.weightLimit;
const knapsackMatrix = Array(numberOfRows).fill(null).map(() => {
return Array(numberOfColumns + 1).fill(null);
});
// Fill the first column with zeros since it would mean that there is
// no items we can add to knapsack in case if weight limitation is zero.
for (let itemIndex = 0; itemIndex < this.possibleItems.length; itemIndex += 1) {
knapsackMatrix[itemIndex][0] = 0;
}
// Fill the first row with max possible values we would get by just adding
// or not adding the first item to the knapsack.
for (let weightIndex = 1; weightIndex <= this.weightLimit; weightIndex += 1) {
const itemIndex = 0;
const itemWeight = this.possibleItems[itemIndex].weight;
const itemValue = this.possibleItems[itemIndex].value;
knapsackMatrix[itemIndex][weightIndex] = itemWeight <= weightIndex ? itemValue : 0;
}
// Go through combinations of how we may add items to knapsack and
// define what weight/value we would receive using Dynamic Programming
// approach.
for (let itemIndex = 1; itemIndex < this.possibleItems.length; itemIndex += 1) {
for (let weightIndex = 1; weightIndex <= this.weightLimit; weightIndex += 1) {
const currentItemWeight = this.possibleItems[itemIndex].weight;
const currentItemValue = this.possibleItems[itemIndex].value;
if (currentItemWeight > weightIndex) {
// In case if item's weight is bigger then currently allowed weight
// then we can't add it to knapsack and the max possible value we can
// gain at the moment is the max value we got for previous item.
knapsackMatrix[itemIndex][weightIndex] = knapsackMatrix[itemIndex - 1][weightIndex];
} else {
// Else we need to consider the max value we can gain at this point by adding
// current value or just by keeping the previous item for current weight.
knapsackMatrix[itemIndex][weightIndex] = Math.max(
currentItemValue + knapsackMatrix[itemIndex - 1][weightIndex - currentItemWeight],
knapsackMatrix[itemIndex - 1][weightIndex],
);
}
}
}
// Now let's trace back the knapsack matrix to see what items we're going to add
// to the knapsack.
let itemIndex = this.possibleItems.length - 1;
let weightIndex = this.weightLimit;
while (itemIndex > 0) {
const currentItem = this.possibleItems[itemIndex];
const prevItem = this.possibleItems[itemIndex - 1];
// Check if matrix value came from top (from previous item).
// In this case this would mean that we need to include previous item
// to the list of selected items.
if (
knapsackMatrix[itemIndex][weightIndex]
&& knapsackMatrix[itemIndex][weightIndex] === knapsackMatrix[itemIndex - 1][weightIndex]
) {
// Check if there are several items with the same weight but with the different values.
// We need to add highest item in the matrix that is possible to get the highest value.
const prevSumValue = knapsackMatrix[itemIndex - 1][weightIndex];
const prevPrevSumValue = knapsackMatrix[itemIndex - 2][weightIndex];
if (
!prevSumValue
|| (prevSumValue && prevPrevSumValue !== prevSumValue)
) {
this.selectedItems.push(prevItem);
}
} else if (knapsackMatrix[itemIndex - 1][weightIndex - currentItem.weight]) {
this.selectedItems.push(prevItem);
weightIndex -= currentItem.weight;
}
itemIndex -= 1;
}
}
// Solve unbounded knapsack problem.
// Greedy approach.
solveUnboundedKnapsackProblem() {
this.sortPossibleItemsByValue();
this.sortPossibleItemsByValuePerWeightRatio();
for (let itemIndex = 0; itemIndex < this.possibleItems.length; itemIndex += 1) {
if (this.totalWeight < this.weightLimit) {
const currentItem = this.possibleItems[itemIndex];
// Detect how much of current items we can push to knapsack.
const availableWeight = this.weightLimit - this.totalWeight;
const maxPossibleItemsCount = Math.floor(availableWeight / currentItem.weight);
if (maxPossibleItemsCount > currentItem.itemsInStock) {
// If we have more items in stock then it is allowed to add
// let's add the maximum allowed number of them.
currentItem.quantity = currentItem.itemsInStock;
} else if (maxPossibleItemsCount) {
// In case if we don't have specified number of items in stock
// let's add only items we have in stock.
currentItem.quantity = maxPossibleItemsCount;
}
this.selectedItems.push(currentItem);
}
}
}
get totalValue() {
/** @var {KnapsackItem} item */
return this.selectedItems.reduce((accumulator, item) => {
return accumulator + item.totalValue;
}, 0);
}
get totalWeight() {
/** @var {KnapsackItem} item */
return this.selectedItems.reduce((accumulator, item) => {
return accumulator + item.totalWeight;
}, 0);
}
}
| javascript-algorithms/src/algorithms/sets/knapsack-problem/Knapsack.js/0 | {
"file_path": "javascript-algorithms/src/algorithms/sets/knapsack-problem/Knapsack.js",
"repo_id": "javascript-algorithms",
"token_count": 2648
} | 95 |
import dpMaximumSubarray from '../dpMaximumSubarray';
describe('dpMaximumSubarray', () => {
it('should find maximum subarray using the dynamic programming algorithm', () => {
expect(dpMaximumSubarray([])).toEqual([]);
expect(dpMaximumSubarray([0, 0])).toEqual([0]);
expect(dpMaximumSubarray([0, 0, 1])).toEqual([0, 0, 1]);
expect(dpMaximumSubarray([0, 0, 1, 2])).toEqual([0, 0, 1, 2]);
expect(dpMaximumSubarray([0, 0, -1, 2])).toEqual([2]);
expect(dpMaximumSubarray([-1, -2, -3, -4, -5])).toEqual([-1]);
expect(dpMaximumSubarray([1, 2, 3, 2, 3, 4, 5])).toEqual([1, 2, 3, 2, 3, 4, 5]);
expect(dpMaximumSubarray([-2, 1, -3, 4, -1, 2, 1, -5, 4])).toEqual([4, -1, 2, 1]);
expect(dpMaximumSubarray([-2, -3, 4, -1, -2, 1, 5, -3])).toEqual([4, -1, -2, 1, 5]);
expect(dpMaximumSubarray([1, -3, 2, -5, 7, 6, -1, 4, 11, -23])).toEqual([7, 6, -1, 4, 11]);
});
});
| javascript-algorithms/src/algorithms/sets/maximum-subarray/__test__/dpMaximumSubarray.test.js/0 | {
"file_path": "javascript-algorithms/src/algorithms/sets/maximum-subarray/__test__/dpMaximumSubarray.test.js",
"repo_id": "javascript-algorithms",
"token_count": 404
} | 96 |
import caPowerSet from '../caPowerSet';
describe('caPowerSet', () => {
it('should calculate power set of given set using cascading approach', () => {
expect(caPowerSet([1])).toEqual([
[],
[1],
]);
expect(caPowerSet([1, 2])).toEqual([
[],
[1],
[2],
[1, 2],
]);
expect(caPowerSet([1, 2, 3])).toEqual([
[],
[1],
[2],
[1, 2],
[3],
[1, 3],
[2, 3],
[1, 2, 3],
]);
});
});
| javascript-algorithms/src/algorithms/sets/power-set/__test__/caPowerSet.test.js/0 | {
"file_path": "javascript-algorithms/src/algorithms/sets/power-set/__test__/caPowerSet.test.js",
"repo_id": "javascript-algorithms",
"token_count": 258
} | 97 |
import BucketSort from '../BucketSort';
import {
equalArr,
notSortedArr,
reverseArr,
sortedArr,
} from '../../SortTester';
describe('BucketSort', () => {
it('should sort the array of numbers with different buckets amounts', () => {
expect(BucketSort(notSortedArr, 4)).toEqual(sortedArr);
expect(BucketSort(equalArr, 4)).toEqual(equalArr);
expect(BucketSort(reverseArr, 4)).toEqual(sortedArr);
expect(BucketSort(sortedArr, 4)).toEqual(sortedArr);
expect(BucketSort(notSortedArr, 10)).toEqual(sortedArr);
expect(BucketSort(equalArr, 10)).toEqual(equalArr);
expect(BucketSort(reverseArr, 10)).toEqual(sortedArr);
expect(BucketSort(sortedArr, 10)).toEqual(sortedArr);
expect(BucketSort(notSortedArr, 50)).toEqual(sortedArr);
expect(BucketSort(equalArr, 50)).toEqual(equalArr);
expect(BucketSort(reverseArr, 50)).toEqual(sortedArr);
expect(BucketSort(sortedArr, 50)).toEqual(sortedArr);
});
it('should sort the array of numbers with the default buckets of 1', () => {
expect(BucketSort(notSortedArr)).toEqual(sortedArr);
expect(BucketSort(equalArr)).toEqual(equalArr);
expect(BucketSort(reverseArr)).toEqual(sortedArr);
expect(BucketSort(sortedArr)).toEqual(sortedArr);
});
});
| javascript-algorithms/src/algorithms/sorting/bucket-sort/__test__/BucketSort.test.js/0 | {
"file_path": "javascript-algorithms/src/algorithms/sorting/bucket-sort/__test__/BucketSort.test.js",
"repo_id": "javascript-algorithms",
"token_count": 508
} | 98 |
# ๋ณํฉ ์ ๋ ฌ
์ปดํจํฐ๊ณผํ์์, ๋ณํฉ ์ ๋ ฌ(์ผ๋ฐ์ ์ผ๋ก mergesort๋ผ๊ณ ์ฐ๋)์ ํจ์จ์ ์ด๊ณ , ๋ฒ์ฉ์ ์ธ, ๋น๊ต ๊ธฐ๋ฐ์ ์ ๋ ฌ ์๊ณ ๋ฆฌ์ฆ์
๋๋ค. ๋๋ถ๋ถ์ ๊ตฌํ๋ค์ ์์ ์ ์ธ ์ ๋ ฌ์ ๋ง๋ค์ด๋ด๋ฉฐ, ์ด๋ ์ ๋ ฌ๋ ์ฐ์ถ๋ฌผ์์ ๋์ผํ ์์๋ค์ ์
๋ ฅ ์์๊ฐ ์ ์ง๋๋ค๋ ๊ฒ์ ์๋ฏธํฉ๋๋ค. ๋ณํฉ ์ ๋ ฌ์ 1945๋
์ John von Neumann์ด ๋ง๋ ๋ถํ ์ ๋ณต ์๊ณ ๋ฆฌ์ฆ์
๋๋ค.
๋ณํฉ ์ ๋ ฌ์ ์์์
๋๋ค. ์ฐ์ ๋ฆฌ์คํธ๋ฅผ ๊ฐ์ฅ ์์ ๋จ์๋ก ๋๋๊ณ (ํ ๊ฐ์ ์์), ๋ ๊ฐ์ ์ธ์ ํ ๋ฆฌ์คํธ๋ฅผ ์ ๋ ฌํ๊ณ ๋ณํฉํ๊ธฐ ์ํด ๊ฐ ์์์ ์ธ์ ํ ๋ฆฌ์คํธ๋ฅผ ๋น๊ตํฉ๋๋ค. ๋ง์ง๋ง์ผ๋ก ๋ชจ๋ ์์๋ค์ ์ ๋ ฌ๋๊ณ ๋ณํฉ๋ฉ๋๋ค.

์ฌ๊ท์ ์ธ ๋ณํฉ ์ ๋ ฌ ์๊ณ ๋ฆฌ์ฆ์ 7๊ฐ์ ์ ์๊ฐ์ ๊ฐ์ง ๋ฐฐ์ด์ ์ ๋ ฌํ๋๋ฐ ์ฌ์ฉ๋ฉ๋๋ค. ๋ค์์ ํฉ๋ณ ์ ๋ ฌ์ ๋ชจ๋ฐฉํ๊ธฐ ์ํด ์ฌ๋์ด ์ทจํ๋ ๋จ๊ณ์
๋๋ค.(ํํฅ์)

## ๋ณต์ก๋
| Name | Best | Average | Worst | Memory | Stable | Comments |
| --------------------- | :-------------: | :-----------------: | :-----------------: | :-------: | :-------: | :-------- |
| **Merge sort** | n log(n) | n log(n) | n log(n) | n | Yes | |
## ์ฐธ์กฐ
- [Wikipedia](https://en.wikipedia.org/wiki/Merge_sort)
- [YouTube](https://www.youtube.com/watch?v=KF2j-9iSf4Q&index=27&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)
| javascript-algorithms/src/algorithms/sorting/merge-sort/README.ko-KR.md/0 | {
"file_path": "javascript-algorithms/src/algorithms/sorting/merge-sort/README.ko-KR.md",
"repo_id": "javascript-algorithms",
"token_count": 1169
} | 99 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.