Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitbd40179

Browse files
PatOnTheBackpoyea
authored andcommitted
Added Whitespace and Docstring (#924)
* Added Whitespace and DocstringI modified the file to make Pylint happier and make the code more readable.* Beautified Code and Added DocstringI modified the file to make Pylint happier and make the code more readable.* Added DOCSTRINGS, Wikipedia link, and whitespaceI 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 parent2333f93 commitbd40179

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
importnumpy
35

4-
defLUDecompose (table):
6+
7+
defLUDecompose(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-
ifrows!=columns:
10+
rows,columns=numpy.shape(table)
11+
L=numpy.zeros((rows,columns))
12+
U=numpy.zeros((rows,columns))
13+
ifrows!=columns:
1114
return []
12-
foriinrange (columns):
13-
forjinrange(i-1):
14-
sum=0
15-
forkinrange (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-
forjinrange(i-1,columns):
20-
sum1=0
21-
forkinrange(i-1):
22-
sum1+=L[i][k]*U[k][j]
23-
U[i][j]=table[i][j]-sum1
24-
returnL,U
15+
foriinrange(columns):
16+
forjinrange(i-1):
17+
sum=0
18+
forkinrange(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+
forjinrange(i-1,columns):
23+
sum1=0
24+
forkinrange(i-1):
25+
sum1+=L[i][k]*U[k][j]
26+
U[i][j]=table[i][j]-sum1
27+
returnL,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)
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-
defnewton(function,function1,startingInt):#function is the f(x) and function1 is the f'(x)
4-
x_n=startingInt
5-
whileTrue:
6-
x_n1=x_n-function(x_n)/function1(x_n)
7-
ifabs(x_n-x_n1)<10**-5:
8-
returnx_n1
9-
x_n=x_n1
10-
5+
6+
# function is the f(x) and function1 is the f'(x)
7+
defnewton(function,function1,startingInt):
8+
x_n=startingInt
9+
whileTrue:
10+
x_n1=x_n-function(x_n)/function1(x_n)
11+
ifabs(x_n-x_n1)<10**-5:
12+
returnx_n1
13+
x_n=x_n1
14+
15+
1116
deff(x):
12-
return (x**3)- (2*x)-5
17+
return (x**3)- (2*x)-5
18+
1319

1420
deff1(x):
15-
return3* (x**2)-2
21+
return3* (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
importlogging
58

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

912

10-
defTower_Of_Hanoi(n,source,dest,by,mouvement):
13+
defTower_Of_Hanoi(n,source,dest,by,movement):
14+
"""Tower of Hanoi - Move plates to different rods."""
1115
ifn==0:
1216
returnn
1317
elifn==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-
returnmouvement
22+
returnmovement
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-
returnmouvement
28+
movement=movement+1+Tower_Of_Hanoi(n-1,by,dest,source,0)
29+
returnmovement

‎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
defabsVal(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
returnnum
1317

18+
1419
defmain():
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
defaverage(nums):
5+
"""Find mean of a list of numbers."""
26
sum=0
37
forxinnums:
4-
sum+=x
8+
sum+=x
59
avg=sum/len(nums)
610
print(avg)
711
returnavg
812

13+
914
defmain():
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
deffind_lcm(num_1,num_2):
7+
"""Find the LCM of two numbers."""
28
max=num_1ifnum_1>num_2elsenum_2
39
lcm=max
410
while (True):
@@ -9,6 +15,7 @@ def find_lcm(num_1, num_2):
915

1016

1117
defmain():
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
defbucket_sort(my_list,bucket_size=DEFAULT_BUCKET_SIZE):
1926
iflen(my_list)==0:
@@ -24,12 +31,14 @@ def bucket_sort(my_list, bucket_size=DEFAULT_BUCKET_SIZE):
2431
buckets= [[]for_inrange(int(bucket_count))]
2532

2633
foriinrange(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
returnsorted([buckets[i][j]foriinrange(len(buckets))
30-
forjinrange(len(buckets[i]))])
38+
forjinrange(len(buckets[i]))])
39+
3140

3241
if__name__=="__main__":
3342
user_input=input('Enter numbers separated by a comma:').strip()
3443
unsorted= [float(n)forninuser_input.split(',')iflen(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__importprint_function
24

5+
36
defgnome_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
iflen(unsorted)<=1:
89
returnunsorted
9-
10+
1011
i=1
11-
12+
1213
whilei<len(unsorted):
13-
ifunsorted[i-1]<=unsorted[i]:
14+
ifunsorted[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
exceptNameError:
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)foriteminuser_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
frombogo_sortimportbogo_sort
24
frombubble_sortimportbubble_sort
35
frombucket_sortimportbucket_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
forfunctioninTEST_FUNCTIONS:
7274
forcaseinTEST_CASES:
7375
result=function(case['input'])
74-
assertresult==case['expected'],'Executed function: {}, {} != {}'.format(function.__name__,result,case['expected'])
76+
assertresult==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__importprint_function
24
# a
35
# / \
@@ -28,6 +30,7 @@ def topological_sort(start, visited, sort):
2830
# return sort
2931
returnsort
3032

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

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp