contribution guidelines checks (#1787)

* spelling corrections

* review

* improved documentation, removed redundant variables, added testing

* added type hint

* camel case to snake case

* spelling fix

* review

* python --> Python # it is a brand name, not a snake

* explicit cast to int

* spaces in int list

* "!= None" to "is not None"

* Update comb_sort.py

* various spelling corrections in documentation & several variables naming conventions fix

* + char in file name

* import dependency - bug fix

Co-authored-by: John Law <johnlaw.po@gmail.com>
This commit is contained in:
matkosoric 2020-03-04 13:40:28 +01:00 committed by GitHub
parent 2b19e84767
commit 7f04e5cd34
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
57 changed files with 198 additions and 198 deletions

2
.gitignore vendored
View File

@ -26,7 +26,7 @@ wheels/
MANIFEST MANIFEST
# PyInstaller # PyInstaller
# Usually these files are written by a python script from a template # Usually these files are written by a Python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it. # before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest *.manifest
*.spec *.spec

View File

@ -263,7 +263,7 @@
* [Support Vector Machines](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/support_vector_machines.py) * [Support Vector Machines](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/support_vector_machines.py)
## Maths ## Maths
* [3N+1](https://github.com/TheAlgorithms/Python/blob/master/maths/3n+1.py) * [3N+1](https://github.com/TheAlgorithms/Python/blob/master/maths/3n_plus_1.py)
* [Abs](https://github.com/TheAlgorithms/Python/blob/master/maths/abs.py) * [Abs](https://github.com/TheAlgorithms/Python/blob/master/maths/abs.py)
* [Abs Max](https://github.com/TheAlgorithms/Python/blob/master/maths/abs_max.py) * [Abs Max](https://github.com/TheAlgorithms/Python/blob/master/maths/abs_max.py)
* [Abs Min](https://github.com/TheAlgorithms/Python/blob/master/maths/abs_min.py) * [Abs Min](https://github.com/TheAlgorithms/Python/blob/master/maths/abs_min.py)

View File

@ -42,7 +42,7 @@ def solve(board, row):
""" """
It creates a state space tree and calls the safe function until it receives a It creates a state space tree and calls the safe function until it receives a
False Boolean and terminates that branch and backtracks to the next False Boolean and terminates that branch and backtracks to the next
poosible solution branch. possible solution branch.
""" """
if row >= len(board): if row >= len(board):
""" """
@ -56,7 +56,7 @@ def solve(board, row):
return return
for i in range(len(board)): for i in range(len(board)):
""" """
For every row it iterates through each column to check if it is feesible to place a For every row it iterates through each column to check if it is feasible to place a
queen there. queen there.
If all the combinations for that particular branch are successful the board is If all the combinations for that particular branch are successful the board is
reinitialized for the next possible combination. reinitialized for the next possible combination.

View File

@ -65,11 +65,11 @@ class HillCipher:
encrypt_key is an NxN numpy matrix encrypt_key is an NxN numpy matrix
""" """
self.encrypt_key = self.modulus(encrypt_key) # mod36 calc's on the encrypt key self.encrypt_key = self.modulus(encrypt_key) # mod36 calc's on the encrypt key
self.checkDeterminant() # validate the determinant of the encryption key self.check_determinant() # validate the determinant of the encryption key
self.decrypt_key = None self.decrypt_key = None
self.break_key = encrypt_key.shape[0] self.break_key = encrypt_key.shape[0]
def checkDeterminant(self): def check_determinant(self):
det = round(numpy.linalg.det(self.encrypt_key)) det = round(numpy.linalg.det(self.encrypt_key))
if det < 0: if det < 0:
@ -83,7 +83,7 @@ class HillCipher:
) )
) )
def processText(self, text): def process_text(self, text):
text = list(text.upper()) text = list(text.upper())
text = [char for char in text if char in self.key_string] text = [char for char in text if char in self.key_string]
@ -94,7 +94,7 @@ class HillCipher:
return "".join(text) return "".join(text)
def encrypt(self, text): def encrypt(self, text):
text = self.processText(text.upper()) text = self.process_text(text.upper())
encrypted = "" encrypted = ""
for i in range(0, len(text) - self.break_key + 1, self.break_key): for i in range(0, len(text) - self.break_key + 1, self.break_key):
@ -109,7 +109,7 @@ class HillCipher:
return encrypted return encrypted
def makeDecryptKey(self): def make_decrypt_key(self):
det = round(numpy.linalg.det(self.encrypt_key)) det = round(numpy.linalg.det(self.encrypt_key))
if det < 0: if det < 0:
@ -129,8 +129,8 @@ class HillCipher:
return self.toInt(self.modulus(inv_key)) return self.toInt(self.modulus(inv_key))
def decrypt(self, text): def decrypt(self, text):
self.decrypt_key = self.makeDecryptKey() self.decrypt_key = self.make_decrypt_key()
text = self.processText(text.upper()) text = self.process_text(text.upper())
decrypted = "" decrypted = ""
for i in range(0, len(text) - self.break_key + 1, self.break_key): for i in range(0, len(text) - self.break_key + 1, self.break_key):

View File

@ -3,7 +3,7 @@ import random
class Onepad: class Onepad:
def encrypt(self, text): def encrypt(self, text):
"""Function to encrypt text using psedo-random numbers""" """Function to encrypt text using pseudo-random numbers"""
plain = [ord(i) for i in text] plain = [ord(i) for i in text]
key = [] key = []
cipher = [] cipher = []
@ -15,7 +15,7 @@ class Onepad:
return cipher, key return cipher, key
def decrypt(self, cipher, key): def decrypt(self, cipher, key):
"""Function to decrypt text using psedo-random numbers.""" """Function to decrypt text using pseudo-random numbers."""
plain = [] plain = []
for i in range(len(key)): for i in range(len(key)):
p = int((cipher[i] - (key[i]) ** 2) / key[i]) p = int((cipher[i] - (key[i]) ** 2) / key[i])

View File

@ -28,16 +28,16 @@ class BinarySearchTree:
""" """
return str(self.root) return str(self.root)
def __reassign_nodes(self, node, newChildren): def __reassign_nodes(self, node, new_children):
if newChildren is not None: # reset its kids if new_children is not None: # reset its kids
newChildren.parent = node.parent new_children.parent = node.parent
if node.parent is not None: # reset its parent if node.parent is not None: # reset its parent
if self.is_right(node): # If it is the right children if self.is_right(node): # If it is the right children
node.parent.right = newChildren node.parent.right = new_children
else: else:
node.parent.left = newChildren node.parent.left = new_children
else: else:
self.root = newChildren self.root = new_children
def is_right(self, node): def is_right(self, node):
return node == node.parent.right return node == node.parent.right
@ -117,39 +117,39 @@ class BinarySearchTree:
elif node.right is None: # Has only left children elif node.right is None: # Has only left children
self.__reassign_nodes(node, node.left) self.__reassign_nodes(node, node.left)
else: else:
tmpNode = self.get_max( tmp_node = self.get_max(
node.left node.left
) # Gets the max value of the left branch ) # Gets the max value of the left branch
self.remove(tmpNode.value) self.remove(tmp_node.value)
node.value = ( node.value = (
tmpNode.value tmp_node.value
) # Assigns the value to the node to delete and keesp tree structure ) # Assigns the value to the node to delete and keep tree structure
def preorder_traverse(self, node): def preorder_traverse(self, node):
if node is not None: if node is not None:
yield node # Preorder Traversal yield node # Preorder Traversal
yield from self.preorder_traverse(node.left) yield from self.preorder_traverse(node.left)
yield from self.preorder_traverse(node.right) yield from self.preorder_traverse(node.right)
def traversal_tree(self, traversalFunction=None): def traversal_tree(self, traversal_function=None):
""" """
This function traversal the tree. This function traversal the tree.
You can pass a function to traversal the tree as needed by client code You can pass a function to traversal the tree as needed by client code
""" """
if traversalFunction is None: if traversal_function is None:
return self.preorder_traverse(self.root) return self.preorder_traverse(self.root)
else: else:
return traversalFunction(self.root) return traversal_function(self.root)
def postorder(curr_node): def postorder(curr_node):
""" """
postOrder (left, right, self) postOrder (left, right, self)
""" """
nodeList = list() node_list = list()
if curr_node is not None: if curr_node is not None:
nodeList = postorder(curr_node.left) + postorder(curr_node.right) + [curr_node] node_list = postorder(curr_node.left) + postorder(curr_node.right) + [curr_node]
return nodeList return node_list
def binary_search_tree(): def binary_search_tree():

View File

@ -82,7 +82,7 @@ def binary_tree_count(node_count: int) -> int:
""" """
Return the number of possible of binary trees. Return the number of possible of binary trees.
:param n: number of nodes :param n: number of nodes
:return: Number of possilble binary trees :return: Number of possible binary trees
>>> binary_tree_count(5) >>> binary_tree_count(5)
5040 5040

View File

@ -21,7 +21,7 @@ class _DoublyLinkedBase:
def has_next_and_prev(self): def has_next_and_prev(self):
return " Prev -> {0}, Next -> {1}".format( return " Prev -> {0}, Next -> {1}".format(
self._prev != None, self._next != None self._prev is not None, self._next is not None
) )
def __init__(self): def __init__(self):

View File

@ -62,7 +62,7 @@ class LinkedList: # making main class named linked list
def display(self): # Prints contents of the list def display(self): # Prints contents of the list
current = self.head current = self.head
while current != None: while current is not None:
current.displayLink() current.displayLink()
current = current.next current = current.next
print() print()

View File

@ -1,4 +1,4 @@
"""Queue represented by a python list""" """Queue represented by a Python list"""
class Queue: class Queue:

View File

@ -2,7 +2,7 @@
Changing contrast with PIL Changing contrast with PIL
This algorithm is used in This algorithm is used in
https://noivce.pythonanywhere.com/ python web app. https://noivce.pythonanywhere.com/ Python web app.
python/black: True python/black: True
flake8 : True flake8 : True

View File

@ -344,19 +344,19 @@ def convex_hull_recursive(points):
right_most_point = points[n - 1] right_most_point = points[n - 1]
convex_set = {left_most_point, right_most_point} convex_set = {left_most_point, right_most_point}
upperhull = [] upper_hull = []
lowerhull = [] lower_hull = []
for i in range(1, n - 1): for i in range(1, n - 1):
det = _det(left_most_point, right_most_point, points[i]) det = _det(left_most_point, right_most_point, points[i])
if det > 0: if det > 0:
upperhull.append(points[i]) upper_hull.append(points[i])
elif det < 0: elif det < 0:
lowerhull.append(points[i]) lower_hull.append(points[i])
_construct_hull(upperhull, left_most_point, right_most_point, convex_set) _construct_hull(upper_hull, left_most_point, right_most_point, convex_set)
_construct_hull(lowerhull, right_most_point, left_most_point, convex_set) _construct_hull(lower_hull, right_most_point, left_most_point, convex_set)
return sorted(convex_set) return sorted(convex_set)

View File

@ -1,6 +1,6 @@
""" """
This is a python implementation for questions involving task assignments between people. This is a Python implementation for questions involving task assignments between people.
Here Bitmasking and DP are used for solving this. Here Bitmasking and DP are used for solving this.
Question :- Question :-
@ -25,41 +25,41 @@ class AssignmentUsingBitmask:
self.task = defaultdict(list) # stores the list of persons for each task self.task = defaultdict(list) # stores the list of persons for each task
# finalmask is used to check if all persons are included by setting all bits to 1 # final_mask is used to check if all persons are included by setting all bits to 1
self.finalmask = (1 << len(task_performed)) - 1 self.final_mask = (1 << len(task_performed)) - 1
def CountWaysUtil(self, mask, taskno): def CountWaysUtil(self, mask, task_no):
# if mask == self.finalmask all persons are distributed tasks, return 1 # if mask == self.finalmask all persons are distributed tasks, return 1
if mask == self.finalmask: if mask == self.final_mask:
return 1 return 1
# if not everyone gets the task and no more tasks are available, return 0 # if not everyone gets the task and no more tasks are available, return 0
if taskno > self.total_tasks: if task_no > self.total_tasks:
return 0 return 0
# if case already considered # if case already considered
if self.dp[mask][taskno] != -1: if self.dp[mask][task_no] != -1:
return self.dp[mask][taskno] return self.dp[mask][task_no]
# Number of ways when we don't this task in the arrangement # Number of ways when we don't this task in the arrangement
total_ways_util = self.CountWaysUtil(mask, taskno + 1) total_ways_util = self.CountWaysUtil(mask, task_no + 1)
# now assign the tasks one by one to all possible persons and recursively assign for the remaining tasks. # now assign the tasks one by one to all possible persons and recursively assign for the remaining tasks.
if taskno in self.task: if task_no in self.task:
for p in self.task[taskno]: for p in self.task[task_no]:
# if p is already given a task # if p is already given a task
if mask & (1 << p): if mask & (1 << p):
continue continue
# assign this task to p and change the mask value. And recursively assign tasks with the new mask value. # assign this task to p and change the mask value. And recursively assign tasks with the new mask value.
total_ways_util += self.CountWaysUtil(mask | (1 << p), taskno + 1) total_ways_util += self.CountWaysUtil(mask | (1 << p), task_no + 1)
# save the value. # save the value.
self.dp[mask][taskno] = total_ways_util self.dp[mask][task_no] = total_ways_util
return self.dp[mask][taskno] return self.dp[mask][task_no]
def countNoOfWays(self, task_performed): def countNoOfWays(self, task_performed):

View File

@ -28,7 +28,7 @@ class Fibonacci:
[0, 1, 1, 2, 3, 5] [0, 1, 1, 2, 3, 5]
[] []
""" """
if sequence_no != None: if sequence_no is not None:
if sequence_no < len(self.fib_array): if sequence_no < len(self.fib_array):
return print(self.fib_array[: sequence_no + 1]) return print(self.fib_array[: sequence_no + 1])
else: else:

View File

@ -11,7 +11,7 @@ import skfuzzy as fuzz
if __name__ == "__main__": if __name__ == "__main__":
# Create universe of discourse in python using linspace () # Create universe of discourse in Python using linspace ()
X = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) X = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False)
# Create two fuzzy sets by defining any membership function (trapmf(), gbellmf(),gaussmf(), etc). # Create two fuzzy sets by defining any membership function (trapmf(), gbellmf(),gaussmf(), etc).

View File

@ -8,7 +8,7 @@ def printDist(dist, V):
def BellmanFord(graph: List[Dict[str, int]], V: int, E: int, src: int) -> int: def BellmanFord(graph: List[Dict[str, int]], V: int, E: int, src: int) -> int:
r""" """
Returns shortest paths from a vertex src to all Returns shortest paths from a vertex src to all
other vertices. other vertices.
""" """

View File

@ -3,7 +3,7 @@ import random as rand
import math as math import math as math
import time import time
# the dfault weight is 1 if not assigned but all the implementation is weighted # the default weight is 1 if not assigned but all the implementation is weighted
class DirectedGraph: class DirectedGraph:

View File

@ -6,13 +6,13 @@ def PrimsAlgorithm(l):
nodePosition = [] nodePosition = []
def getPosition(vertex): def get_position(vertex):
return nodePosition[vertex] return nodePosition[vertex]
def setPosition(vertex, pos): def set_position(vertex, pos):
nodePosition[vertex] = pos nodePosition[vertex] = pos
def topToBottom(heap, start, size, positions): def top_to_bottom(heap, start, size, positions):
if start > size // 2 - 1: if start > size // 2 - 1:
return return
else: else:
@ -28,14 +28,14 @@ def PrimsAlgorithm(l):
heap[m], positions[m] = heap[start], positions[start] heap[m], positions[m] = heap[start], positions[start]
heap[start], positions[start] = temp, temp1 heap[start], positions[start] = temp, temp1
temp = getPosition(positions[m]) temp = get_position(positions[m])
setPosition(positions[m], getPosition(positions[start])) set_position(positions[m], get_position(positions[start]))
setPosition(positions[start], temp) set_position(positions[start], temp)
topToBottom(heap, m, size, positions) top_to_bottom(heap, m, size, positions)
# Update function if value of any node in min-heap decreases # Update function if value of any node in min-heap decreases
def bottomToTop(val, index, heap, position): def bottom_to_top(val, index, heap, position):
temp = position[index] temp = position[index]
while index != 0: while index != 0:
@ -47,27 +47,27 @@ def PrimsAlgorithm(l):
if val < heap[parent]: if val < heap[parent]:
heap[index] = heap[parent] heap[index] = heap[parent]
position[index] = position[parent] position[index] = position[parent]
setPosition(position[parent], index) set_position(position[parent], index)
else: else:
heap[index] = val heap[index] = val
position[index] = temp position[index] = temp
setPosition(temp, index) set_position(temp, index)
break break
index = parent index = parent
else: else:
heap[0] = val heap[0] = val
position[0] = temp position[0] = temp
setPosition(temp, 0) set_position(temp, 0)
def heapify(heap, positions): def heapify(heap, positions):
start = len(heap) // 2 - 1 start = len(heap) // 2 - 1
for i in range(start, -1, -1): for i in range(start, -1, -1):
topToBottom(heap, i, len(heap), positions) top_to_bottom(heap, i, len(heap), positions)
def deleteMinimum(heap, positions): def deleteMinimum(heap, positions):
temp = positions[0] temp = positions[0]
heap[0] = sys.maxsize heap[0] = sys.maxsize
topToBottom(heap, 0, len(heap), positions) top_to_bottom(heap, 0, len(heap), positions)
return temp return temp
visited = [0 for i in range(len(l))] visited = [0 for i in range(len(l))]
@ -96,9 +96,9 @@ def PrimsAlgorithm(l):
TreeEdges.append((Nbr_TV[vertex], vertex)) TreeEdges.append((Nbr_TV[vertex], vertex))
visited[vertex] = 1 visited[vertex] = 1
for v in l[vertex]: for v in l[vertex]:
if visited[v[0]] == 0 and v[1] < Distance_TV[getPosition(v[0])]: if visited[v[0]] == 0 and v[1] < Distance_TV[get_position(v[0])]:
Distance_TV[getPosition(v[0])] = v[1] Distance_TV[get_position(v[0])] = v[1]
bottomToTop(v[1], getPosition(v[0]), Distance_TV, Positions) bottom_to_top(v[1], get_position(v[0]), Distance_TV, Positions)
Nbr_TV[v[0]] = vertex Nbr_TV[v[0]] = vertex
return TreeEdges return TreeEdges

View File

@ -52,25 +52,25 @@ class PriorityQueue:
return (priority, item) return (priority, item)
def consistent_hueristic(P, goal): def consistent_heuristic(P, goal):
# euclidean distance # euclidean distance
a = np.array(P) a = np.array(P)
b = np.array(goal) b = np.array(goal)
return np.linalg.norm(a - b) return np.linalg.norm(a - b)
def hueristic_2(P, goal): def heuristic_2(P, goal):
# integer division by time variable # integer division by time variable
return consistent_hueristic(P, goal) // t return consistent_heuristic(P, goal) // t
def hueristic_1(P, goal): def heuristic_1(P, goal):
# manhattan distance # manhattan distance
return abs(P[0] - goal[0]) + abs(P[1] - goal[1]) return abs(P[0] - goal[0]) + abs(P[1] - goal[1])
def key(start, i, goal, g_function): def key(start, i, goal, g_function):
ans = g_function[start] + W1 * hueristics[i](start, goal) ans = g_function[start] + W1 * heuristics[i](start, goal)
return ans return ans
@ -134,7 +134,7 @@ def expand_state(
open_list, open_list,
back_pointer, back_pointer,
): ):
for itera in range(n_hueristic): for itera in range(n_heuristic):
open_list[itera].remove_element(s) open_list[itera].remove_element(s)
# print("s", s) # print("s", s)
# print("j", j) # print("j", j)
@ -158,30 +158,24 @@ def expand_state(
if neighbours not in close_list_anchor: if neighbours not in close_list_anchor:
open_list[0].put(neighbours, key(neighbours, 0, goal, g_function)) open_list[0].put(neighbours, key(neighbours, 0, goal, g_function))
if neighbours not in close_list_inad: if neighbours not in close_list_inad:
for var in range(1, n_hueristic): for var in range(1, n_heuristic):
if key(neighbours, var, goal, g_function) <= W2 * key( if key(neighbours, var, goal, g_function) <= W2 * key(
neighbours, 0, goal, g_function neighbours, 0, goal, g_function
): ):
# print("why not plssssssssss")
open_list[j].put( open_list[j].put(
neighbours, key(neighbours, var, goal, g_function) neighbours, key(neighbours, var, goal, g_function)
) )
# print
def make_common_ground(): def make_common_ground():
some_list = [] some_list = []
# block 1
for x in range(1, 5): for x in range(1, 5):
for y in range(1, 6): for y in range(1, 6):
some_list.append((x, y)) some_list.append((x, y))
# line
for x in range(15, 20): for x in range(15, 20):
some_list.append((x, 17)) some_list.append((x, 17))
# block 2 big
for x in range(10, 19): for x in range(10, 19):
for y in range(1, 15): for y in range(1, 15):
some_list.append((x, y)) some_list.append((x, y))
@ -196,7 +190,7 @@ def make_common_ground():
return some_list return some_list
hueristics = {0: consistent_hueristic, 1: hueristic_1, 2: hueristic_2} heuristics = {0: consistent_heuristic, 1: heuristic_1, 2: heuristic_2}
blocks_blk = [ blocks_blk = [
(0, 1), (0, 1),
@ -229,7 +223,7 @@ blocks = blocks_blk
W1 = 1 W1 = 1
W2 = 1 W2 = 1
n = 20 n = 20
n_hueristic = 3 # one consistent and two other inconsistent n_heuristic = 3 # one consistent and two other inconsistent
# start and end destination # start and end destination
start = (0, 0) start = (0, 0)
@ -238,26 +232,24 @@ goal = (n - 1, n - 1)
t = 1 t = 1
def multi_a_star(start, goal, n_hueristic): def multi_a_star(start, goal, n_heuristic):
g_function = {start: 0, goal: float("inf")} g_function = {start: 0, goal: float("inf")}
back_pointer = {start: -1, goal: -1} back_pointer = {start: -1, goal: -1}
open_list = [] open_list = []
visited = set() visited = set()
for i in range(n_hueristic): for i in range(n_heuristic):
open_list.append(PriorityQueue()) open_list.append(PriorityQueue())
open_list[i].put(start, key(start, i, goal, g_function)) open_list[i].put(start, key(start, i, goal, g_function))
close_list_anchor = [] close_list_anchor = []
close_list_inad = [] close_list_inad = []
while open_list[0].minkey() < float("inf"): while open_list[0].minkey() < float("inf"):
for i in range(1, n_hueristic): for i in range(1, n_heuristic):
# print("i", i)
# print(open_list[0].minkey(), open_list[i].minkey()) # print(open_list[0].minkey(), open_list[i].minkey())
if open_list[i].minkey() <= W2 * open_list[0].minkey(): if open_list[i].minkey() <= W2 * open_list[0].minkey():
global t global t
t += 1 t += 1
# print("less prio")
if g_function[goal] <= open_list[i].minkey(): if g_function[goal] <= open_list[i].minkey():
if g_function[goal] < float("inf"): if g_function[goal] < float("inf"):
do_something(back_pointer, goal, start) do_something(back_pointer, goal, start)
@ -276,12 +268,10 @@ def multi_a_star(start, goal, n_hueristic):
) )
close_list_inad.append(get_s) close_list_inad.append(get_s)
else: else:
# print("more prio")
if g_function[goal] <= open_list[0].minkey(): if g_function[goal] <= open_list[0].minkey():
if g_function[goal] < float("inf"): if g_function[goal] < float("inf"):
do_something(back_pointer, goal, start) do_something(back_pointer, goal, start)
else: else:
# print("hoolla")
get_s = open_list[0].top_show() get_s = open_list[0].top_show()
visited.add(get_s) visited.add(get_s)
expand_state( expand_state(
@ -319,4 +309,4 @@ def multi_a_star(start, goal, n_hueristic):
if __name__ == "__main__": if __name__ == "__main__":
multi_a_star(start, goal, n_hueristic) multi_a_star(start, goal, n_heuristic)

View File

@ -121,7 +121,7 @@ def emitterConverter(sizePar, data):
# counter to control the loop reading # counter to control the loop reading
contLoop = 0 contLoop = 0
for x in dataOrd: for x in dataOrd:
if x != None: if x is not None:
try: try:
aux = (binPos[contLoop])[-1 * (bp)] aux = (binPos[contLoop])[-1 * (bp)]
except IndexError: except IndexError:
@ -224,7 +224,7 @@ def receptorConverter(sizePar, data):
# Counter to control loop reading # Counter to control loop reading
contLoop = 0 contLoop = 0
for x in dataOrd: for x in dataOrd:
if x != None: if x is not None:
try: try:
aux = (binPos[contLoop])[-1 * (bp)] aux = (binPos[contLoop])[-1 * (bp)]
except IndexError: except IndexError:

View File

@ -1,10 +1,10 @@
""" """
Linear regression is the most basic type of regression commonly used for Linear regression is the most basic type of regression commonly used for
predictive analysis. The idea is pretty simple, we have a dataset and we have predictive analysis. The idea is pretty simple: we have a dataset and we have
a feature's associated with it. The Features should be choose very cautiously features associated with it. Features should be chosen very cautiously
as they determine, how much our model will be able to make future predictions. as they determine how much our model will be able to make future predictions.
We try to set these Feature weights, over many iterations, so that they best We try to set the weight of these features, over many iterations, so that they best
fits our dataset. In this particular code, i had used a CSGO dataset (ADR vs fit our dataset. In this particular code, I had used a CSGO dataset (ADR vs
Rating). We try to best fit a line through dataset and estimate the parameters. Rating). We try to best fit a line through dataset and estimate the parameters.
""" """
import requests import requests

View File

@ -3,7 +3,7 @@ from typing import Tuple, List
def n31(a: int) -> Tuple[List[int], int]: def n31(a: int) -> Tuple[List[int], int]:
""" """
Returns the Collatz sequence and its length of any postiver integer. Returns the Collatz sequence and its length of any positive integer.
>>> n31(4) >>> n31(4)
([4, 2, 1], 3) ([4, 2, 1], 3)
""" """

View File

@ -14,7 +14,7 @@ def mode(input_list): # Defining function "mode."
>>> mode(input_list) == statistics.mode(input_list) >>> mode(input_list) == statistics.mode(input_list)
True True
""" """
# Copying inputlist to check with the index number later. # Copying input_list to check with the index number later.
check_list = input_list.copy() check_list = input_list.copy()
result = list() # Empty list to store the counts of elements in input_list result = list() # Empty list to store the counts of elements in input_list
for x in input_list: for x in input_list:

View File

@ -63,7 +63,7 @@ def sum_of_divisors(n: int) -> int:
def euler_phi(n: int) -> int: def euler_phi(n: int) -> int:
"""Calculte Euler's Phi Function. """Calculate Euler's Phi Function.
>>> euler_phi(100) >>> euler_phi(100)
40 40
""" """

View File

@ -1,7 +1,7 @@
import numpy as np import numpy as np
def explicit_euler(ode_func, y0, x0, stepsize, x_end): def explicit_euler(ode_func, y0, x0, step_size, x_end):
""" """
Calculate numeric solution at each step to an ODE using Euler's Method Calculate numeric solution at each step to an ODE using Euler's Method
@ -22,14 +22,14 @@ def explicit_euler(ode_func, y0, x0, stepsize, x_end):
>>> y[-1] >>> y[-1]
144.77277243257308 144.77277243257308
""" """
N = int(np.ceil((x_end - x0) / stepsize)) N = int(np.ceil((x_end - x0) / step_size))
y = np.zeros((N + 1,)) y = np.zeros((N + 1,))
y[0] = y0 y[0] = y0
x = x0 x = x0
for k in range(N): for k in range(N):
y[k + 1] = y[k] + stepsize * ode_func(x, y[k]) y[k + 1] = y[k] + step_size * ode_func(x, y[k])
x += stepsize x += step_size
return y return y

View File

@ -26,5 +26,5 @@ def factorial(n: int) -> int:
if __name__ == "__main__": if __name__ == "__main__":
n = int(input("Enter a positivve integer: ").strip() or 0) n = int(input("Enter a positive integer: ").strip() or 0)
print(f"factorial{n} is {factorial(n)}") print(f"factorial{n} is {factorial(n)}")

View File

@ -16,8 +16,8 @@ for word in word_list:
word_bysig[signature(word)].append(word) word_bysig[signature(word)].append(word)
def anagram(myword): def anagram(my_word):
return word_bysig[signature(myword)] return word_bysig[signature(my_word)]
print("finding anagrams...") print("finding anagrams...")

View File

@ -26,10 +26,10 @@ class Trie:
result = [] result = []
for c, v in d.items(): for c, v in d.items():
if c == END: if c == END:
subresult = [" "] sub_result = [" "]
else: else:
subresult = [c + s for s in self._elements(v)] sub_result = [c + s for s in self._elements(v)]
result.extend(subresult) result.extend(sub_result)
return tuple(result) return tuple(result)

View File

@ -7,12 +7,12 @@ wikipedia/Fischer-Yates-Shuffle.
import random import random
def FYshuffle(LIST): def FYshuffle(list):
for i in range(len(LIST)): for i in range(len(list)):
a = random.randint(0, len(LIST) - 1) a = random.randint(0, len(list) - 1)
b = random.randint(0, len(LIST) - 1) b = random.randint(0, len(list) - 1)
LIST[a], LIST[b] = LIST[b], LIST[a] list[a], list[b] = list[b], list[a]
return LIST return list
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -1,4 +1,4 @@
# Python program for generating diamond pattern in python 3.7+ # Python program for generating diamond pattern in Python 3.7+
# Function to print upper half of diamond (pyramid) # Function to print upper half of diamond (pyramid)
def floyd(n): def floyd(n):

View File

@ -3,7 +3,7 @@ Created on Thu Oct 5 16:44:23 2017
@author: Christian Bender @author: Christian Bender
This python library contains some useful functions to deal with This Python library contains some useful functions to deal with
prime numbers and whole numbers. prime numbers and whole numbers.
Overview: Overview:

View File

@ -20,7 +20,7 @@ def solution(n):
39893 39893
""" """
answer = 0 answer = 0
for i in range(999, 99, -1): # 3 digit nimbers range from 999 down to 100 for i in range(999, 99, -1): # 3 digit numbers range from 999 down to 100
for j in range(999, 99, -1): for j in range(999, 99, -1):
t = str(i * j) t = str(i * j)
if t == t[::-1] and i * j < n: if t == t[::-1] and i * j < n:

View File

@ -8,7 +8,7 @@ We can see that the 6th prime is 13. What is the Nth prime number?
from math import sqrt from math import sqrt
def isprime(n): def is_prime(n):
if n == 2: if n == 2:
return True return True
elif n % 2 == 0: elif n % 2 == 0:
@ -41,11 +41,11 @@ def solution(n):
j = 1 j = 1
while i != n and j < 3: while i != n and j < 3:
j += 1 j += 1
if isprime(j): if is_prime(j):
i += 1 i += 1
while i != n: while i != n:
j += 2 j += 2
if isprime(j): if is_prime(j):
i += 1 i += 1
return j return j

View File

@ -52,10 +52,10 @@ def next_term(a_i, k, i, n):
sub_memo = memo.get(ds_b) sub_memo = memo.get(ds_b)
if sub_memo != None: if sub_memo is not None:
jumps = sub_memo.get(c) jumps = sub_memo.get(c)
if jumps != None and len(jumps) > 0: if jumps is not None and len(jumps) > 0:
# find and make the largest jump without going over # find and make the largest jump without going over
max_jump = -1 max_jump = -1
for _k in range(len(jumps) - 1, -1, -1): for _k in range(len(jumps) - 1, -1, -1):

View File

@ -6,14 +6,14 @@ from typing import Iterator
URL_BASE = "https://github.com/TheAlgorithms/Python/blob/master" URL_BASE = "https://github.com/TheAlgorithms/Python/blob/master"
def good_filepaths(top_dir: str = ".") -> Iterator[str]: def good_file_paths(top_dir: str = ".") -> Iterator[str]:
for dirpath, dirnames, filenames in os.walk(top_dir): for dir_path, dir_names, filenames in os.walk(top_dir):
dirnames[:] = [d for d in dirnames if d != "scripts" and d[0] not in "._"] dir_names[:] = [d for d in dir_names if d != "scripts" and d[0] not in "._"]
for filename in filenames: for filename in filenames:
if filename == "__init__.py": if filename == "__init__.py":
continue continue
if os.path.splitext(filename)[1] in (".py", ".ipynb"): if os.path.splitext(filename)[1] in (".py", ".ipynb"):
yield os.path.join(dirpath, filename).lstrip("./") yield os.path.join(dir_path, filename).lstrip("./")
def md_prefix(i): def md_prefix(i):
@ -31,7 +31,7 @@ def print_path(old_path: str, new_path: str) -> str:
def print_directory_md(top_dir: str = ".") -> None: def print_directory_md(top_dir: str = ".") -> None:
old_path = "" old_path = ""
for filepath in sorted(good_filepaths()): for filepath in sorted(good_file_paths()):
filepath, filename = os.path.split(filepath) filepath, filename = os.path.split(filepath)
if filepath != old_path: if filepath != old_path:
old_path = print_path(old_path, filepath) old_path = print_path(old_path, filepath)

View File

@ -1,10 +1,10 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import os import os
from build_directory_md import good_filepaths from build_directory_md import good_file_paths
filepaths = list(good_filepaths()) filepaths = list(good_file_paths())
assert filepaths, "good_filepaths() failed!" assert filepaths, "good_file_paths() failed!"
upper_files = [file for file in filepaths if file != file.lower()] upper_files = [file for file in filepaths if file != file.lower()]

View File

@ -1,5 +1,5 @@
""" """
This is pure python implementation of binary search algorithms This is pure Python implementation of binary search algorithms
For doctests run following command: For doctests run following command:
python -m doctest -v binary_search.py python -m doctest -v binary_search.py

View File

@ -1,5 +1,5 @@
""" """
This is pure python implementation of interpolation search algorithm This is pure Python implementation of interpolation search algorithm
""" """

View File

@ -1,5 +1,5 @@
""" """
This is pure python implementation of linear search algorithm This is pure Python implementation of linear search algorithm
For doctests run following command: For doctests run following command:
python -m doctest -v linear_search.py python -m doctest -v linear_search.py

View File

@ -1,5 +1,5 @@
""" """
This is pure python implementation of sentinel linear search algorithm This is pure Python implementation of sentinel linear search algorithm
For doctests run following command: For doctests run following command:
python -m doctest -v sentinel_linear_search.py python -m doctest -v sentinel_linear_search.py

View File

@ -66,15 +66,15 @@ def simulated_annealing(
if change > 0: # improves the solution if change > 0: # improves the solution
next_state = picked_neighbor next_state = picked_neighbor
else: else:
probabililty = (math.e) ** ( probability = (math.e) ** (
change / current_temp change / current_temp
) # probability generation function ) # probability generation function
if random.random() < probabililty: # random number within probability if random.random() < probability: # random number within probability
next_state = picked_neighbor next_state = picked_neighbor
current_temp = current_temp - (current_temp * rate_of_decrease) current_temp = current_temp - (current_temp * rate_of_decrease)
if current_temp < threshold_temp or next_state is None: if current_temp < threshold_temp or next_state is None:
# temperature below threshold, or could not find a suitaable neighbor # temperature below threshold, or could not find a suitable neighbor
search_end = True search_end = True
else: else:
current_state = next_state current_state = next_state

View File

@ -1,5 +1,5 @@
""" """
This is pure python implementation of Tabu search algorithm for a Travelling Salesman Problem, that the distances This is pure Python implementation of Tabu search algorithm for a Travelling Salesman Problem, that the distances
between the cities are symmetric (the distance between city 'a' and city 'b' is the same between city 'b' and city 'a'). between the cities are symmetric (the distance between city 'a' and city 'b' is the same between city 'b' and city 'a').
The TSP can be represented into a graph. The cities are represented by nodes and the distance between them is The TSP can be represented into a graph. The cities are represented by nodes and the distance between them is
represented by the weight of the ark between the nodes. represented by the weight of the ark between the nodes.

View File

@ -14,36 +14,36 @@ def compAndSwap(a, i, j, dire):
# if dir = 1, and in descending order otherwise (means dir=0). # if dir = 1, and in descending order otherwise (means dir=0).
# The sequence to be sorted starts at index position low, # The sequence to be sorted starts at index position low,
# the parameter cnt is the number of elements to be sorted. # the parameter cnt is the number of elements to be sorted.
def bitonicMerge(a, low, cnt, dire): def bitonic_merge(a, low, cnt, dire):
if cnt > 1: if cnt > 1:
k = int(cnt / 2) k = int(cnt / 2)
for i in range(low, low + k): for i in range(low, low + k):
compAndSwap(a, i, i + k, dire) compAndSwap(a, i, i + k, dire)
bitonicMerge(a, low, k, dire) bitonic_merge(a, low, k, dire)
bitonicMerge(a, low + k, k, dire) bitonic_merge(a, low + k, k, dire)
# This function first produces a bitonic sequence by recursively # This function first produces a bitonic sequence by recursively
# sorting its two halves in opposite sorting orders, and then # sorting its two halves in opposite sorting orders, and then
# calls bitonicMerge to make them in the same order # calls bitonic_merge to make them in the same order
def bitonicSort(a, low, cnt, dire): def bitonic_sort(a, low, cnt, dire):
if cnt > 1: if cnt > 1:
k = int(cnt / 2) k = int(cnt / 2)
bitonicSort(a, low, k, 1) bitonic_sort(a, low, k, 1)
bitonicSort(a, low + k, k, 0) bitonic_sort(a, low + k, k, 0)
bitonicMerge(a, low, cnt, dire) bitonic_merge(a, low, cnt, dire)
# Caller of bitonicSort for sorting the entire array of length N # Caller of bitonic_sort for sorting the entire array of length N
# in ASCENDING order # in ASCENDING order
def sort(a, N, up): def sort(a, N, up):
bitonicSort(a, 0, N, up) bitonic_sort(a, 0, N, up)
if __name__ == "__main__": if __name__ == "__main__":
# Driver code to test above
a = [] a = []
n = int(input().strip()) n = int(input().strip())

View File

@ -1,5 +1,10 @@
""" """
This is a pure python implementation of the bogosort algorithm This is a pure Python implementation of the bogosort algorithm,
also known as permutation sort, stupid sort, slowsort, shotgun sort, or monkey sort.
Bogosort generates random permutations until it guesses the correct one.
More info on: https://en.wikipedia.org/wiki/Bogosort
For doctests run following command: For doctests run following command:
python -m doctest -v bogo_sort.py python -m doctest -v bogo_sort.py
or or
@ -25,7 +30,7 @@ def bogo_sort(collection):
[-45, -5, -2] [-45, -5, -2]
""" """
def isSorted(collection): def is_sorted(collection):
if len(collection) < 2: if len(collection) < 2:
return True return True
for i in range(len(collection) - 1): for i in range(len(collection) - 1):
@ -33,7 +38,7 @@ def bogo_sort(collection):
return False return False
return True return True
while not isSorted(collection): while not is_sorted(collection):
random.shuffle(collection) random.shuffle(collection)
return collection return collection

View File

@ -1,8 +1,13 @@
""" """
This is pure Python implementation of comb sort algorithm.
Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz Dobosiewicz in 1980. Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz Dobosiewicz in 1980.
Later it was rediscovered by Stephen Lacey and Richard Box in 1991. Comb sort improves on bubble sort. It was rediscovered by Stephen Lacey and Richard Box in 1991. Comb sort improves on bubble sort algorithm.
In bubble sort, distance (or gap) between two compared elements is always one.
Comb sort improvement is that gap can be much more than 1, in order to prevent slowing down by small values
at the end of a list.
More info on: https://en.wikipedia.org/wiki/Comb_sort
This is pure python implementation of comb sort algorithm
For doctests run following command: For doctests run following command:
python -m doctest -v comb_sort.py python -m doctest -v comb_sort.py
or or
@ -13,42 +18,44 @@ python comb_sort.py
""" """
def comb_sort(data): def comb_sort(data: list) -> list:
"""Pure implementation of comb sort algorithm in Python """Pure implementation of comb sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous :param data: mutable collection with comparable items
comparable items inside :return: the same collection in ascending order
:return: the same collection ordered by ascending
Examples: Examples:
>>> comb_sort([0, 5, 3, 2, 2]) >>> comb_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5] [0, 2, 2, 3, 5]
>>> comb_sort([]) >>> comb_sort([])
[] []
>>> comb_sort([-2, -5, -45]) >>> comb_sort([99, 45, -7, 8, 2, 0, -15, 3])
[-45, -5, -2] [-15, -7, 0, 2, 3, 8, 45, 99]
""" """
shrink_factor = 1.3 shrink_factor = 1.3
gap = len(data) gap = len(data)
swapped = True completed = False
i = 0
while not completed:
while gap > 1 or swapped:
# Update the gap value for a next comb # Update the gap value for a next comb
gap = int(float(gap) / shrink_factor) gap = int(gap / shrink_factor)
if gap <= 1:
completed = True
swapped = False index = 0
i = 0 while index + gap < len(data):
if data[index] > data[index + gap]:
while gap + i < len(data):
if data[i] > data[i + gap]:
# Swap values # Swap values
data[i], data[i + gap] = data[i + gap], data[i] data[index], data[index + gap] = data[index + gap], data[index]
swapped = True completed = False
i += 1 index += 1
return data return data
if __name__ == "__main__": if __name__ == "__main__":
import doctest
doctest.testmod()
user_input = input("Enter numbers separated by a comma:\n").strip() user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")] unsorted = [int(item) for item in user_input.split(",")]
print(comb_sort(unsorted)) print(comb_sort(unsorted))

View File

@ -1,5 +1,5 @@
""" """
This is pure python implementation of counting sort algorithm This is pure Python implementation of counting sort algorithm
For doctests run following command: For doctests run following command:
python -m doctest -v counting_sort.py python -m doctest -v counting_sort.py
or or

View File

@ -1,5 +1,5 @@
""" """
This is a pure python implementation of the heap sort algorithm. This is a pure Python implementation of the heap sort algorithm.
For doctests run following command: For doctests run following command:
python -m doctest -v heap_sort.py python -m doctest -v heap_sort.py

View File

@ -1,5 +1,5 @@
""" """
This is a pure python implementation of the insertion sort algorithm This is a pure Python implementation of the insertion sort algorithm
For doctests run following command: For doctests run following command:
python -m doctest -v insertion_sort.py python -m doctest -v insertion_sort.py

View File

@ -1,5 +1,5 @@
""" """
This is a pure python implementation of the merge sort algorithm This is a pure Python implementation of the merge sort algorithm
For doctests run following command: For doctests run following command:
python -m doctest -v merge_sort.py python -m doctest -v merge_sort.py

View File

@ -18,7 +18,7 @@ processLock = Lock()
""" """
The function run by the processes that sorts the list The function run by the processes that sorts the list
position = the position in the list the prcoess represents, used to know which position = the position in the list the process represents, used to know which
neighbor we pass our value to neighbor we pass our value to
value = the initial value at list[position] value = the initial value at list[position]
LSend, RSend = the pipes we use to send to our left and right neighbors LSend, RSend = the pipes we use to send to our left and right neighbors
@ -35,7 +35,7 @@ def oeProcess(position, value, LSend, RSend, LRcv, RRcv, resultPipe):
# find out we are sorted as it does to sort the list with this algorithm # find out we are sorted as it does to sort the list with this algorithm
for i in range(0, 10): for i in range(0, 10):
if (i + position) % 2 == 0 and RSend != None: if (i + position) % 2 == 0 and RSend is not None:
# send your value to your right neighbor # send your value to your right neighbor
processLock.acquire() processLock.acquire()
RSend[1].send(value) RSend[1].send(value)
@ -48,7 +48,7 @@ def oeProcess(position, value, LSend, RSend, LRcv, RRcv, resultPipe):
# take the lower value since you are on the left # take the lower value since you are on the left
value = min(value, temp) value = min(value, temp)
elif (i + position) % 2 != 0 and LSend != None: elif (i + position) % 2 != 0 and LSend is not None:
# send your value to your left neighbor # send your value to your left neighbor
processLock.acquire() processLock.acquire()
LSend[1].send(value) LSend[1].send(value)

View File

@ -1,5 +1,5 @@
""" """
This is a pure python implementation of the pancake sort algorithm This is a pure Python implementation of the pancake sort algorithm
For doctests run following command: For doctests run following command:
python3 -m doctest -v pancake_sort.py python3 -m doctest -v pancake_sort.py
or or

View File

@ -1,5 +1,5 @@
""" """
This is a pure python implementation of the quick sort algorithm This is a pure Python implementation of the quick sort algorithm
For doctests run following command: For doctests run following command:
python -m doctest -v quick_sort.py python -m doctest -v quick_sort.py

View File

@ -1,5 +1,5 @@
""" """
This is a pure python implementation of the selection sort algorithm This is a pure Python implementation of the selection sort algorithm
For doctests run following command: For doctests run following command:
python -m doctest -v selection_sort.py python -m doctest -v selection_sort.py

View File

@ -1,5 +1,5 @@
""" """
This is a pure python implementation of the shell sort algorithm This is a pure Python implementation of the shell sort algorithm
For doctests run following command: For doctests run following command:
python -m doctest -v shell_sort.py python -m doctest -v shell_sort.py

View File

@ -1,7 +1,7 @@
""" """
Python implementation of a sort algorithm. Python implementation of a sort algorithm.
Best Case Scenario : O(n) Best Case Scenario : O(n)
Worst Case Scenario : O(n^2) because native python functions:min, max and remove are already O(n) Worst Case Scenario : O(n^2) because native Python functions:min, max and remove are already O(n)
""" """

View File

@ -1,5 +1,5 @@
""" """
This is pure python implementation of tree traversal algorithms This is pure Python implementation of tree traversal algorithms
""" """
import queue import queue
from typing import List from typing import List

View File

@ -51,8 +51,6 @@ def get_domain_name(url: str) -> str:
# Get sub domain name (sub.example.com) # Get sub domain name (sub.example.com)
def get_sub_domain_name(url: str) -> str: def get_sub_domain_name(url: str) -> str:
""" """
This function get sub domin name
>>> get_sub_domain_name("https://a.b.c.d/e/f?g=h,i=j#k") >>> get_sub_domain_name("https://a.b.c.d/e/f?g=h,i=j#k")
'a.b.c.d' 'a.b.c.d'
>>> get_sub_domain_name("Not a URL!") >>> get_sub_domain_name("Not a URL!")