Skip to content

Single number i #11153

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 24 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
66eea04
Algorithm solving problem "136. Single Number" from Leetcode (https:/…
eukub Nov 11, 2023
e662451
Algorithm solving problem "136. Single Number" from Leetcode (https:/…
eukub Nov 11, 2023
352d0fb
Algorithm solving problem "136. Single Number" from Leetcode (https:/…
eukub Nov 14, 2023
492890f
Merge branch 'TheAlgorithms:master' into Single-number-I
eukub Nov 14, 2023
ea22368
Algorithm solving problem "136. Single Number" from Leetcode (https:/…
eukub Nov 14, 2023
67859cc
Merge branch 'Single-number-I' of github.com:eukub/Python into Single…
eukub Nov 14, 2023
2fec97b
Algorithm solving problem "136. Single Number" from Leetcode (https:/…
eukub Nov 11, 2023
09a990b
Algorithm solving problem "136. Single Number" from Leetcode (https:/…
eukub Nov 11, 2023
66af9cb
Algorithm solving problem "136. Single Number" from Leetcode (https:/…
eukub Nov 14, 2023
56017b7
Algorithm solving problem "136. Single Number" from Leetcode (https:/…
eukub Nov 14, 2023
b91dbfc
Fix ignore venv in build_directory_md.py (#11156)
FishyGitHubUser Nov 16, 2023
f693cd9
adding a geometry module (#11138)
meg-1 Nov 24, 2023
9a3ddf1
Fix typo in knight_tour.py (#11173)
FishyGitHubUser Nov 25, 2023
826f64d
Typo deicmal -> decimal (#11169)
rahidzeynal Nov 25, 2023
8ecbc70
add graphs/ant_colony_optimization_algorithms.py (#11163)
Clarkzzzzz Nov 25, 2023
3c2925d
Bug fix combinations (#11158)
moaldeen Nov 25, 2023
f474f45
[pre-commit.ci] pre-commit autoupdate (#11154)
pre-commit-ci[bot] Nov 25, 2023
7922760
Create Spearman's rank correlation coefficient (#11155)
cyrixninja Nov 25, 2023
414f854
Added doctest to binary_search_tree.py (#11145)
Suyashd999 Nov 25, 2023
c36b5a7
Update levenshtein_distance.py (#11171)
pedram-mohajer Nov 26, 2023
9b8e185
Add doctest to is_safe function (#11183)
pedram-mohajer Nov 27, 2023
262c01f
[pre-commit.ci] pre-commit autoupdate (#11184)
pre-commit-ci[bot] Nov 27, 2023
0a89331
Create smallestRange.py (#11179)
pedram-mohajer Dec 1, 2023
daa4b92
Merge branch 'Single-number-I' of github.com:eukub/Python into Single…
eukub Dec 2, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ repos:
- id: auto-walrus

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.4
rev: v0.1.6
hooks:
- id: ruff

- repo: https://github.com/psf/black
rev: 23.10.1
rev: 23.11.0
hooks:
- id: black

Expand All @@ -33,7 +33,7 @@ repos:
- tomli

- repo: https://github.com/tox-dev/pyproject-fmt
rev: "1.4.1"
rev: "1.5.1"
hooks:
- id: pyproject-fmt

Expand All @@ -51,7 +51,7 @@ repos:
- id: validate-pyproject

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.6.1
rev: v1.7.1
hooks:
- id: mypy
args:
Expand Down
6 changes: 5 additions & 1 deletion DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -428,12 +428,16 @@
* [Haversine Distance](geodesy/haversine_distance.py)
* [Lamberts Ellipsoidal Distance](geodesy/lamberts_ellipsoidal_distance.py)

## Geometry
* [Geometry](geometry/geometry.py)

## Graphics
* [Bezier Curve](graphics/bezier_curve.py)
* [Vector3 For 2D Rendering](graphics/vector3_for_2d_rendering.py)

## Graphs
* [A Star](graphs/a_star.py)
* [Ant Colony Optimization Algorithms](graphs/ant_colony_optimization_algorithms.py)
* [Articulation Points](graphs/articulation_points.py)
* [Basic Graphs](graphs/basic_graphs.py)
* [Bellman Ford](graphs/bellman_ford.py)
Expand Down Expand Up @@ -718,6 +722,7 @@
* [Sock Merchant](maths/sock_merchant.py)
* [Softmax](maths/softmax.py)
* [Solovay Strassen Primality Test](maths/solovay_strassen_primality_test.py)
* [Spearman Rank Correlation Coefficient](maths/spearman_rank_correlation_coefficient.py)
* Special Numbers
* [Armstrong Numbers](maths/special_numbers/armstrong_numbers.py)
* [Automorphic Number](maths/special_numbers/automorphic_number.py)
Expand Down Expand Up @@ -1310,7 +1315,6 @@
* [Fetch Well Rx Price](web_programming/fetch_well_rx_price.py)
* [Get Amazon Product Data](web_programming/get_amazon_product_data.py)
* [Get Imdb Top 250 Movies Csv](web_programming/get_imdb_top_250_movies_csv.py)
* [Get Imdbtop](web_programming/get_imdbtop.py)
* [Get Ip Geolocation](web_programming/get_ip_geolocation.py)
* [Get Top Billionaires](web_programming/get_top_billionaires.py)
* [Get Top Hn Posts](web_programming/get_top_hn_posts.py)
Expand Down
10 changes: 8 additions & 2 deletions backtracking/all_combinations.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,22 @@ def generate_all_combinations(n: int, k: int) -> list[list[int]]:
>>> generate_all_combinations(n=10, k=-1)
Traceback (most recent call last):
...
RecursionError: maximum recursion depth exceeded
ValueError: k must not be negative
>>> generate_all_combinations(n=-1, k=10)
[]
Traceback (most recent call last):
...
ValueError: n must not be negative
>>> generate_all_combinations(n=5, k=4)
[[1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]]
>>> from itertools import combinations
>>> all(generate_all_combinations(n, k) == combination_lists(n, k)
... for n in range(1, 6) for k in range(1, 6))
True
"""
if k < 0:
raise ValueError("k must not be negative")
if n < 0:
raise ValueError("n must not be negative")

result: list[list[int]] = []
create_all_state(1, n, k, [], result)
Expand Down
4 changes: 2 additions & 2 deletions backtracking/knight_tour.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def open_knight_tour(n: int) -> list[list[int]]:
>>> open_knight_tour(2)
Traceback (most recent call last):
...
ValueError: Open Kight Tour cannot be performed on a board of size 2
ValueError: Open Knight Tour cannot be performed on a board of size 2
"""

board = [[0 for i in range(n)] for j in range(n)]
Expand All @@ -91,7 +91,7 @@ def open_knight_tour(n: int) -> list[list[int]]:
return board
board[i][j] = 0

msg = f"Open Kight Tour cannot be performed on a board of size {n}"
msg = f"Open Knight Tour cannot be performed on a board of size {n}"
raise ValueError(msg)


Expand Down
4 changes: 4 additions & 0 deletions backtracking/n_queens.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ def is_safe(board: list[list[int]], row: int, column: int) -> bool:
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
Expand Down
2 changes: 1 addition & 1 deletion bit_manipulation/is_even.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
def is_even(number: int) -> bool:
"""
return true if the input integer is even
Explanation: Lets take a look at the following deicmal to binary conversions
Explanation: Lets take a look at the following decimal to binary conversions
2 => 10
14 => 1110
100 => 1100100
Expand Down
41 changes: 41 additions & 0 deletions bit_manipulation/single_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""
Given a non-empty array of integers nums, every element
appears twice except for one. Find that single one

You must implement a solution with a linear runtime complexity
and use only constant extra space.

Reference: https://leetcode.com/problems/single-number/
"""


def single_number(nums: list) -> int:
"""
:param nums: A non-empty array of any integers nums,
every element appears twice except for one.
:return: element that appears only one time

Examples:
Example 1
>>> print(single_number([1, 3, 3, 2, 6, 2, 1]))
6

Example 2
>>> print(single_number([12, 1, 1, 7, 1, 12, 1]))
7

Example 3
>>> print(single_number([6]))
6
"""

result = 0
for el in nums:
result ^= el
return result


if __name__ == "__main__":
import doctest

doctest.testmod()
42 changes: 42 additions & 0 deletions data_structures/binary_tree/binary_search_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,30 @@ def insert(self, *values) -> Self:
return self

def search(self, value) -> Node | None:
"""
>>> tree = BinarySearchTree().insert(10, 20, 30, 40, 50)
>>> tree.search(10)
{'10': (None, {'20': (None, {'30': (None, {'40': (None, 50)})})})}
>>> tree.search(20)
{'20': (None, {'30': (None, {'40': (None, 50)})})}
>>> tree.search(30)
{'30': (None, {'40': (None, 50)})}
>>> tree.search(40)
{'40': (None, 50)}
>>> tree.search(50)
50
>>> tree.search(5) is None # element not present
True
>>> tree.search(0) is None # element not present
True
>>> tree.search(-5) is None # element not present
True
>>> BinarySearchTree().search(10)
Traceback (most recent call last):
...
IndexError: Warning: Tree is empty! please use another.
"""

if self.empty():
raise IndexError("Warning: Tree is empty! please use another.")
else:
Expand All @@ -210,6 +234,15 @@ def search(self, value) -> Node | None:
def get_max(self, node: Node | None = None) -> Node | None:
"""
We go deep on the right branch

>>> BinarySearchTree().insert(10, 20, 30, 40, 50).get_max()
50
>>> BinarySearchTree().insert(-5, -1, 0.1, -0.3, -4.5).get_max()
{'0.1': (-0.3, None)}
>>> BinarySearchTree().insert(1, 78.3, 30, 74.0, 1).get_max()
{'78.3': ({'30': (1, 74.0)}, None)}
>>> BinarySearchTree().insert(1, 783, 30, 740, 1).get_max()
{'783': ({'30': (1, 740)}, None)}
"""
if node is None:
if self.root is None:
Expand All @@ -224,6 +257,15 @@ def get_max(self, node: Node | None = None) -> Node | None:
def get_min(self, node: Node | None = None) -> Node | None:
"""
We go deep on the left branch

>>> BinarySearchTree().insert(10, 20, 30, 40, 50).get_min()
{'10': (None, {'20': (None, {'30': (None, {'40': (None, 50)})})})}
>>> BinarySearchTree().insert(-5, -1, 0, -0.3, -4.5).get_min()
{'-5': (None, {'-1': (-4.5, {'0': (-0.3, None)})})}
>>> BinarySearchTree().insert(1, 78.3, 30, 74.0, 1).get_min()
{'1': (None, {'78.3': ({'30': (1, 74.0)}, None)})}
>>> BinarySearchTree().insert(1, 783, 30, 740, 1).get_min()
{'1': (None, {'783': ({'30': (1, 740)}, None)})}
"""
if node is None:
node = self.root
Expand Down
Loading