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:
PatOnTheBack
2019-07-01 04:10:18 -04:00
committed by John Law
parent 2333f93323
commit bd4017928e
12 changed files with 154 additions and 87 deletions

View File

@ -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))

View File

@ -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)

View File

@ -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'])

View File

@ -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)

View File

@ -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]))

View File

@ -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)