Skip to content

Commit 7aca8ef

Browse files
cclaussFaraz126
andauthored
Create codespell.yml (TheAlgorithms#1696)
* Added implementation for simulated annealing (TheAlgorithms#1679) * added hill climbing algorithm * Shorten long lines, streamline get_neighbors() * Update hill_climbing.py * Update and rename optimization/hill_climbing.py to searches/hill_climbing.py * added hill climbing algorithm * Shorten long lines, streamline get_neighbors() * Update hill_climbing.py * Rebased * added simulated annealing.py * added final comments and test * black formatted * restricted search domain Co-authored-by: Christian Clauss <cclauss@me.com> * Create codespell.yml * updating DIRECTORY.md * Update simulated_annealing.py * codespell -L ans,fo,hist,iff,Secant,Tim,tim --skip=$SKIP * codespell -L ans,fo,hist,iff,secant,tim --skip=$SKIP * if __name__ == "__main__": * fixup! Format Python code with psf/black push Co-authored-by: Faraz Ahmed Khan <31242842+fk03983@users.noreply.github.com>
1 parent fbd566b commit 7aca8ef

File tree

75 files changed

+310
-174
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

75 files changed

+310
-174
lines changed

.github/workflows/codespell.yml

+3-1
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,6 @@ jobs:
99
- uses: actions/checkout@v2
1010
- uses: actions/setup-python@v1
1111
- run: pip install codespell flake8
12-
- run: codespell -L ans --skip="./.*,./other/dictionary.txt,./other/words,./project_euler/problem_22/p022_names.txt,*.jpg,*.png,*.jpeg,*.gif"
12+
- run: |
13+
SKIP="./.*,./other/dictionary.txt,./other/words,./project_euler/problem_22/p022_names.txt,*.bak,*.gif,*.jpeg,*.jpg,*.json,*.png,*.pyc"
14+
codespell -L ans,fo,hist,iff,secant,tim --skip=$SKIP

DIRECTORY.md

+5-4
Original file line numberDiff line numberDiff line change
@@ -177,14 +177,14 @@
177177
* [Longest Sub Array](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_sub_array.py)
178178
* [Matrix Chain Order](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/matrix_chain_order.py)
179179
* [Max Sub Array](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/max_sub_array.py)
180-
* [Max Sum Contigous Subsequence](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/max_sum_contigous_subsequence.py)
180+
* [Max Sum Contiguous Subsequence](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/max_sum_contiguous_subsequence.py)
181181
* [Minimum Partition](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_partition.py)
182182
* [Rod Cutting](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/rod_cutting.py)
183183
* [Subset Generation](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/subset_generation.py)
184184
* [Sum Of Subset](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/sum_of_subset.py)
185185

186186
## File Transfer
187-
* [Recieve File](https://github.com/TheAlgorithms/Python/blob/master/file_transfer/recieve_file.py)
187+
* [Receive File](https://github.com/TheAlgorithms/Python/blob/master/file_transfer/receive_file.py)
188188
* [Send File](https://github.com/TheAlgorithms/Python/blob/master/file_transfer/send_file.py)
189189

190190
## Fuzzy Logic
@@ -219,7 +219,7 @@
219219
* [Kahns Algorithm Topo](https://github.com/TheAlgorithms/Python/blob/master/graphs/kahns_algorithm_topo.py)
220220
* [Minimum Spanning Tree Kruskal](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_kruskal.py)
221221
* [Minimum Spanning Tree Prims](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_prims.py)
222-
* [Multi Hueristic Astar](https://github.com/TheAlgorithms/Python/blob/master/graphs/multi_hueristic_astar.py)
222+
* [Multi Heuristic Astar](https://github.com/TheAlgorithms/Python/blob/master/graphs/multi_heuristic_astar.py)
223223
* [Page Rank](https://github.com/TheAlgorithms/Python/blob/master/graphs/page_rank.py)
224224
* [Prim](https://github.com/TheAlgorithms/Python/blob/master/graphs/prim.py)
225225
* [Scc Kosaraju](https://github.com/TheAlgorithms/Python/blob/master/graphs/scc_kosaraju.py)
@@ -511,6 +511,7 @@
511511
* [Quick Select](https://github.com/TheAlgorithms/Python/blob/master/searches/quick_select.py)
512512
* [Sentinel Linear Search](https://github.com/TheAlgorithms/Python/blob/master/searches/sentinel_linear_search.py)
513513
* [Simple-Binary-Search](https://github.com/TheAlgorithms/Python/blob/master/searches/simple-binary-search.py)
514+
* [Simulated Annealing](https://github.com/TheAlgorithms/Python/blob/master/searches/simulated_annealing.py)
514515
* [Tabu Search](https://github.com/TheAlgorithms/Python/blob/master/searches/tabu_search.py)
515516
* [Ternary Search](https://github.com/TheAlgorithms/Python/blob/master/searches/ternary_search.py)
516517

@@ -567,7 +568,7 @@
567568
* [Reverse Words](https://github.com/TheAlgorithms/Python/blob/master/strings/reverse_words.py)
568569
* [Split](https://github.com/TheAlgorithms/Python/blob/master/strings/split.py)
569570
* [Upper](https://github.com/TheAlgorithms/Python/blob/master/strings/upper.py)
570-
* [Word Occurence](https://github.com/TheAlgorithms/Python/blob/master/strings/word_occurence.py)
571+
* [Word Occurrence](https://github.com/TheAlgorithms/Python/blob/master/strings/word_occurrence.py)
571572

572573
## Traversals
573574
* [Binary Tree Traversals](https://github.com/TheAlgorithms/Python/blob/master/traversals/binary_tree_traversals.py)

backtracking/n_queens.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,8 @@ def isSafe(board, row, column):
4040

4141
def solve(board, row):
4242
"""
43-
It creates a state space tree and calls the safe function untill it receives a
44-
False Boolean and terminates that brach and backtracks to the next
43+
It creates a state space tree and calls the safe function until it receives a
44+
False Boolean and terminates that branch and backtracks to the next
4545
poosible solution branch.
4646
"""
4747
if row >= len(board):
@@ -58,7 +58,7 @@ def solve(board, row):
5858
"""
5959
For every row it iterates through each column to check if it is feesible to place a
6060
queen there.
61-
If all the combinations for that particaular branch are successfull the board is
61+
If all the combinations for that particular branch are successful the board is
6262
reinitialized for the next possible combination.
6363
"""
6464
if isSafe(board, row, i):
@@ -70,7 +70,7 @@ def solve(board, row):
7070

7171
def printboard(board):
7272
"""
73-
Prints the boards that have a successfull combination.
73+
Prints the boards that have a successful combination.
7474
"""
7575
for i in range(len(board)):
7676
for j in range(len(board)):

ciphers/hill_cipher.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,15 @@
33
Hill Cipher:
44
The below defined class 'HillCipher' implements the Hill Cipher algorithm.
55
The Hill Cipher is an algorithm that implements modern linear algebra techniques
6-
In this algortihm, you have an encryption key matrix. This is what will be used
6+
In this algorithm, you have an encryption key matrix. This is what will be used
77
in encoding and decoding your text.
88
9-
Algortihm:
9+
Algorithm:
1010
Let the order of the encryption key be N (as it is a square matrix).
1111
Your text is divided into batches of length N and converted to numerical vectors
1212
by a simple mapping starting with A=0 and so on.
1313
14-
The key is then mulitplied with the newly created batch vector to obtain the
14+
The key is then multiplied with the newly created batch vector to obtain the
1515
encoded vector. After each multiplication modular 36 calculations are performed
1616
on the vectors so as to bring the numbers between 0 and 36 and then mapped with
1717
their corresponding alphanumerics.

ciphers/rsa_cipher.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
def main():
88
filename = "encrypted_file.txt"
9-
response = input(r"Encrypte\Decrypt [e\d]: ")
9+
response = input(r"Encrypt\Decrypt [e\d]: ")
1010

1111
if response.lower().startswith("e"):
1212
mode = "encrypt"

ciphers/rsa_key_generator.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,12 @@ def makeKeyFiles(name, keySize):
4242

4343
publicKey, privateKey = generateKey(keySize)
4444
print("\nWriting public key to file %s_pubkey.txt..." % name)
45-
with open("%s_pubkey.txt" % name, "w") as fo:
46-
fo.write("{},{},{}".format(keySize, publicKey[0], publicKey[1]))
45+
with open("%s_pubkey.txt" % name, "w") as out_file:
46+
out_file.write("{},{},{}".format(keySize, publicKey[0], publicKey[1]))
4747

4848
print("Writing private key to file %s_privkey.txt..." % name)
49-
with open("%s_privkey.txt" % name, "w") as fo:
50-
fo.write("{},{},{}".format(keySize, privateKey[0], privateKey[1]))
49+
with open("%s_privkey.txt" % name, "w") as out_file:
50+
out_file.write("{},{},{}".format(keySize, privateKey[0], privateKey[1]))
5151

5252

5353
if __name__ == "__main__":

compression/burrows_wheeler.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -157,11 +157,11 @@ def reverse_bwt(bwt_string: str, idx_original_string: int) -> str:
157157
entry_msg = "Provide a string that I will generate its BWT transform: "
158158
s = input(entry_msg).strip()
159159
result = bwt_transform(s)
160-
bwt_output_msg = "Burrows Wheeler tranform for string '{}' results in '{}'"
160+
bwt_output_msg = "Burrows Wheeler transform for string '{}' results in '{}'"
161161
print(bwt_output_msg.format(s, result["bwt_string"]))
162162
original_string = reverse_bwt(result["bwt_string"], result["idx_original_string"])
163163
fmt = (
164-
"Reversing Burrows Wheeler tranform for entry '{}' we get original"
164+
"Reversing Burrows Wheeler transform for entry '{}' we get original"
165165
" string '{}'"
166166
)
167167
print(fmt.format(result["bwt_string"], original_string))

compression/huffman.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def __init__(self, freq, left, right):
2121
def parse_file(file_path):
2222
"""
2323
Read the file and build a dict of all letters and their
24-
frequences, then convert the dict into a list of Letters.
24+
frequencies, then convert the dict into a list of Letters.
2525
"""
2626
chars = {}
2727
with open(file_path) as f:

compression/peak_signal_to_noise_ratio.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""
22
Peak signal-to-noise ratio - PSNR - https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio
3-
Soruce: https://tutorials.techonical.com/how-to-calculate-psnr-value-of-two-images-using-python/
3+
Source: https://tutorials.techonical.com/how-to-calculate-psnr-value-of-two-images-using-python/
44
"""
55

66
import math

conversions/decimal_to_octal.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def decimal_to_octal(num: int) -> str:
2424

2525

2626
def main():
27-
"""Print octal equivelents of decimal numbers."""
27+
"""Print octal equivalents of decimal numbers."""
2828
print("\n2 in octal is:")
2929
print(decimal_to_octal(2)) # = 2
3030
print("\n8 in octal is:")

data_structures/binary_tree/binary_search_tree.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ def __repr__(self):
1515

1616
if self.left is None and self.right is None:
1717
return str(self.value)
18-
return pformat({"%s" % (self.value): (self.left, self.right)}, indent=1,)
18+
return pformat({"%s" % (self.value): (self.left, self.right)}, indent=1)
1919

2020

2121
class BinarySearchTree:

data_structures/binary_tree/lowest_common_ancestor.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ def swap(a, b):
1111
return a, b
1212

1313

14-
# creating sparse table which saves each nodes 2^ith parent
14+
# creating sparse table which saves each nodes 2^i-th parent
1515
def creatSparse(max_node, parent):
1616
j = 1
1717
while (1 << j) < max_node:

data_structures/binary_tree/number_of_possible_binary_trees.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def binomial_coefficient(n: int, k: int) -> int:
4141

4242
def catalan_number(node_count: int) -> int:
4343
"""
44-
We can find Catalan number many ways but here we use Binomial Coefficent because it
44+
We can find Catalan number many ways but here we use Binomial Coefficient because it
4545
does the job in O(n)
4646
4747
return the Catalan number of n using 2nCn/(n+1).

data_structures/binary_tree/red_black_tree.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ class RedBlackTree:
1212
less strict, so it will perform faster for writing/deleting nodes
1313
and slower for reading in the average case, though, because they're
1414
both balanced binary search trees, both will get the same asymptotic
15-
perfomance.
15+
performance.
1616
To read more about them, https://en.wikipedia.org/wiki/Red–black_tree
1717
Unless otherwise specified, all asymptotic runtimes are specified in
1818
terms of the size of the tree.
@@ -37,7 +37,7 @@ def __init__(self, label=None, color=0, parent=None, left=None, right=None):
3737
def rotate_left(self):
3838
"""Rotate the subtree rooted at this node to the left and
3939
returns the new root to this subtree.
40-
Perfoming one rotation can be done in O(1).
40+
Performing one rotation can be done in O(1).
4141
"""
4242
parent = self.parent
4343
right = self.right
@@ -656,7 +656,7 @@ def test_tree_traversal():
656656

657657

658658
def test_tree_chaining():
659-
"""Tests the three different tree chaning functions."""
659+
"""Tests the three different tree chaining functions."""
660660
tree = RedBlackTree(0)
661661
tree = tree.insert(-16).insert(16).insert(8).insert(24).insert(20).insert(22)
662662
if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]:

data_structures/binary_tree/treap.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def __repr__(self):
2121
return f"'{self.value}: {self.prior:.5}'"
2222
else:
2323
return pformat(
24-
{f"{self.value}: {self.prior:.5}": (self.left, self.right)}, indent=1,
24+
{f"{self.value}: {self.prior:.5}": (self.left, self.right)}, indent=1
2525
)
2626

2727
def __str__(self):
@@ -161,7 +161,7 @@ def main():
161161
"""After each command, program prints treap"""
162162
root = None
163163
print(
164-
"enter numbers to creat a tree, + value to add value into treap, - value to erase all nodes with value. 'q' to quit. "
164+
"enter numbers to create a tree, + value to add value into treap, - value to erase all nodes with value. 'q' to quit. "
165165
)
166166

167167
args = input()

data_structures/heap/binomial_heap.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ class BinomialHeap:
4949
r"""
5050
Min-oriented priority queue implemented with the Binomial Heap data
5151
structure implemented with the BinomialHeap class. It supports:
52-
- Insert element in a heap with n elemnts: Guaranteed logn, amoratized 1
52+
- Insert element in a heap with n elements: Guaranteed logn, amoratized 1
5353
- Merge (meld) heaps of size m and n: O(logn + logm)
5454
- Delete Min: O(logn)
5555
- Peek (return min without deleting it): O(1)

data_structures/linked_list/deque_doubly.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
Operations:
44
1. insertion in the front -> O(1)
55
2. insertion in the end -> O(1)
6-
3. remove fron the front -> O(1)
6+
3. remove from the front -> O(1)
77
4. remove from the end -> O(1)
88
"""
99

data_structures/linked_list/doubly_linked_list.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
- This is an example of a double ended, doubly linked list.
44
- Each link references the next link and the previous one.
55
- A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer, together with next pointer and data which are there in singly linked list.
6-
- Advantages over SLL - IT can be traversed in both forward and backward direction.,Delete operation is more efficent"""
6+
- Advantages over SLL - IT can be traversed in both forward and backward direction.,Delete operation is more efficient"""
77

88

99
class LinkedList: # making main class named linked list

data_structures/linked_list/singly_linked_list.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def __repr__(self): # String representation/visualization of a Linked Lists
7979
# END represents end of the LinkedList
8080
return string_repr + "END"
8181

82-
# Indexing Support. Used to get a node at particaular position
82+
# Indexing Support. Used to get a node at particular position
8383
def __getitem__(self, index):
8484
current = self.head
8585

data_structures/stacks/postfix_evaluation.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def Solve(Postfix):
5454

5555
Stack.append(
5656
str(Opr[x](int(A), int(B)))
57-
) # evaluate the 2 values poped from stack & push result to stack
57+
) # evaluate the 2 values popped from stack & push result to stack
5858
print(
5959
x.rjust(8),
6060
("push(" + A + x + B + ")").ljust(12),

data_structures/stacks/stock_span_problem.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def calculateSpan(price, S):
2121
# Calculate span values for rest of the elements
2222
for i in range(1, n):
2323

24-
# Pop elements from stack whlie stack is not
24+
# Pop elements from stack while stack is not
2525
# empty and top of stack is smaller than price[i]
2626
while len(st) > 0 and price[st[0]] <= price[i]:
2727
st.pop()

digital_image_processing/index_calculation.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -541,7 +541,7 @@ def NDRE(self):
541541
# instantiating the class with the values
542542
#cl = indexCalculation(red=red, green=green, blue=blue, redEdge=redEdge, nir=nir)
543543
544-
# how set the values after instantiate the class cl, (for update the data or when dont
544+
# how set the values after instantiate the class cl, (for update the data or when don't
545545
# instantiating the class with the values)
546546
cl.setMatrices(red=red, green=green, blue=blue, redEdge=redEdge, nir=nir)
547547
@@ -551,8 +551,8 @@ def NDRE(self):
551551
redEdge=redEdge, nir=nir).astype(np.float64)
552552
indexValue_form2 = cl.CCCI()
553553
554-
# calculating the index with the values directly -- you can set just the values preferred --
555-
# note: the *calculation* fuction performs the function *setMatrices*
554+
# calculating the index with the values directly -- you can set just the values
555+
# preferred note: the *calculation* function performs the function *setMatrices*
556556
indexValue_form3 = cl.calculation("CCCI", red=red, green=green, blue=blue,
557557
redEdge=redEdge, nir=nir).astype(np.float64)
558558

digital_image_processing/test_digital_image_processing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def test_gen_gaussian_kernel():
4242
# canny.py
4343
def test_canny():
4444
canny_img = imread("digital_image_processing/image_data/lena_small.jpg", 0)
45-
# assert ambiguos array for all == True
45+
# assert ambiguous array for all == True
4646
assert canny_img.all()
4747
canny_array = canny.canny(canny_img)
4848
# assert canny array for at least one True

dynamic_programming/bitmask.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def CountWaysUtil(self, mask, taskno):
4242
if self.dp[mask][taskno] != -1:
4343
return self.dp[mask][taskno]
4444

45-
# Number of ways when we dont this task in the arrangement
45+
# Number of ways when we don't this task in the arrangement
4646
total_ways_util = self.CountWaysUtil(mask, taskno + 1)
4747

4848
# now assign the tasks one by one to all possible persons and recursively assign for the remaining tasks.

dynamic_programming/knapsack.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,9 @@ def knapsack_with_example_solution(W: int, wt: list, val: list):
4949
5050
W: int, the total maximum weight for the given knapsack problem.
5151
wt: list, the vector of weights for all items where wt[i] is the weight
52-
of the ith item.
52+
of the i-th item.
5353
val: list, the vector of values for all items where val[i] is the value
54-
of te ith item
54+
of the i-th item
5555
5656
Returns
5757
-------

dynamic_programming/longest_sub_array.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
"""
2-
Auther : Yvonne
2+
Author : Yvonne
33
44
This is a pure Python implementation of Dynamic Programming solution to the longest_sub_array problem.
55
+10-13
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
# python program to print all subset combination of n element in given set of r element .
1+
# Python program to print all subset combinations of n element in given set of r element.
22
# arr[] ---> Input Array
33
# data[] ---> Temporary array to store current combination
44
# start & end ---> Staring and Ending indexes in arr[]
55
# index ---> Current index in data[]
66
# r ---> Size of a combination to be printed
7-
def combinationUtil(arr, n, r, index, data, i):
7+
def combination_util(arr, n, r, index, data, i):
88
# Current combination is ready to be printed,
99
# print it
1010
if index == r:
@@ -15,29 +15,26 @@ def combinationUtil(arr, n, r, index, data, i):
1515
# When no more elements are there to put in data[]
1616
if i >= n:
1717
return
18-
# current is included, put next at next
19-
# location
18+
# current is included, put next at next location
2019
data[index] = arr[i]
21-
combinationUtil(arr, n, r, index + 1, data, i + 1)
20+
combination_util(arr, n, r, index + 1, data, i + 1)
2221
# current is excluded, replace it with
2322
# next (Note that i+1 is passed, but
2423
# index is not changed)
25-
combinationUtil(arr, n, r, index, data, i + 1)
24+
combination_util(arr, n, r, index, data, i + 1)
2625
# The main function that prints all combinations
2726
# of size r in arr[] of size n. This function
2827
# mainly uses combinationUtil()
2928

3029

31-
def printcombination(arr, n, r):
32-
# A temporary array to store all combination
33-
# one by one
30+
def print_combination(arr, n, r):
31+
# A temporary array to store all combination one by one
3432
data = [0] * r
35-
# Print all combination using temprary
36-
# array 'data[]'
37-
combinationUtil(arr, n, r, 0, data, 0)
33+
# Print all combination using temporary array 'data[]'
34+
combination_util(arr, n, r, 0, data, 0)
3835

3936

4037
# Driver function to check for above function
4138
arr = [10, 20, 30, 40, 50]
42-
printcombination(arr, len(arr), 3)
39+
print_combination(arr, len(arr), 3)
4340
# This code is contributed by Ambuj sahu
File renamed without changes.

0 commit comments

Comments
 (0)