mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +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
|
||||
import numpy
|
||||
|
||||
def LUDecompose (table):
|
||||
|
||||
def LUDecompose(table):
|
||||
# Table that contains our data
|
||||
# Table has to be a square array so we need to check first
|
||||
rows,columns=numpy.shape(table)
|
||||
L=numpy.zeros((rows,columns))
|
||||
U=numpy.zeros((rows,columns))
|
||||
if rows!=columns:
|
||||
rows, columns = numpy.shape(table)
|
||||
L = numpy.zeros((rows, columns))
|
||||
U = numpy.zeros((rows, columns))
|
||||
if rows != columns:
|
||||
return []
|
||||
for i in range (columns):
|
||||
for j in range(i-1):
|
||||
sum=0
|
||||
for k in range (j-1):
|
||||
sum+=L[i][k]*U[k][j]
|
||||
L[i][j]=(table[i][j]-sum)/U[j][j]
|
||||
L[i][i]=1
|
||||
for j in range(i-1,columns):
|
||||
sum1=0
|
||||
for k in range(i-1):
|
||||
sum1+=L[i][k]*U[k][j]
|
||||
U[i][j]=table[i][j]-sum1
|
||||
return L,U
|
||||
for i in range(columns):
|
||||
for j in range(i - 1):
|
||||
sum = 0
|
||||
for k in range(j - 1):
|
||||
sum += L[i][k] * U[k][j]
|
||||
L[i][j] = (table[i][j] - sum) / U[j][j]
|
||||
L[i][i] = 1
|
||||
for j in range(i - 1, columns):
|
||||
sum1 = 0
|
||||
for k in range(i - 1):
|
||||
sum1 += L[i][k] * U[k][j]
|
||||
U[i][j] = table[i][j] - sum1
|
||||
return L, U
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
matrix =numpy.array([[2,-2,1],
|
||||
[0,1,2],
|
||||
[5,3,1]])
|
||||
L,U = LUDecompose(matrix)
|
||||
matrix = numpy.array([[2, -2, 1],
|
||||
[0, 1, 2],
|
||||
[5, 3, 1]])
|
||||
L, U = LUDecompose(matrix)
|
||||
print(L)
|
||||
print(U)
|
||||
|
|
|
@ -1,18 +1,25 @@
|
|||
"""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)
|
||||
x_n=startingInt
|
||||
while True:
|
||||
x_n1=x_n-function(x_n)/function1(x_n)
|
||||
if abs(x_n-x_n1) < 10**-5:
|
||||
return x_n1
|
||||
x_n=x_n1
|
||||
|
||||
|
||||
# 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)
|
||||
if abs(x_n - x_n1) < 10**-5:
|
||||
return x_n1
|
||||
x_n = x_n1
|
||||
|
||||
|
||||
def f(x):
|
||||
return (x**3) - (2 * x) -5
|
||||
return (x**3) - (2 * x) - 5
|
||||
|
||||
|
||||
def f1(x):
|
||||
return 3 * (x**2) -2
|
||||
return 3 * (x**2) - 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(newton(f,f1,3))
|
||||
print(newton(f, f1, 3))
|
||||
|
|
|
@ -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
|
||||
|
|
11
maths/abs.py
11
maths/abs.py
|
@ -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(absVal(-34)) # = 34
|
||||
"""Print absolute value of -34."""
|
||||
print(absVal(-34)) # = 34
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
|
@ -1,13 +1,20 @@
|
|||
"""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
|
||||
sum += x
|
||||
avg = sum / len(nums)
|
||||
print(avg)
|
||||
return avg
|
||||
|
||||
|
||||
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__':
|
||||
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):
|
||||
"""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))
|
||||
|
|
|
@ -1,19 +1,26 @@
|
|||
#!/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
|
||||
DEFAULT_BUCKET_SIZE = 5
|
||||
|
||||
|
||||
def bucket_sort(my_list, bucket_size=DEFAULT_BUCKET_SIZE):
|
||||
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))]
|
||||
|
||||
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]))])
|
||||
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]
|
||||
print(bucket_sort(unsorted))
|
||||
print(bucket_sort(unsorted))
|
||||
|
|
|
@ -1,29 +1,31 @@
|
|||
"""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
|
||||
|
||||
|
||||
i = 1
|
||||
|
||||
|
||||
while i < len(unsorted):
|
||||
if unsorted[i-1] <= unsorted[i]:
|
||||
if unsorted[i - 1] <= unsorted[i]:
|
||||
i += 1
|
||||
else:
|
||||
unsorted[i-1], unsorted[i] = unsorted[i], unsorted[i-1]
|
||||
unsorted[i - 1], unsorted[i] = unsorted[i], unsorted[i - 1]
|
||||
i -= 1
|
||||
if (i == 0):
|
||||
i = 1
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
raw_input # Python 2
|
||||
except NameError:
|
||||
raw_input = input # Python 3
|
||||
|
||||
|
||||
user_input = raw_input('Enter numbers separated by a comma:\n').strip()
|
||||
unsorted = [int(item) for item in user_input.split(',')]
|
||||
gnome_sort(unsorted)
|
||||
|
|
|
@ -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)
|
||||
'''
|
||||
|
||||
|
@ -71,4 +73,4 @@ TEST_FUNCTIONS = [
|
|||
for function in TEST_FUNCTIONS:
|
||||
for case in TEST_CASES:
|
||||
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
|
||||
# a
|
||||
# / \
|
||||
|
@ -28,6 +30,7 @@ def topological_sort(start, visited, sort):
|
|||
# return sort
|
||||
return sort
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sort = topological_sort('a', [], [])
|
||||
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():
|
||||
# BST data structure
|
||||
def __init__(self, val):
|
||||
self.val = val
|
||||
self.left = None
|
||||
self.right = None
|
||||
|
||||
def insert(self,val):
|
||||
self.left = None
|
||||
self.right = None
|
||||
|
||||
def insert(self, val):
|
||||
if self.val:
|
||||
if val < self.val:
|
||||
if self.left is None:
|
||||
|
@ -23,24 +27,27 @@ class node():
|
|||
else:
|
||||
self.val = val
|
||||
|
||||
|
||||
def inorder(root, res):
|
||||
# Recursive travesal
|
||||
# Recursive travesal
|
||||
if root:
|
||||
inorder(root.left,res)
|
||||
inorder(root.left, res)
|
||||
res.append(root.val)
|
||||
inorder(root.right,res)
|
||||
inorder(root.right, res)
|
||||
|
||||
|
||||
def tree_sort(arr):
|
||||
# Build BST
|
||||
if len(arr) == 0:
|
||||
return arr
|
||||
root = node(arr[0])
|
||||
for i in range(1,len(arr)):
|
||||
for i in range(1, len(arr)):
|
||||
root.insert(arr[i])
|
||||
# Traverse BST in order.
|
||||
# Traverse BST in order.
|
||||
res = []
|
||||
inorder(root,res)
|
||||
inorder(root, res)
|
||||
return res
|
||||
|
||||
|
||||
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:
|
||||
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].
|
||||
"""
|
||||
|
||||
|
||||
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 (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()))
|
||||
array = list(map(int, input().split()))
|
||||
print("The unsorted array is:\n")
|
||||
print(array)
|
||||
wiggle_sort(array)
|
||||
|
|
Loading…
Reference in New Issue
Block a user