Added Whitespace and Docstring (#924)

* Added Whitespace and Docstring

I modified the file to make Pylint happier and make the code more readable.

* Beautified Code and Added Docstring

I modified the file to make Pylint happier and make the code more readable.

* Added DOCSTRINGS, Wikipedia link, and whitespace

I added DOCSTRINGS and whitespace to make the code more readable and understandable.

* Improved Formatting

* Wrapped comments
* Fixed spelling error for `movement` variable
* Added DOCSTRINGs

* Improved Formatting

* Corrected whitespace to improve readability.
* Added docstrings.
* Made comments fit inside an 80 column layout.
This commit is contained in:
PatOnTheBack 2019-07-01 04:10:18 -04:00 committed by John Law
parent 2333f93323
commit bd4017928e
12 changed files with 154 additions and 87 deletions

View File

@ -1,6 +1,9 @@
"""Lower-Upper (LU) Decomposition."""
# lowerupper (LU) decomposition - https://en.wikipedia.org/wiki/LU_decomposition
import numpy
def LUDecompose(table):
# Table that contains our data
# Table has to be a square array so we need to check first
@ -23,6 +26,7 @@ def LUDecompose (table):
U[i][j] = table[i][j] - sum1
return L, U
if __name__ == "__main__":
matrix = numpy.array([[2, -2, 1],
[0, 1, 2],

View File

@ -1,6 +1,10 @@
"""Newton's Method."""
# Newton's Method - https://en.wikipedia.org/wiki/Newton%27s_method
def newton(function,function1,startingInt): #function is the f(x) and function1 is the f'(x)
# function is the f(x) and function1 is the f'(x)
def newton(function, function1, startingInt):
x_n = startingInt
while True:
x_n1 = x_n - function(x_n) / function1(x_n)
@ -8,11 +12,14 @@ def newton(function,function1,startingInt): #function is the f(x) and function1
return x_n1
x_n = x_n1
def f(x):
return (x**3) - (2 * x) - 5
def f1(x):
return 3 * (x**2) - 2
if __name__ == "__main__":
print(newton(f, f1, 3))

View File

@ -1,5 +1,8 @@
"""Tower of Hanoi."""
# @author willx75
# Tower of Hanoi recursion game algorithm is a game, it consists of three rods and a number of disks of different sizes, which can slide onto any rod
# Tower of Hanoi recursion game algorithm is a game, it consists of three rods
# and a number of disks of different sizes, which can slide onto any rod
import logging
@ -7,18 +10,20 @@ log = logging.getLogger()
logging.basicConfig(level=logging.DEBUG)
def Tower_Of_Hanoi(n, source, dest, by, mouvement):
def Tower_Of_Hanoi(n, source, dest, by, movement):
"""Tower of Hanoi - Move plates to different rods."""
if n == 0:
return n
elif n == 1:
mouvement += 1
# no print statement (you could make it an optional flag for printing logs)
movement += 1
# no print statement
# (you could make it an optional flag for printing logs)
logging.debug('Move the plate from', source, 'to', dest)
return mouvement
return movement
else:
mouvement = mouvement + Tower_Of_Hanoi(n-1, source, by, dest, 0)
movement = movement + Tower_Of_Hanoi(n - 1, source, by, dest, 0)
logging.debug('Move the plate from', source, 'to', dest)
mouvement = mouvement + 1 + Tower_Of_Hanoi(n-1, by, dest, source, 0)
return mouvement
movement = movement + 1 + Tower_Of_Hanoi(n - 1, by, dest, source, 0)
return movement

View File

@ -1,6 +1,10 @@
"""Absolute Value."""
def absVal(num):
"""
Function to fins absolute value of numbers.
Find the absolute value of a number.
>>absVal(-5)
5
>>absVal(0)
@ -11,8 +15,11 @@ def absVal(num):
else:
return num
def main():
"""Print absolute value of -34."""
print(absVal(-34)) # = 34
if __name__ == '__main__':
main()

View File

@ -1,4 +1,8 @@
"""Find mean of a list of numbers."""
def average(nums):
"""Find mean of a list of numbers."""
sum = 0
for x in nums:
sum += x
@ -6,8 +10,11 @@ def average(nums):
print(avg)
return avg
def main():
"""Call average module to find mean of a specific list of numbers."""
average([2, 4, 6, 8, 20, 50, 70])
if __name__ == '__main__':
main()

View File

@ -1,4 +1,10 @@
"""Find Least Common Multiple."""
# https://en.wikipedia.org/wiki/Least_common_multiple
def find_lcm(num_1, num_2):
"""Find the LCM of two numbers."""
max = num_1 if num_1 > num_2 else num_2
lcm = max
while (True):
@ -9,6 +15,7 @@ def find_lcm(num_1, num_2):
def main():
"""Use test numbers to run the find_lcm algorithm."""
num_1 = 12
num_2 = 76
print(find_lcm(num_1, num_2))

View File

@ -1,20 +1,27 @@
#!/usr/bin/env python
"""Illustrate how to implement bucket sort algorithm."""
# Author: OMKAR PATHAK
# This program will illustrate how to implement bucket sort algorithm
# Wikipedia says: Bucket sort, or bin sort, is a sorting algorithm that works by distributing the
# elements of an array into a number of buckets. Each bucket is then sorted individually, either using
# a different sorting algorithm, or by recursively applying the bucket sorting algorithm. It is a
# distribution sort, and is a cousin of radix sort in the most to least significant digit flavour.
# Bucket sort is a generalization of pigeonhole sort. Bucket sort can be implemented with comparisons
# and therefore can also be considered a comparison sort algorithm. The computational complexity estimates
# involve the number of buckets.
# Wikipedia says: Bucket sort, or bin sort, is a sorting algorithm that works
# by distributing the elements of an array into a number of buckets.
# Each bucket is then sorted individually, either using a different sorting
# algorithm, or by recursively applying the bucket sorting algorithm. It is a
# distribution sort, and is a cousin of radix sort in the most to least
# significant digit flavour.
# Bucket sort is a generalization of pigeonhole sort. Bucket sort can be
# implemented with comparisons and therefore can also be considered a
# comparison sort algorithm. The computational complexity estimates involve the
# number of buckets.
# Time Complexity of Solution:
# Best Case O(n); Average Case O(n); Worst Case O(n)
DEFAULT_BUCKET_SIZE = 5
def bucket_sort(my_list, bucket_size=DEFAULT_BUCKET_SIZE):
if len(my_list) == 0:
raise Exception("Please add some elements in the array.")
@ -24,11 +31,13 @@ def bucket_sort(my_list, bucket_size=DEFAULT_BUCKET_SIZE):
buckets = [[] for _ in range(int(bucket_count))]
for i in range(len(my_list)):
buckets[int((my_list[i] - min_value) // bucket_size)].append(my_list[i])
buckets[int((my_list[i] - min_value) // bucket_size)
].append(my_list[i])
return sorted([buckets[i][j] for i in range(len(buckets))
for j in range(len(buckets[i]))])
if __name__ == "__main__":
user_input = input('Enter numbers separated by a comma:').strip()
unsorted = [float(n) for n in user_input.split(',') if len(user_input) > 0]

View File

@ -1,9 +1,10 @@
"""Gnome Sort Algorithm."""
from __future__ import print_function
def gnome_sort(unsorted):
"""
Pure implementation of the gnome sort algorithm in Python.
"""
"""Pure implementation of the gnome sort algorithm in Python."""
if len(unsorted) <= 1:
return unsorted
@ -18,6 +19,7 @@ def gnome_sort(unsorted):
if (i == 0):
i = 1
if __name__ == '__main__':
try:
raw_input # Python 2

View File

@ -1,3 +1,5 @@
"""Test Sort Algorithms for Errors."""
from bogo_sort import bogo_sort
from bubble_sort import bubble_sort
from bucket_sort import bucket_sort
@ -36,8 +38,8 @@ TEST_CASES = [
TODO:
- Fix some broken tests in particular cases (as [] for example),
- Unify the input format: should always be function(input_collection) (no additional args)
- Unify the output format: should always be a collection instead of updating input elements
and returning None
- Unify the output format: should always be a collection instead of
updating input elements and returning None
- Rewrite some algorithms in function format (in case there is no function definition)
'''

View File

@ -1,3 +1,5 @@
"""Topological Sort."""
from __future__ import print_function
# a
# / \
@ -28,6 +30,7 @@ def topological_sort(start, visited, sort):
# return sort
return sort
if __name__ == '__main__':
sort = topological_sort('a', [], [])
print(sort)

View File

@ -1,5 +1,9 @@
# Tree_sort algorithm
# Build a BST and in order traverse.
"""
Tree_sort algorithm.
Build a BST and in order traverse.
"""
class node():
# BST data structure
@ -23,6 +27,7 @@ class node():
else:
self.val = val
def inorder(root, res):
# Recursive travesal
if root:
@ -30,6 +35,7 @@ def inorder(root, res):
res.append(root.val)
inorder(root.right, res)
def tree_sort(arr):
# Build BST
if len(arr) == 0:
@ -42,5 +48,6 @@ def tree_sort(arr):
inorder(root, res)
return res
if __name__ == '__main__':
print(tree_sort([10, 1, 3, 2, 9, 14, 13]))

View File

@ -1,14 +1,21 @@
"""
Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....
Wiggle Sort.
Given an unsorted array nums, reorder it such
that nums[0] < nums[1] > nums[2] < nums[3]....
For example:
if input numbers = [3, 5, 2, 1, 6, 4]
one possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4].
"""
def wiggle_sort(nums):
"""Perform Wiggle Sort."""
for i in range(len(nums)):
if (i % 2 == 1) == (nums[i - 1] > nums[i]):
nums[i - 1], nums[i] = nums[i], nums[i - 1]
if __name__ == '__main__':
print("Enter the array elements:\n")
array = list(map(int, input().split()))