Skip to content

Commit b13db68

Browse files
authored
Merge branch 'TheAlgorithms:master' into master
2 parents b541857 + fe4aad0 commit b13db68

18 files changed

+824
-44
lines changed

CONTRIBUTING.md

+10-10
Original file line numberDiff line numberDiff line change
@@ -2,28 +2,28 @@
22

33
## Before contributing
44

5-
Welcome to [TheAlgorithms/Python](https://github.com/TheAlgorithms/Python)! Before sending your pull requests, make sure that you __read the whole guidelines__. If you have any doubt on the contributing guide, please feel free to [state it clearly in an issue](https://github.com/TheAlgorithms/Python/issues/new) or ask the community in [Gitter](https://gitter.im/TheAlgorithms/community).
5+
Welcome to [TheAlgorithms/Python](https://github.com/TheAlgorithms/Python)! Before submitting your pull requests, please ensure that you __read the whole guidelines__. If you have any doubts about the contributing guide, please feel free to [state it clearly in an issue](https://github.com/TheAlgorithms/Python/issues/new) or ask the community on [Gitter](https://gitter.im/TheAlgorithms/community).
66

77
## Contributing
88

99
### Contributor
1010

11-
We are very happy that you are considering implementing algorithms and data structures for others! This repository is referenced and used by learners from all over the globe. Being one of our contributors, you agree and confirm that:
11+
We are delighted that you are considering implementing algorithms and data structures for others! This repository is referenced and used by learners from all over the globe. By being one of our contributors, you agree and confirm that:
1212

13-
- You did your work - no plagiarism allowed
13+
- You did your work - no plagiarism allowed.
1414
- Any plagiarized work will not be merged.
15-
- Your work will be distributed under [MIT License](LICENSE.md) once your pull request is merged
16-
- Your submitted work fulfils or mostly fulfils our styles and standards
15+
- Your work will be distributed under [MIT License](LICENSE.md) once your pull request is merged.
16+
- Your submitted work fulfills or mostly fulfills our styles and standards.
1717

18-
__New implementation__ is welcome! For example, new solutions for a problem, different representations for a graph data structure or algorithm designs with different complexity but __identical implementation__ of an existing implementation is not allowed. Please check whether the solution is already implemented or not before submitting your pull request.
18+
__New implementation__ is welcome! For example, new solutions for a problem, different representations for a graph data structure or algorithm designs with different complexity, but __identical implementation__ of an existing implementation is not allowed. Please check whether the solution is already implemented or not before submitting your pull request.
1919

2020
__Improving comments__ and __writing proper tests__ are also highly welcome.
2121

2222
### Contribution
2323

2424
We appreciate any contribution, from fixing a grammar mistake in a comment to implementing complex algorithms. Please read this section if you are contributing your work.
2525

26-
Your contribution will be tested by our [automated testing on GitHub Actions](https://github.com/TheAlgorithms/Python/actions) to save time and mental energy. After you have submitted your pull request, you should see the GitHub Actions tests start to run at the bottom of your submission page. If those tests fail, then click on the ___details___ button try to read through the GitHub Actions output to understand the failure. If you do not understand, please leave a comment on your submission page and a community member will try to help.
26+
Your contribution will be tested by our [automated testing on GitHub Actions](https://github.com/TheAlgorithms/Python/actions) to save time and mental energy. After you have submitted your pull request, you should see the GitHub Actions tests start to run at the bottom of your submission page. If those tests fail, then click on the ___details___ button to read through the GitHub Actions output to understand the failure. If you do not understand, please leave a comment on your submission page and a community member will try to help.
2727

2828
#### Issues
2929

@@ -58,7 +58,7 @@ Algorithms should:
5858
* contain doctests that test both valid and erroneous input values
5959
* return all calculation results instead of printing or plotting them
6060

61-
Algorithms in this repo should not be how-to examples for existing Python packages. Instead, they should perform internal calculations or manipulations to convert input values into different output values. Those calculations or manipulations can use data types, classes, or functions of existing Python packages but each algorithm in this repo should add unique value.
61+
Algorithms in this repo should not be how-to examples for existing Python packages. Instead, they should perform internal calculations or manipulations to convert input values into different output values. Those calculations or manipulations can use data types, classes, or functions of existing Python packages but each algorithm in this repo should add unique value.
6262

6363
#### Pre-commit plugin
6464
Use [pre-commit](https://pre-commit.com/#installation) to automatically format your code to match our coding style:
@@ -77,7 +77,7 @@ pre-commit run --all-files --show-diff-on-failure
7777

7878
We want your work to be readable by others; therefore, we encourage you to note the following:
7979

80-
- Please write in Python 3.12+. For instance: `print()` is a function in Python 3 so `print "Hello"` will *not* work but `print("Hello")` will.
80+
- Please write in Python 3.12+. For instance: `print()` is a function in Python 3 so `print "Hello"` will *not* work but `print("Hello")` will.
8181
- Please focus hard on the naming of functions, classes, and variables. Help your reader by using __descriptive names__ that can help you to remove redundant comments.
8282
- Single letter variable names are *old school* so please avoid them unless their life only spans a few lines.
8383
- Expand acronyms because `gcd()` is hard to understand but `greatest_common_divisor()` is not.
@@ -145,7 +145,7 @@ We want your work to be readable by others; therefore, we encourage you to note
145145
python3 -m doctest -v my_submission.py
146146
```
147147

148-
The use of the Python builtin `input()` function is __not__ encouraged:
148+
The use of the Python built-in `input()` function is __not__ encouraged:
149149

150150
```python
151151
input('Enter your input:')

DIRECTORY.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -774,8 +774,8 @@
774774
## Other
775775
* [Activity Selection](other/activity_selection.py)
776776
* [Alternative List Arrange](other/alternative_list_arrange.py)
777+
* [Bankers Algorithm](other/bankers_algorithm.py)
777778
* [Davis Putnam Logemann Loveland](other/davis_putnam_logemann_loveland.py)
778-
* [Dijkstra Bankers Algorithm](other/dijkstra_bankers_algorithm.py)
779779
* [Doomsday](other/doomsday.py)
780780
* [Fischer Yates Shuffle](other/fischer_yates_shuffle.py)
781781
* [Gauss Easter](other/gauss_easter.py)

computer_vision/haralick_descriptors.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -253,13 +253,13 @@ def matrix_concurrency(image: np.ndarray, coordinate: tuple[int, int]) -> np.nda
253253

254254

255255
def haralick_descriptors(matrix: np.ndarray) -> list[float]:
256-
"""Calculates all 8 Haralick descriptors based on co-occurence input matrix.
256+
"""Calculates all 8 Haralick descriptors based on co-occurrence input matrix.
257257
All descriptors are as follows:
258258
Maximum probability, Inverse Difference, Homogeneity, Entropy,
259259
Energy, Dissimilarity, Contrast and Correlation
260260
261261
Args:
262-
matrix: Co-occurence matrix to use as base for calculating descriptors.
262+
matrix: Co-occurrence matrix to use as base for calculating descriptors.
263263
264264
Returns:
265265
Reverse ordered list of resulting descriptors
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
"""
2+
Retrieves the value of an 0-indexed 1D index from a 2D array.
3+
There are two ways to retrieve value(s):
4+
5+
1. Index2DArrayIterator(matrix) -> Iterator[int]
6+
This iterator allows you to iterate through a 2D array by passing in the matrix and
7+
calling next(your_iterator). You can also use the iterator in a loop.
8+
Examples:
9+
list(Index2DArrayIterator(matrix))
10+
set(Index2DArrayIterator(matrix))
11+
tuple(Index2DArrayIterator(matrix))
12+
sum(Index2DArrayIterator(matrix))
13+
-5 in Index2DArrayIterator(matrix)
14+
15+
2. index_2d_array_in_1d(array: list[int], index: int) -> int
16+
This function allows you to provide a 2D array and a 0-indexed 1D integer index,
17+
and retrieves the integer value at that index.
18+
19+
Python doctests can be run using this command:
20+
python3 -m doctest -v index_2d_array_in_1d.py
21+
"""
22+
23+
from collections.abc import Iterator
24+
from dataclasses import dataclass
25+
26+
27+
@dataclass
28+
class Index2DArrayIterator:
29+
matrix: list[list[int]]
30+
31+
def __iter__(self) -> Iterator[int]:
32+
"""
33+
>>> tuple(Index2DArrayIterator([[5], [-523], [-1], [34], [0]]))
34+
(5, -523, -1, 34, 0)
35+
>>> tuple(Index2DArrayIterator([[5, -523, -1], [34, 0]]))
36+
(5, -523, -1, 34, 0)
37+
>>> tuple(Index2DArrayIterator([[5, -523, -1, 34, 0]]))
38+
(5, -523, -1, 34, 0)
39+
>>> t = Index2DArrayIterator([[5, 2, 25], [23, 14, 5], [324, -1, 0]])
40+
>>> tuple(t)
41+
(5, 2, 25, 23, 14, 5, 324, -1, 0)
42+
>>> list(t)
43+
[5, 2, 25, 23, 14, 5, 324, -1, 0]
44+
>>> sorted(t)
45+
[-1, 0, 2, 5, 5, 14, 23, 25, 324]
46+
>>> tuple(t)[3]
47+
23
48+
>>> sum(t)
49+
397
50+
>>> -1 in t
51+
True
52+
>>> t = iter(Index2DArrayIterator([[5], [-523], [-1], [34], [0]]))
53+
>>> next(t)
54+
5
55+
>>> next(t)
56+
-523
57+
"""
58+
for row in self.matrix:
59+
yield from row
60+
61+
62+
def index_2d_array_in_1d(array: list[list[int]], index: int) -> int:
63+
"""
64+
Retrieves the value of the one-dimensional index from a two-dimensional array.
65+
66+
Args:
67+
array: A 2D array of integers where all rows are the same size and all
68+
columns are the same size.
69+
index: A 1D index.
70+
71+
Returns:
72+
int: The 0-indexed value of the 1D index in the array.
73+
74+
Examples:
75+
>>> index_2d_array_in_1d([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], 5)
76+
5
77+
>>> index_2d_array_in_1d([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], -1)
78+
Traceback (most recent call last):
79+
...
80+
ValueError: index out of range
81+
>>> index_2d_array_in_1d([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], 12)
82+
Traceback (most recent call last):
83+
...
84+
ValueError: index out of range
85+
>>> index_2d_array_in_1d([[]], 0)
86+
Traceback (most recent call last):
87+
...
88+
ValueError: no items in array
89+
"""
90+
rows = len(array)
91+
cols = len(array[0])
92+
93+
if rows == 0 or cols == 0:
94+
raise ValueError("no items in array")
95+
96+
if index < 0 or index >= rows * cols:
97+
raise ValueError("index out of range")
98+
99+
return array[index // cols][index % cols]
100+
101+
102+
if __name__ == "__main__":
103+
import doctest
104+
105+
doctest.testmod()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
"""
2+
Given an array of integers and an integer k, find the kth largest element in the array.
3+
4+
https://stackoverflow.com/questions/251781
5+
"""
6+
7+
8+
def partition(arr: list[int], low: int, high: int) -> int:
9+
"""
10+
Partitions list based on the pivot element.
11+
12+
This function rearranges the elements in the input list 'elements' such that
13+
all elements greater than or equal to the chosen pivot are on the right side
14+
of the pivot, and all elements smaller than the pivot are on the left side.
15+
16+
Args:
17+
arr: The list to be partitioned
18+
low: The lower index of the list
19+
high: The higher index of the list
20+
21+
Returns:
22+
int: The index of pivot element after partitioning
23+
24+
Examples:
25+
>>> partition([3, 1, 4, 5, 9, 2, 6, 5, 3, 5], 0, 9)
26+
4
27+
>>> partition([7, 1, 4, 5, 9, 2, 6, 5, 8], 0, 8)
28+
1
29+
>>> partition(['apple', 'cherry', 'date', 'banana'], 0, 3)
30+
2
31+
>>> partition([3.1, 1.2, 5.6, 4.7], 0, 3)
32+
1
33+
"""
34+
pivot = arr[high]
35+
i = low - 1
36+
for j in range(low, high):
37+
if arr[j] >= pivot:
38+
i += 1
39+
arr[i], arr[j] = arr[j], arr[i]
40+
arr[i + 1], arr[high] = arr[high], arr[i + 1]
41+
return i + 1
42+
43+
44+
def kth_largest_element(arr: list[int], position: int) -> int:
45+
"""
46+
Finds the kth largest element in a list.
47+
Should deliver similar results to:
48+
```python
49+
def kth_largest_element(arr, position):
50+
return sorted(arr)[-position]
51+
```
52+
53+
Args:
54+
nums: The list of numbers.
55+
k: The position of the desired kth largest element.
56+
57+
Returns:
58+
int: The kth largest element.
59+
60+
Examples:
61+
>>> kth_largest_element([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5], 3)
62+
5
63+
>>> kth_largest_element([2, 5, 6, 1, 9, 3, 8, 4, 7, 3, 5], 1)
64+
9
65+
>>> kth_largest_element([2, 5, 6, 1, 9, 3, 8, 4, 7, 3, 5], -2)
66+
Traceback (most recent call last):
67+
...
68+
ValueError: Invalid value of 'position'
69+
>>> kth_largest_element([9, 1, 3, 6, 7, 9, 8, 4, 2, 4, 9], 110)
70+
Traceback (most recent call last):
71+
...
72+
ValueError: Invalid value of 'position'
73+
>>> kth_largest_element([1, 2, 4, 3, 5, 9, 7, 6, 5, 9, 3], 0)
74+
Traceback (most recent call last):
75+
...
76+
ValueError: Invalid value of 'position'
77+
>>> kth_largest_element(['apple', 'cherry', 'date', 'banana'], 2)
78+
'cherry'
79+
>>> kth_largest_element([3.1, 1.2, 5.6, 4.7,7.9,5,0], 2)
80+
5.6
81+
>>> kth_largest_element([-2, -5, -4, -1], 1)
82+
-1
83+
>>> kth_largest_element([], 1)
84+
-1
85+
>>> kth_largest_element([3.1, 1.2, 5.6, 4.7, 7.9, 5, 0], 1.5)
86+
Traceback (most recent call last):
87+
...
88+
ValueError: The position should be an integer
89+
>>> kth_largest_element((4, 6, 1, 2), 4)
90+
Traceback (most recent call last):
91+
...
92+
TypeError: 'tuple' object does not support item assignment
93+
"""
94+
if not arr:
95+
return -1
96+
if not isinstance(position, int):
97+
raise ValueError("The position should be an integer")
98+
if not 1 <= position <= len(arr):
99+
raise ValueError("Invalid value of 'position'")
100+
low, high = 0, len(arr) - 1
101+
while low <= high:
102+
if low > len(arr) - 1 or high < 0:
103+
return -1
104+
pivot_index = partition(arr, low, high)
105+
if pivot_index == position - 1:
106+
return arr[pivot_index]
107+
elif pivot_index > position - 1:
108+
high = pivot_index - 1
109+
else:
110+
low = pivot_index + 1
111+
return -1
112+
113+
114+
if __name__ == "__main__":
115+
import doctest
116+
117+
doctest.testmod()

0 commit comments

Comments
 (0)