mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-04-06 22:05:54 +00:00
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:
parent
2333f93323
commit
bd4017928e
@ -1,32 +1,36 @@
|
|||||||
|
"""Lower-Upper (LU) Decomposition."""
|
||||||
|
|
||||||
# lower–upper (LU) decomposition - https://en.wikipedia.org/wiki/LU_decomposition
|
# lower–upper (LU) decomposition - https://en.wikipedia.org/wiki/LU_decomposition
|
||||||
import numpy
|
import numpy
|
||||||
|
|
||||||
def LUDecompose (table):
|
|
||||||
|
def LUDecompose(table):
|
||||||
# Table that contains our data
|
# Table that contains our data
|
||||||
# Table has to be a square array so we need to check first
|
# Table has to be a square array so we need to check first
|
||||||
rows,columns=numpy.shape(table)
|
rows, columns = numpy.shape(table)
|
||||||
L=numpy.zeros((rows,columns))
|
L = numpy.zeros((rows, columns))
|
||||||
U=numpy.zeros((rows,columns))
|
U = numpy.zeros((rows, columns))
|
||||||
if rows!=columns:
|
if rows != columns:
|
||||||
return []
|
return []
|
||||||
for i in range (columns):
|
for i in range(columns):
|
||||||
for j in range(i-1):
|
for j in range(i - 1):
|
||||||
sum=0
|
sum = 0
|
||||||
for k in range (j-1):
|
for k in range(j - 1):
|
||||||
sum+=L[i][k]*U[k][j]
|
sum += L[i][k] * U[k][j]
|
||||||
L[i][j]=(table[i][j]-sum)/U[j][j]
|
L[i][j] = (table[i][j] - sum) / U[j][j]
|
||||||
L[i][i]=1
|
L[i][i] = 1
|
||||||
for j in range(i-1,columns):
|
for j in range(i - 1, columns):
|
||||||
sum1=0
|
sum1 = 0
|
||||||
for k in range(i-1):
|
for k in range(i - 1):
|
||||||
sum1+=L[i][k]*U[k][j]
|
sum1 += L[i][k] * U[k][j]
|
||||||
U[i][j]=table[i][j]-sum1
|
U[i][j] = table[i][j] - sum1
|
||||||
return L,U
|
return L, U
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
matrix =numpy.array([[2,-2,1],
|
matrix = numpy.array([[2, -2, 1],
|
||||||
[0,1,2],
|
[0, 1, 2],
|
||||||
[5,3,1]])
|
[5, 3, 1]])
|
||||||
L,U = LUDecompose(matrix)
|
L, U = LUDecompose(matrix)
|
||||||
print(L)
|
print(L)
|
||||||
print(U)
|
print(U)
|
||||||
|
@ -1,18 +1,25 @@
|
|||||||
|
"""Newton's Method."""
|
||||||
|
|
||||||
# Newton's Method - https://en.wikipedia.org/wiki/Newton%27s_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)
|
|
||||||
x_n=startingInt
|
# function is the f(x) and function1 is the f'(x)
|
||||||
while True:
|
def newton(function, function1, startingInt):
|
||||||
x_n1=x_n-function(x_n)/function1(x_n)
|
x_n = startingInt
|
||||||
if abs(x_n-x_n1) < 10**-5:
|
while True:
|
||||||
return x_n1
|
x_n1 = x_n - function(x_n) / function1(x_n)
|
||||||
x_n=x_n1
|
if abs(x_n - x_n1) < 10**-5:
|
||||||
|
return x_n1
|
||||||
|
x_n = x_n1
|
||||||
|
|
||||||
|
|
||||||
def f(x):
|
def f(x):
|
||||||
return (x**3) - (2 * x) -5
|
return (x**3) - (2 * x) - 5
|
||||||
|
|
||||||
|
|
||||||
def f1(x):
|
def f1(x):
|
||||||
return 3 * (x**2) -2
|
return 3 * (x**2) - 2
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(newton(f,f1,3))
|
print(newton(f, f1, 3))
|
||||||
|
@ -1,5 +1,8 @@
|
|||||||
|
"""Tower of Hanoi."""
|
||||||
|
|
||||||
# @author willx75
|
# @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
|
import logging
|
||||||
|
|
||||||
@ -7,18 +10,20 @@ log = logging.getLogger()
|
|||||||
logging.basicConfig(level=logging.DEBUG)
|
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:
|
if n == 0:
|
||||||
return n
|
return n
|
||||||
elif n == 1:
|
elif n == 1:
|
||||||
mouvement += 1
|
movement += 1
|
||||||
# no print statement (you could make it an optional flag for printing logs)
|
# no print statement
|
||||||
|
# (you could make it an optional flag for printing logs)
|
||||||
logging.debug('Move the plate from', source, 'to', dest)
|
logging.debug('Move the plate from', source, 'to', dest)
|
||||||
return mouvement
|
return movement
|
||||||
else:
|
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)
|
logging.debug('Move the plate from', source, 'to', dest)
|
||||||
|
|
||||||
mouvement = mouvement + 1 + Tower_Of_Hanoi(n-1, by, dest, source, 0)
|
movement = movement + 1 + Tower_Of_Hanoi(n - 1, by, dest, source, 0)
|
||||||
return mouvement
|
return movement
|
||||||
|
11
maths/abs.py
11
maths/abs.py
@ -1,6 +1,10 @@
|
|||||||
|
"""Absolute Value."""
|
||||||
|
|
||||||
|
|
||||||
def absVal(num):
|
def absVal(num):
|
||||||
"""
|
"""
|
||||||
Function to fins absolute value of numbers.
|
Find the absolute value of a number.
|
||||||
|
|
||||||
>>absVal(-5)
|
>>absVal(-5)
|
||||||
5
|
5
|
||||||
>>absVal(0)
|
>>absVal(0)
|
||||||
@ -11,8 +15,11 @@ def absVal(num):
|
|||||||
else:
|
else:
|
||||||
return num
|
return num
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
print(absVal(-34)) # = 34
|
"""Print absolute value of -34."""
|
||||||
|
print(absVal(-34)) # = 34
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
main()
|
main()
|
||||||
|
@ -1,13 +1,20 @@
|
|||||||
|
"""Find mean of a list of numbers."""
|
||||||
|
|
||||||
|
|
||||||
def average(nums):
|
def average(nums):
|
||||||
|
"""Find mean of a list of numbers."""
|
||||||
sum = 0
|
sum = 0
|
||||||
for x in nums:
|
for x in nums:
|
||||||
sum += x
|
sum += x
|
||||||
avg = sum / len(nums)
|
avg = sum / len(nums)
|
||||||
print(avg)
|
print(avg)
|
||||||
return avg
|
return avg
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
average([2, 4, 6, 8, 20, 50, 70])
|
"""Call average module to find mean of a specific list of numbers."""
|
||||||
|
average([2, 4, 6, 8, 20, 50, 70])
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
main()
|
main()
|
||||||
|
@ -1,4 +1,10 @@
|
|||||||
|
"""Find Least Common Multiple."""
|
||||||
|
|
||||||
|
# https://en.wikipedia.org/wiki/Least_common_multiple
|
||||||
|
|
||||||
|
|
||||||
def find_lcm(num_1, num_2):
|
def find_lcm(num_1, num_2):
|
||||||
|
"""Find the LCM of two numbers."""
|
||||||
max = num_1 if num_1 > num_2 else num_2
|
max = num_1 if num_1 > num_2 else num_2
|
||||||
lcm = max
|
lcm = max
|
||||||
while (True):
|
while (True):
|
||||||
@ -9,6 +15,7 @@ def find_lcm(num_1, num_2):
|
|||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
"""Use test numbers to run the find_lcm algorithm."""
|
||||||
num_1 = 12
|
num_1 = 12
|
||||||
num_2 = 76
|
num_2 = 76
|
||||||
print(find_lcm(num_1, num_2))
|
print(find_lcm(num_1, num_2))
|
||||||
|
@ -1,19 +1,26 @@
|
|||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
"""Illustrate how to implement bucket sort algorithm."""
|
||||||
|
|
||||||
# Author: OMKAR PATHAK
|
# Author: OMKAR PATHAK
|
||||||
# This program will illustrate how to implement bucket sort algorithm
|
# 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
|
# Wikipedia says: Bucket sort, or bin sort, is a sorting algorithm that works
|
||||||
# elements of an array into a number of buckets. Each bucket is then sorted individually, either using
|
# by distributing the elements of an array into a number of buckets.
|
||||||
# a different sorting algorithm, or by recursively applying the bucket sorting algorithm. It is a
|
# Each bucket is then sorted individually, either using a different sorting
|
||||||
# distribution sort, and is a cousin of radix sort in the most to least significant digit flavour.
|
# algorithm, or by recursively applying the bucket sorting algorithm. It is a
|
||||||
# Bucket sort is a generalization of pigeonhole sort. Bucket sort can be implemented with comparisons
|
# distribution sort, and is a cousin of radix sort in the most to least
|
||||||
# and therefore can also be considered a comparison sort algorithm. The computational complexity estimates
|
# significant digit flavour.
|
||||||
# involve the number of buckets.
|
# 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:
|
# Time Complexity of Solution:
|
||||||
# Best Case O(n); Average Case O(n); Worst Case O(n)
|
# Best Case O(n); Average Case O(n); Worst Case O(n)
|
||||||
|
|
||||||
DEFAULT_BUCKET_SIZE=5
|
DEFAULT_BUCKET_SIZE = 5
|
||||||
|
|
||||||
|
|
||||||
def bucket_sort(my_list, bucket_size=DEFAULT_BUCKET_SIZE):
|
def bucket_sort(my_list, bucket_size=DEFAULT_BUCKET_SIZE):
|
||||||
if len(my_list) == 0:
|
if len(my_list) == 0:
|
||||||
@ -24,12 +31,14 @@ def bucket_sort(my_list, bucket_size=DEFAULT_BUCKET_SIZE):
|
|||||||
buckets = [[] for _ in range(int(bucket_count))]
|
buckets = [[] for _ in range(int(bucket_count))]
|
||||||
|
|
||||||
for i in range(len(my_list)):
|
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))
|
return sorted([buckets[i][j] for i in range(len(buckets))
|
||||||
for j in range(len(buckets[i]))])
|
for j in range(len(buckets[i]))])
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
user_input = input('Enter numbers separated by a comma:').strip()
|
user_input = input('Enter numbers separated by a comma:').strip()
|
||||||
unsorted = [float(n) for n in user_input.split(',') if len(user_input) > 0]
|
unsorted = [float(n) for n in user_input.split(',') if len(user_input) > 0]
|
||||||
print(bucket_sort(unsorted))
|
print(bucket_sort(unsorted))
|
||||||
|
@ -1,29 +1,31 @@
|
|||||||
|
"""Gnome Sort Algorithm."""
|
||||||
|
|
||||||
from __future__ import print_function
|
from __future__ import print_function
|
||||||
|
|
||||||
|
|
||||||
def gnome_sort(unsorted):
|
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:
|
if len(unsorted) <= 1:
|
||||||
return unsorted
|
return unsorted
|
||||||
|
|
||||||
i = 1
|
i = 1
|
||||||
|
|
||||||
while i < len(unsorted):
|
while i < len(unsorted):
|
||||||
if unsorted[i-1] <= unsorted[i]:
|
if unsorted[i - 1] <= unsorted[i]:
|
||||||
i += 1
|
i += 1
|
||||||
else:
|
else:
|
||||||
unsorted[i-1], unsorted[i] = unsorted[i], unsorted[i-1]
|
unsorted[i - 1], unsorted[i] = unsorted[i], unsorted[i - 1]
|
||||||
i -= 1
|
i -= 1
|
||||||
if (i == 0):
|
if (i == 0):
|
||||||
i = 1
|
i = 1
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
try:
|
try:
|
||||||
raw_input # Python 2
|
raw_input # Python 2
|
||||||
except NameError:
|
except NameError:
|
||||||
raw_input = input # Python 3
|
raw_input = input # Python 3
|
||||||
|
|
||||||
user_input = raw_input('Enter numbers separated by a comma:\n').strip()
|
user_input = raw_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(',')]
|
||||||
gnome_sort(unsorted)
|
gnome_sort(unsorted)
|
||||||
|
@ -1,3 +1,5 @@
|
|||||||
|
"""Test Sort Algorithms for Errors."""
|
||||||
|
|
||||||
from bogo_sort import bogo_sort
|
from bogo_sort import bogo_sort
|
||||||
from bubble_sort import bubble_sort
|
from bubble_sort import bubble_sort
|
||||||
from bucket_sort import bucket_sort
|
from bucket_sort import bucket_sort
|
||||||
@ -36,8 +38,8 @@ TEST_CASES = [
|
|||||||
TODO:
|
TODO:
|
||||||
- Fix some broken tests in particular cases (as [] for example),
|
- 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 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
|
- Unify the output format: should always be a collection instead of
|
||||||
and returning None
|
updating input elements and returning None
|
||||||
- Rewrite some algorithms in function format (in case there is no function definition)
|
- Rewrite some algorithms in function format (in case there is no function definition)
|
||||||
'''
|
'''
|
||||||
|
|
||||||
@ -71,4 +73,4 @@ TEST_FUNCTIONS = [
|
|||||||
for function in TEST_FUNCTIONS:
|
for function in TEST_FUNCTIONS:
|
||||||
for case in TEST_CASES:
|
for case in TEST_CASES:
|
||||||
result = function(case['input'])
|
result = function(case['input'])
|
||||||
assert result == case['expected'], 'Executed function: {}, {} != {}'.format(function.__name__, result, case['expected'])
|
assert result == case['expected'], 'Executed function: {}, {} != {}'.format(function.__name__, result, case['expected'])
|
||||||
|
@ -1,3 +1,5 @@
|
|||||||
|
"""Topological Sort."""
|
||||||
|
|
||||||
from __future__ import print_function
|
from __future__ import print_function
|
||||||
# a
|
# a
|
||||||
# / \
|
# / \
|
||||||
@ -28,6 +30,7 @@ def topological_sort(start, visited, sort):
|
|||||||
# return sort
|
# return sort
|
||||||
return sort
|
return sort
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
sort = topological_sort('a', [], [])
|
sort = topological_sort('a', [], [])
|
||||||
print(sort)
|
print(sort)
|
||||||
|
@ -1,14 +1,18 @@
|
|||||||
# Tree_sort algorithm
|
"""
|
||||||
# Build a BST and in order traverse.
|
Tree_sort algorithm.
|
||||||
|
|
||||||
|
Build a BST and in order traverse.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
class node():
|
class node():
|
||||||
# BST data structure
|
# BST data structure
|
||||||
def __init__(self, val):
|
def __init__(self, val):
|
||||||
self.val = val
|
self.val = val
|
||||||
self.left = None
|
self.left = None
|
||||||
self.right = None
|
self.right = None
|
||||||
|
|
||||||
def insert(self,val):
|
def insert(self, val):
|
||||||
if self.val:
|
if self.val:
|
||||||
if val < self.val:
|
if val < self.val:
|
||||||
if self.left is None:
|
if self.left is None:
|
||||||
@ -23,24 +27,27 @@ class node():
|
|||||||
else:
|
else:
|
||||||
self.val = val
|
self.val = val
|
||||||
|
|
||||||
|
|
||||||
def inorder(root, res):
|
def inorder(root, res):
|
||||||
# Recursive travesal
|
# Recursive travesal
|
||||||
if root:
|
if root:
|
||||||
inorder(root.left,res)
|
inorder(root.left, res)
|
||||||
res.append(root.val)
|
res.append(root.val)
|
||||||
inorder(root.right,res)
|
inorder(root.right, res)
|
||||||
|
|
||||||
|
|
||||||
def tree_sort(arr):
|
def tree_sort(arr):
|
||||||
# Build BST
|
# Build BST
|
||||||
if len(arr) == 0:
|
if len(arr) == 0:
|
||||||
return arr
|
return arr
|
||||||
root = node(arr[0])
|
root = node(arr[0])
|
||||||
for i in range(1,len(arr)):
|
for i in range(1, len(arr)):
|
||||||
root.insert(arr[i])
|
root.insert(arr[i])
|
||||||
# Traverse BST in order.
|
# Traverse BST in order.
|
||||||
res = []
|
res = []
|
||||||
inorder(root,res)
|
inorder(root, res)
|
||||||
return res
|
return res
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
print(tree_sort([10,1,3,2,9,14,13]))
|
print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
|
||||||
|
@ -1,17 +1,24 @@
|
|||||||
"""
|
"""
|
||||||
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:
|
For example:
|
||||||
if input numbers = [3, 5, 2, 1, 6, 4]
|
if input numbers = [3, 5, 2, 1, 6, 4]
|
||||||
one possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4].
|
one possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4].
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
def wiggle_sort(nums):
|
def wiggle_sort(nums):
|
||||||
|
"""Perform Wiggle Sort."""
|
||||||
for i in range(len(nums)):
|
for i in range(len(nums)):
|
||||||
if (i % 2 == 1) == (nums[i-1] > nums[i]):
|
if (i % 2 == 1) == (nums[i - 1] > nums[i]):
|
||||||
nums[i-1], nums[i] = nums[i], nums[i-1]
|
nums[i - 1], nums[i] = nums[i], nums[i - 1]
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
print("Enter the array elements:\n")
|
print("Enter the array elements:\n")
|
||||||
array=list(map(int,input().split()))
|
array = list(map(int, input().split()))
|
||||||
print("The unsorted array is:\n")
|
print("The unsorted array is:\n")
|
||||||
print(array)
|
print(array)
|
||||||
wiggle_sort(array)
|
wiggle_sort(array)
|
||||||
|
Loading…
x
Reference in New Issue
Block a user