Skip to content

Added Whitespace and Docstring #924

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jul 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 26 additions & 22 deletions arithmetic_analysis/lu_decomposition.py
Original file line number Diff line number Diff line change
@@ -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)
29 changes: 18 additions & 11 deletions arithmetic_analysis/newton_method.py
Original file line number Diff line number Diff line change
@@ -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))
21 changes: 13 additions & 8 deletions maths/Hanoi.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
"""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

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 changes: 9 additions & 2 deletions maths/abs.py
Original file line number Diff line number Diff line change
@@ -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)
Expand All @@ -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()
13 changes: 10 additions & 3 deletions maths/average.py
Original file line number Diff line number Diff line change
@@ -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()
7 changes: 7 additions & 0 deletions maths/find_lcm.py
Original file line number Diff line number Diff line change
@@ -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):
Expand All @@ -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))
Expand Down
31 changes: 20 additions & 11 deletions sorts/bucket_sort.py
Original file line number Diff line number Diff line change
@@ -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:
Expand All @@ -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))
20 changes: 11 additions & 9 deletions sorts/gnome_sort.py
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
8 changes: 5 additions & 3 deletions sorts/tests.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -36,8 +38,8 @@
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)
'''

Expand Down Expand Up @@ -71,4 +73,4 @@
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'])
3 changes: 3 additions & 0 deletions sorts/topological_sort.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Topological Sort."""

from __future__ import print_function
# a
# / \
Expand Down Expand Up @@ -28,6 +30,7 @@ def topological_sort(start, visited, sort):
# return sort
return sort


if __name__ == '__main__':
sort = topological_sort('a', [], [])
print(sort)
33 changes: 20 additions & 13 deletions sorts/tree_sort.py
Original file line number Diff line number Diff line change
@@ -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:
Expand All @@ -23,24 +27,27 @@ def insert(self,val):
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]))
Loading