Skip to content

Commit bd40179

Browse files
PatOnTheBackpoyea
authored andcommitted
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.
1 parent 2333f93 commit bd40179

File tree

12 files changed

+154
-87
lines changed

12 files changed

+154
-87
lines changed
Lines changed: 26 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,36 @@
1+
"""Lower-Upper (LU) Decomposition."""
2+
13
# lower–upper (LU) decomposition - https://en.wikipedia.org/wiki/LU_decomposition
24
import numpy
35

4-
def LUDecompose (table):
6+
7+
def LUDecompose(table):
58
# Table that contains our data
69
# Table has to be a square array so we need to check first
7-
rows,columns=numpy.shape(table)
8-
L=numpy.zeros((rows,columns))
9-
U=numpy.zeros((rows,columns))
10-
if rows!=columns:
10+
rows, columns = numpy.shape(table)
11+
L = numpy.zeros((rows, columns))
12+
U = numpy.zeros((rows, columns))
13+
if rows != columns:
1114
return []
12-
for i in range (columns):
13-
for j in range(i-1):
14-
sum=0
15-
for k in range (j-1):
16-
sum+=L[i][k]*U[k][j]
17-
L[i][j]=(table[i][j]-sum)/U[j][j]
18-
L[i][i]=1
19-
for j in range(i-1,columns):
20-
sum1=0
21-
for k in range(i-1):
22-
sum1+=L[i][k]*U[k][j]
23-
U[i][j]=table[i][j]-sum1
24-
return L,U
15+
for i in range(columns):
16+
for j in range(i - 1):
17+
sum = 0
18+
for k in range(j - 1):
19+
sum += L[i][k] * U[k][j]
20+
L[i][j] = (table[i][j] - sum) / U[j][j]
21+
L[i][i] = 1
22+
for j in range(i - 1, columns):
23+
sum1 = 0
24+
for k in range(i - 1):
25+
sum1 += L[i][k] * U[k][j]
26+
U[i][j] = table[i][j] - sum1
27+
return L, U
28+
2529

2630
if __name__ == "__main__":
27-
matrix =numpy.array([[2,-2,1],
28-
[0,1,2],
29-
[5,3,1]])
30-
L,U = LUDecompose(matrix)
31+
matrix = numpy.array([[2, -2, 1],
32+
[0, 1, 2],
33+
[5, 3, 1]])
34+
L, U = LUDecompose(matrix)
3135
print(L)
3236
print(U)

arithmetic_analysis/newton_method.py

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,25 @@
1+
"""Newton's Method."""
2+
13
# Newton's Method - https://en.wikipedia.org/wiki/Newton%27s_method
24

3-
def newton(function,function1,startingInt): #function is the f(x) and function1 is the f'(x)
4-
x_n=startingInt
5-
while True:
6-
x_n1=x_n-function(x_n)/function1(x_n)
7-
if abs(x_n-x_n1) < 10**-5:
8-
return x_n1
9-
x_n=x_n1
10-
5+
6+
# function is the f(x) and function1 is the f'(x)
7+
def newton(function, function1, startingInt):
8+
x_n = startingInt
9+
while True:
10+
x_n1 = x_n - function(x_n) / function1(x_n)
11+
if abs(x_n - x_n1) < 10**-5:
12+
return x_n1
13+
x_n = x_n1
14+
15+
1116
def f(x):
12-
return (x**3) - (2 * x) -5
17+
return (x**3) - (2 * x) - 5
18+
1319

1420
def f1(x):
15-
return 3 * (x**2) -2
21+
return 3 * (x**2) - 2
22+
1623

1724
if __name__ == "__main__":
18-
print(newton(f,f1,3))
25+
print(newton(f, f1, 3))

maths/Hanoi.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,29 @@
1+
"""Tower of Hanoi."""
2+
13
# @author willx75
2-
# 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
4+
# Tower of Hanoi recursion game algorithm is a game, it consists of three rods
5+
# and a number of disks of different sizes, which can slide onto any rod
36

47
import logging
58

69
log = logging.getLogger()
710
logging.basicConfig(level=logging.DEBUG)
811

912

10-
def Tower_Of_Hanoi(n, source, dest, by, mouvement):
13+
def Tower_Of_Hanoi(n, source, dest, by, movement):
14+
"""Tower of Hanoi - Move plates to different rods."""
1115
if n == 0:
1216
return n
1317
elif n == 1:
14-
mouvement += 1
15-
# no print statement (you could make it an optional flag for printing logs)
18+
movement += 1
19+
# no print statement
20+
# (you could make it an optional flag for printing logs)
1621
logging.debug('Move the plate from', source, 'to', dest)
17-
return mouvement
22+
return movement
1823
else:
1924

20-
mouvement = mouvement + Tower_Of_Hanoi(n-1, source, by, dest, 0)
25+
movement = movement + Tower_Of_Hanoi(n - 1, source, by, dest, 0)
2126
logging.debug('Move the plate from', source, 'to', dest)
2227

23-
mouvement = mouvement + 1 + Tower_Of_Hanoi(n-1, by, dest, source, 0)
24-
return mouvement
28+
movement = movement + 1 + Tower_Of_Hanoi(n - 1, by, dest, source, 0)
29+
return movement

maths/abs.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
1+
"""Absolute Value."""
2+
3+
14
def absVal(num):
25
"""
3-
Function to fins absolute value of numbers.
6+
Find the absolute value of a number.
7+
48
>>absVal(-5)
59
5
610
>>absVal(0)
@@ -11,8 +15,11 @@ def absVal(num):
1115
else:
1216
return num
1317

18+
1419
def main():
15-
print(absVal(-34)) # = 34
20+
"""Print absolute value of -34."""
21+
print(absVal(-34)) # = 34
22+
1623

1724
if __name__ == '__main__':
1825
main()

maths/average.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,20 @@
1+
"""Find mean of a list of numbers."""
2+
3+
14
def average(nums):
5+
"""Find mean of a list of numbers."""
26
sum = 0
37
for x in nums:
4-
sum += x
8+
sum += x
59
avg = sum / len(nums)
610
print(avg)
711
return avg
812

13+
914
def main():
10-
average([2, 4, 6, 8, 20, 50, 70])
15+
"""Call average module to find mean of a specific list of numbers."""
16+
average([2, 4, 6, 8, 20, 50, 70])
17+
1118

1219
if __name__ == '__main__':
13-
main()
20+
main()

maths/find_lcm.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1+
"""Find Least Common Multiple."""
2+
3+
# https://en.wikipedia.org/wiki/Least_common_multiple
4+
5+
16
def find_lcm(num_1, num_2):
7+
"""Find the LCM of two numbers."""
28
max = num_1 if num_1 > num_2 else num_2
39
lcm = max
410
while (True):
@@ -9,6 +15,7 @@ def find_lcm(num_1, num_2):
915

1016

1117
def main():
18+
"""Use test numbers to run the find_lcm algorithm."""
1219
num_1 = 12
1320
num_2 = 76
1421
print(find_lcm(num_1, num_2))

sorts/bucket_sort.py

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,26 @@
11
#!/usr/bin/env python
2+
3+
"""Illustrate how to implement bucket sort algorithm."""
4+
25
# Author: OMKAR PATHAK
36
# This program will illustrate how to implement bucket sort algorithm
47

5-
# Wikipedia says: Bucket sort, or bin sort, is a sorting algorithm that works by distributing the
6-
# elements of an array into a number of buckets. Each bucket is then sorted individually, either using
7-
# a different sorting algorithm, or by recursively applying the bucket sorting algorithm. It is a
8-
# distribution sort, and is a cousin of radix sort in the most to least significant digit flavour.
9-
# Bucket sort is a generalization of pigeonhole sort. Bucket sort can be implemented with comparisons
10-
# and therefore can also be considered a comparison sort algorithm. The computational complexity estimates
11-
# involve the number of buckets.
8+
# Wikipedia says: Bucket sort, or bin sort, is a sorting algorithm that works
9+
# by distributing the elements of an array into a number of buckets.
10+
# Each bucket is then sorted individually, either using a different sorting
11+
# algorithm, or by recursively applying the bucket sorting algorithm. It is a
12+
# distribution sort, and is a cousin of radix sort in the most to least
13+
# significant digit flavour.
14+
# Bucket sort is a generalization of pigeonhole sort. Bucket sort can be
15+
# implemented with comparisons and therefore can also be considered a
16+
# comparison sort algorithm. The computational complexity estimates involve the
17+
# number of buckets.
1218

1319
# Time Complexity of Solution:
1420
# Best Case O(n); Average Case O(n); Worst Case O(n)
1521

16-
DEFAULT_BUCKET_SIZE=5
22+
DEFAULT_BUCKET_SIZE = 5
23+
1724

1825
def bucket_sort(my_list, bucket_size=DEFAULT_BUCKET_SIZE):
1926
if len(my_list) == 0:
@@ -24,12 +31,14 @@ def bucket_sort(my_list, bucket_size=DEFAULT_BUCKET_SIZE):
2431
buckets = [[] for _ in range(int(bucket_count))]
2532

2633
for i in range(len(my_list)):
27-
buckets[int((my_list[i] - min_value) // bucket_size)].append(my_list[i])
34+
buckets[int((my_list[i] - min_value) // bucket_size)
35+
].append(my_list[i])
2836

2937
return sorted([buckets[i][j] for i in range(len(buckets))
30-
for j in range(len(buckets[i]))])
38+
for j in range(len(buckets[i]))])
39+
3140

3241
if __name__ == "__main__":
3342
user_input = input('Enter numbers separated by a comma:').strip()
3443
unsorted = [float(n) for n in user_input.split(',') if len(user_input) > 0]
35-
print(bucket_sort(unsorted))
44+
print(bucket_sort(unsorted))

sorts/gnome_sort.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,31 @@
1+
"""Gnome Sort Algorithm."""
2+
13
from __future__ import print_function
24

5+
36
def gnome_sort(unsorted):
4-
"""
5-
Pure implementation of the gnome sort algorithm in Python.
6-
"""
7+
"""Pure implementation of the gnome sort algorithm in Python."""
78
if len(unsorted) <= 1:
89
return unsorted
9-
10+
1011
i = 1
11-
12+
1213
while i < len(unsorted):
13-
if unsorted[i-1] <= unsorted[i]:
14+
if unsorted[i - 1] <= unsorted[i]:
1415
i += 1
1516
else:
16-
unsorted[i-1], unsorted[i] = unsorted[i], unsorted[i-1]
17+
unsorted[i - 1], unsorted[i] = unsorted[i], unsorted[i - 1]
1718
i -= 1
1819
if (i == 0):
1920
i = 1
20-
21+
22+
2123
if __name__ == '__main__':
2224
try:
2325
raw_input # Python 2
2426
except NameError:
2527
raw_input = input # Python 3
26-
28+
2729
user_input = raw_input('Enter numbers separated by a comma:\n').strip()
2830
unsorted = [int(item) for item in user_input.split(',')]
2931
gnome_sort(unsorted)

sorts/tests.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
"""Test Sort Algorithms for Errors."""
2+
13
from bogo_sort import bogo_sort
24
from bubble_sort import bubble_sort
35
from bucket_sort import bucket_sort
@@ -36,8 +38,8 @@
3638
TODO:
3739
- Fix some broken tests in particular cases (as [] for example),
3840
- Unify the input format: should always be function(input_collection) (no additional args)
39-
- Unify the output format: should always be a collection instead of updating input elements
40-
and returning None
41+
- Unify the output format: should always be a collection instead of
42+
updating input elements and returning None
4143
- Rewrite some algorithms in function format (in case there is no function definition)
4244
'''
4345

@@ -71,4 +73,4 @@
7173
for function in TEST_FUNCTIONS:
7274
for case in TEST_CASES:
7375
result = function(case['input'])
74-
assert result == case['expected'], 'Executed function: {}, {} != {}'.format(function.__name__, result, case['expected'])
76+
assert result == case['expected'], 'Executed function: {}, {} != {}'.format(function.__name__, result, case['expected'])

sorts/topological_sort.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
"""Topological Sort."""
2+
13
from __future__ import print_function
24
# a
35
# / \
@@ -28,6 +30,7 @@ def topological_sort(start, visited, sort):
2830
# return sort
2931
return sort
3032

33+
3134
if __name__ == '__main__':
3235
sort = topological_sort('a', [], [])
3336
print(sort)

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy