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 functio... | 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(bo... | 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'
>>>... | 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.... | 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)
li... | 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 addi... | 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 f... | 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, the... | 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 Erro... | 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
... ... | 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 num... | 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 pro... | 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 (li... | 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 ... | 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
... | 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... | 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([... | 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... | 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 Wesl... | 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 alg... | 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):
"""
... | 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 ... | 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/... | 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... | 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 al... | 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 g... | 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 option... | 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... | 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 tha... | 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 matc... | 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... | 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... | 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):
... | 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... | 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... | 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 ha... | 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/itsAkshayDub... | 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 (m... | 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 cub... | 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_p... | 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 annota... | 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)
... | 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)
113423713055... | 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 ... | 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: ign... | 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,... | 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
f... | 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("012345... | 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 pa... | 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 sequenc... | 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... | 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.
Th... | 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... | 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 exampl... | 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 ex... | 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, ... | 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 = ... | 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) ... | 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: Collec... | 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_sea... | 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 worl... | 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("+94... | 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/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_ph... | 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 g... | 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)
... | 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
* [Th... | 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++ ะขะตะพััั ัะฐ ะฟัะฐ... | 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://laravelp... | 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... | 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-cs... | 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 |
# ฮฯฮดฮนฮบฮฑฯ ฮฮตฮฟฮฝฯฮฟฮปฮฟฮณฮฏฮฑฯ ฮฃฯ
ฮฝฮตฮนฯฯฮตฯฯฮฝฯฯฮฝ
ฮฉฯ ฯฯ
ฮฝฮตฮนฯฯฮญฯฮฟฮฝฯฮตฯ ฮบฮฑฮน ฯฯ
ฮฝฯฮทฯฮทฯฮญฯ ฮฑฯ
ฯฮฟฯ ฯฮฟฯ
ฮญฯฮณฮฟฯ
, ฮบฮฑฮน ฯฯฮฟฮบฮตฮนฮผฮญฮฝฯ ฮฝฮฑ
ฯฯฮฟฯฮธฮฎฯฮฟฯ
ฮผฮต ฮผฮนฮฑ ฮฑฮฝฮฟฮนฯฯฮฎ ฮบฮฑฮน ฯฮนฮปฯฮพฮตฮฝฮท ฮบฮฟฮนฮฝฯฯฮทฯฮฑ, ฮดฮตฯฮผฮตฯ
ฯฮผฮฑฯฯฮต ฮฝฮฑ ฯฮตฮฒฯฮผฮฑฯฯฮต ฯฮปฮฟฯ
ฯ ฯฮฟฯ
ฯ ฮฑฮฝฮธฯฯฯฮฟฯ
ฯ ฯฮฟฯ
ฯฯ
ฮฝฮตฮนฯฯฮญฯฮฟฯ
ฮฝ ฮผฮญฯฯ ฯฯฮฝ ฮฑฮฝฮฑฯฮฟฯฯฮฝ ฮถฮทฯฮทฮผฮฌฯฯฮฝ, ฯฮทฮฝ ฮฑฮฝฮฌฯฯฮทฯฮท ฮฑฮนฯฮทฮผฮฌฯฯฮฝ ฮณฮนฮฑ ฮฝฮญฮตฯ ฮปฮตฮนฯฮฟฯ
ฯฮณฮฏฮตฯ, ฯฮทฮฝ ฮตฮฝฮทฮผฮญฯฯฯฮท
ฯฮฟฯ
documenta... | 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 p... | 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 ... | 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๏ผๅฆๆไฝ ็ผ็พไบไธไบๆ่ถฃ... | 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 แแแแผแ , แแแแถแแแถแแแแแแแขแถแ
แแฝแแขแแแแ... | 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... | 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.c... | 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/... | 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 w... | 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 ... | 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 wi... | 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 |
# ํฌ๋ฃจ์ค์นผ ์๊ณ ๋ฆฌ์ฆ
ํฌ๋ฃจ์ค์นผ ์๊ณ ๋ฆฌ์ฆ์ ๋ ํธ๋ฆฌ๋ฅผ ์ฐ๊ฒฐํ๋ ์ต์ ๊ฐ์ ๊ฐ์ค์น๋ฅผ ์ฐพ๋ ์ต์ ์ ์ฅ ํธ๋ฆฌ ์๊ณ ๋ฆฌ์ฆ์
๋๋ค.
๊ฐ ๋จ๊ณ์์ ๋น์ฉ์ ๋ํ๋ ์ฐ๊ฒฐ๋ ๊ฐ์ค ๊ทธ๋ํ์ ๋ํ ์ต์ ์ ์ฅ ํธ๋ฆฌ๋ฅผ ์ฐพ๊ธฐ ๋๋ฌธ์ ๊ทธ๋ํ ์ด๋ก ์์์ ๊ทธ๋ฆฌ๋ ์๊ณ ๋ฆฌ์ฆ์
๋๋ค. ์ฆ, ํธ๋ฆฌ์ ๋ชจ๋ ๊ฐ์ ์ ์ด ๊ฐ์ค์น๊ฐ ์ต์ํ๋๋ ๋ชจ๋ ์ ์ ์ ํฌํจํ๋ ํธ๋ฆฌ๋ฅผ ํ์ฑํ๋ ๊ฐ์ ์ ํ์ ์งํฉ์ ์ฐพ์ต๋๋ค. ๊ทธ๋ํ๊ฐ ์ฐ๊ฒฐ๋์ด ์์ง ์์ผ๋ฉด ์ต์ ์ ์ฅ ํฌ๋ ์คํธ(์ฐ๊ฒฐ๋ ๊ฐ ๊ตฌ์ฑ ์์์ ์ต์ ์ ์ฅ ํธ๋ฆฌ)๋ฅผ ์ฐพ์ต๋๋ค.

> There is an [interactive version of this post](https://trekhleb.dev/blog/2... | 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 traversedN... | 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);
expe... | 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 ... | 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 d... | 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) ... | 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 partitione... | 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');
... | 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 targ... | 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.le... | 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 = possi... | 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])).to... | 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],
]);
... | 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(Bucket... | 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์ด ๋ง๋ ๋ถํ ์ ๋ณต ์๊ณ ๋ฆฌ์ฆ์
๋๋ค.
๋ณํฉ ์ ๋ ฌ์ ์์์
๋๋ค. ์ฐ์ ๋ฆฌ์คํธ๋ฅผ ๊ฐ์ฅ ์์ ๋จ์๋ก ๋๋๊ณ (ํ ๊ฐ์ ์์), ๋ ๊ฐ์ ์ธ์ ํ ๋ฆฌ์คํธ๋ฅผ ์ ๋ ฌํ๊ณ ๋ณํฉํ๊ธฐ ์ํด ๊ฐ ์์์ ์ธ์ ํ ๋ฆฌ์คํธ๋ฅผ ๋น๊ตํฉ๋๋ค. ๋ง์ง๋ง์ผ๋ก ๋ชจ๋ ์์๋ค์ ์ ๋ ฌ๋๊ณ ๋ณํฉ๋ฉ๋๋ค... | 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.