Skip to content

Commit

Permalink
update version to 0.3.0
Browse files Browse the repository at this point in the history
added new argument: -c / --compare that allows a user to display a comparison between the default sorted() method built in to python with the selected custom sort algorithm.
added new tests to reflect this new argument.
added new tests for sorter.py helper methods.
readme updated to reflect changes.
  • Loading branch information
Brett committed Apr 24, 2018
1 parent ed1ae6c commit 01e63a7
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 29 deletions.
35 changes: 19 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Sort Integers using different sorting algorithms!

## Getting Started

Check the [releases](https://github.com/becurrie/sorters-py/releases) section to find the latest working zip/tar.
Check the [releases](https://github.com/becurrie/py-sorts/releases) section to find the latest working zip/tar.

### ```python -m py_sorter [args]```

Expand All @@ -19,30 +19,33 @@ Check the [releases](https://github.com/becurrie/sorters-py/releases) section to

#### Arguments

| Argument | Description | Example |
|-----------------|------------------------------------------------------------|---------------------------------------|
| -s / --sort | type of sort being performed on list | ```python -m py_sorter -s radix``` |
| -i / --integers | provide a list of integers to be sorted | ```python -m py_sorter -i 9 34 5 4``` |
| -g / --generate | generate a random list of integers to be sorted | ```python -m py_sorter -g 1000``` |
| -l / --list | displays the original/sorted lists | ```python -m py_sorter -l``` |
| -a / --allsorts | perform sort on list with each algorithm, except bogo sort | ```python -m py_sorter -a``` |
| Argument | Description | Example |
|-----------------|--------------------------------------------------------------------------------------|---------------------------------------|
| -s / --sort | type of sort being performed on list. | ```python -m py_sorter -s radix``` |
| -i / --integers | provide a list of integers to be sorted. | ```python -m py_sorter -i 9 34 5 4``` |
| -g / --generate | generate a random list of integers to be sorted. | ```python -m py_sorter -g 1000``` |
| -l / --list | displays the original/sorted lists. | ```python -m py_sorter -l``` |
| -a / --allsorts | perform sort on list with each algorithm, except bogo sort. | ```python -m py_sorter -a``` |
| -c / --compare | display a time comparison between chosen sort and pythons default sorted() function. | ```python -m py_sorter -c``` |

## Examples

```bash
python -m py_sorter --generate 8 --sort bogo --list
python -m py_sorter -g 8 -s bogo -l -c
```

Output:

```
Shuffles: 20,222
Algorithm: [BOGO]
Shuffles: 63,257
Algorithm: [bogo]
Original List:
126, 61, 946, 874, 990, 488, 601, 787
468, 846, 801, 976, 261, 641, 72, 698
Sorted List:
61, 126, 488, 601, 787, 874, 946, 990
Time(seconds): 0.10767681062733224
72, 261, 468, 641, 698, 801, 846, 976
Time(seconds) bogo: 0.3453168464965863
Time(seconds) sorted(): 3.5189852184980275e-06
bogo was 0.3453133275113678 seconds slower.
```
***

Expand All @@ -53,8 +56,8 @@ python -m py_sorter --generate 10000 --sort quick
Output:

```
Algorithm: [QUICK]
Time(seconds): 0.026681231351216618
Algorithm: [quick]
Time(seconds): 0.02490532463518387
```

### Caution
Expand Down
53 changes: 43 additions & 10 deletions py_sorter/sorter.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""py_sorter.sorter: provides argument parsing and entry point main()."""

__version__ = "0.2.1"

"""py_sorter.sorter: provides argument parsing and entry point main().
Any calls to the sorts methods are called from here based on the -s/--sort
argument specified by the user.
"""
__version__ = "0.3.0"

import argparse
import os
Expand All @@ -17,16 +18,16 @@ def parse_args(args):
"""
parser = argparse.ArgumentParser(description='sort some integers.')

# Parser group created to take in either one argument.
# Parser group created to take in either argument. (-i or -g).
# Integers manually specified or generated on the fly.
integers_group = parser.add_mutually_exclusive_group(required=True)
integers_group.add_argument('-i', '--integers', type=int, nargs='+',
help='integer(s) being sorted.')
integers_group.add_argument('-g', '--generate', type=int,
help='generate a random list of integers to sort.')

# Specific sort algorithm or use all sort algorithms.
sorting_group = parser.add_mutually_exclusive_group(required=True)
# Specify a specific sorting algorithm.
sorting_group.add_argument('-s', '--sort', type=str,
choices=['bubble', 'bogo', 'merge', 'selection', 'quick', 'radix', 'insertion',
'insertion_recursive', 'heap'],
Expand All @@ -38,19 +39,23 @@ def parse_args(args):
parser.add_argument('-l', '--list', action='store_true',
help='displays the original and unsorted lists if present.')

# Compare argument to display the time difference compared to the default python sorted() function.
parser.add_argument('-c', '--compare', action='store_true',
help='display the difference in time compared to pythons default \'sorted()\' function.')

return parser.parse_args(args)


def print_error(args, error):
"""Print an error to the screen when a sort fails."""
print('\tAlgorithm: [%s]' % str.upper(args.sort))
print('\tAlgorithm: [%s]' % str(args.sort))
print("\terror occurred while sorting: %s" % error)
print("\t")


def print_results(args, sorted_list, time):
"""Print an original list, sorted list and time required to sort the original list."""
print('\tAlgorithm: [%s]' % str.upper(args.sort))
print('\tAlgorithm: [%s]' % str(args.sort))

# Determine whether or not the original and sorted lists will be printed
# as part of the results output.
Expand All @@ -62,11 +67,31 @@ def print_results(args, sorted_list, time):
for sorted_chunk in print_list_chunks(sorted_list, 20):
print('\t' + str(sorted_chunk)[1:-1])

# Print time required to sort list.
print('\tTime(seconds): %s' % time)
# Check for the --compare flag being present, and print out the difference
# between this results time and the default sorted() function time.
if args.compare:
print('\tTime(seconds) %s: %s' % (args.sort, time))
print('\tTime(seconds) sorted(): %s' % args.compare_time)
print('\t%s' % calculate_compare_time_difference(time, args.compare_time, args.sort))
else:
print('\tTime(seconds): %s' % time)

print('\t')


def calculate_compare_time_difference(algorithm_time, default_time, algorithm):
"""Calculate the difference between a custom algorithms time taken to sort, and
pythons sorted() function time taken to sort the same list, returns a readable string
detailing which was faster.
"""
difference = algorithm_time - default_time

if difference > 0:
return '%s was %s seconds slower.' % (algorithm, difference)
else:
return '%s was %s seconds faster.' % (algorithm, -difference)


def print_list_chunks(integer_list, n):
"""Simple helper method to print out a list in chunks. This allows
the console output to never surpass a specific width. Giving a cleaner
Expand Down Expand Up @@ -130,6 +155,14 @@ def sort(args):

# Final default_timer() method call to grab time after sort is completed.
final = timeit.default_timer()

# Check for compare flag and get the time taken for the default sorted() call on list.
if args.compare:
default_initial = timeit.default_timer()
default_list = sorted(original_list)
default_final = timeit.default_timer()
args.compare_time = default_final - default_initial

print_results(args, sorted_list, final - initial)


Expand Down
38 changes: 35 additions & 3 deletions tests/run_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@
sys.path.insert(0, os.path.abspath('..'))

from py_sorter.sorts import *
from py_sorter.sorter import parse_args
from py_sorter.sorter import parse_args, calculate_compare_time_difference


class TestParsing(unittest.TestCase):
"""Test each argument available in the parser located in the sorter.py file."""

def test_integers(self):
"""Test the optional one of: integers argument."""
parser = parse_args(['-i', '1', '3', '6', '9', '-s', 'bubble'])
Expand Down Expand Up @@ -45,10 +44,43 @@ def test_list(self):
parser = parse_args(['-g', '10', '-s', 'bubble'])
self.assertEqual(False, parser.list)

def test_compare(self):
"""Test the optional compare argument."""
parser = parse_args(['-g', '10', '-s', 'bubble', '-c'])
self.assertTrue(parser.compare)
self.assertEqual(True, parser.compare)

parser = parse_args(['-g', '10', '-s', 'bubble'])
self.assertEqual(False, parser.compare)


class TestHelpers(unittest.TestCase):
"""Test any helper methods present in the sorter.py file."""
def test_compare_difference_string_slower(self):
"""Test that the calculate_compare_time_difference function will always
return the proper string when the custom algorithm takes longer then the
default python sorted() function.
"""
test_algorithm = 'bubble'
test_algorithm_time = 5
test_sorted_time = 1
result = calculate_compare_time_difference(test_algorithm_time, test_sorted_time, test_algorithm)
self.assertEqual('bubble was 4 seconds slower.', result)

def test_compare_difference_string_faster(self):
"""Test that the calculate_compare_time_difference function will always
return the proper string when the custom algorithm is faster then the
default python sorted() function.
"""
test_algorithm = 'bubble'
test_algorithm_time = 2
test_sorted_time = 4
result = calculate_compare_time_difference(test_algorithm_time, test_sorted_time, test_algorithm)
self.assertEqual('bubble was 2 seconds faster.', result)


class TestSorts(unittest.TestCase):
"""Test each sorting method located in the sorts.py file."""

def setUp(self):
"""Simple setup function to create the actual/expected
lists that each sort method should produce if working as
Expand Down

0 comments on commit 01e63a7

Please sign in to comment.