Advertisement
Guest User

Untitled

a guest
Mar 21st, 2017
504
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 32.76 KB | None | 0 0
  1. #add to your bst
  2. def traverse(self):
  3.         a = []
  4.         self._traverse_aux(self._root, a)
  5.         return a
  6.    
  7.     def _traverse_aux(self, node, a):
  8.         if node is not None:
  9.             self._traverse_aux(node._left, a)
  10.             a.append(deepcopy(node._data))
  11.             self._traverse_aux(node._right, a)
  12.            
  13.         return
  14. #data structures
  15. """
  16. -------------------------------------------------------
  17. sorts_array.py
  18. [description of functions]
  19. -------------------------------------------------------
  20. Author:  Prayrit Khanna
  21. ID:      160596860
  22. Email:   khan6860@mylaurier.ca
  23. __updated__ = "2017-03-20"
  24. -------------------------------------------------------
  25. """
  26. # Imports
  27. from math import log
  28. from bst_linked import BST
  29.  
  30.  
  31. class Sorts:
  32.     """
  33.    -------------------------------------------------------
  34.    Defines a number of array-based sort operations.
  35.    Uses class attribute 'swaps' to determine how many times
  36.    elements are swapped by the class.
  37.    Use: print(Sorts.swaps)
  38.    Use: Sorts.swaps = 0
  39.    -------------------------------------------------------
  40.    """
  41.     swaps = 0  # Tracks swaps performed.
  42.  
  43.     # The Sorts
  44.  
  45.     @staticmethod
  46.     def selection_sort(a):
  47.         """
  48.        -------------------------------------------------------
  49.        Sorts an array using the Selection Sort algorithm.
  50.        Use: Sorts.selection_sort(a)
  51.        -------------------------------------------------------
  52.        Preconditions:
  53.            a - a Python list of comparable elements (?)
  54.        Postconditions:
  55.            Contents of a are sorted.
  56.        -------------------------------------------------------
  57.        """
  58.         n = len(a)
  59.         i = 0
  60.  
  61.         while i < n:
  62.             # Walk through entire array
  63.             m = i
  64.             j = i + 1
  65.  
  66.             while j < n:
  67.                 # Find smallest value in unsorted part of array
  68.  
  69.                 if a[m] > a[j]:
  70.                     # Track smallest value so far
  71.                     m = j
  72.                 j += 1
  73.  
  74.             if m != i:
  75.                 # swap elements only if necessary
  76.                 Sorts._swap(a, m, i)
  77.             i = i + 1
  78.         return
  79.  
  80.     @staticmethod
  81.     def insertion_sort(a):
  82.         """
  83.        -------------------------------------------------------
  84.        Sorts an array using the Insertion Sort algorithm.
  85.        Use: Sorts.insertion_sort(a)
  86.        -------------------------------------------------------
  87.        Preconditions:
  88.            a - an array of comparable elements (?)
  89.        Postconditions:
  90.            Contents of a are sorted.
  91.        -------------------------------------------------------
  92.        """
  93.         n = len(a)
  94.         i = 1
  95.  
  96.         while i < n:
  97.             # Walk through entire array
  98.             # Move each key bigger than save in a[1:n-1] one space to right.
  99.             save = a[i]
  100.             # Count as a swap
  101.             Sorts.swaps += 1
  102.             j = i - 1
  103.  
  104.             while j >= 0 and a[j] > save:
  105.                 Sorts._shift(a, j + 1, j)
  106.                 j -= 1
  107.             # Move save into hole opened up by moving previous keys to right.
  108.             a[j + 1] = save
  109.             i += 1
  110.         return
  111.  
  112.     @staticmethod
  113.     def bubble_sort(a):
  114.         """
  115.        -------------------------------------------------------
  116.        Sorts an array using the Bubble Sort algorithm.
  117.        Use: Sorts.bubble_sort(a)
  118.        -------------------------------------------------------
  119.        Preconditions:
  120.            a - an array of comparable elements (?)
  121.        Postconditions:
  122.            Contents of a are sorted.
  123.        -------------------------------------------------------
  124.        """
  125.         done = False
  126.         last = len(a) - 1
  127.  
  128.         while not done:
  129.             # assume done is true
  130.             done = True
  131.             last_swapped = 0
  132.             i = 0
  133.  
  134.             while i < last:
  135.                 if a[i] > a[i + 1]:
  136.                     # Save the list index swapped.
  137.                     last_swapped = i
  138.                     # The pair (a[i], a[i+1]) is out of order.
  139.                     # Exchange a[i] and a[i + 1] to put them in sorted order.
  140.                     Sorts._swap(a, i, i + 1)
  141.                     # If you swapped you need another pass.
  142.                     done = False
  143.                 i += 1
  144.             last = last_swapped
  145.             # Decreases 'last' because everything after last_swapped is already
  146.             # in order. done == False iff no pair of keys swapped on last pass.
  147.         return
  148.  
  149.     @staticmethod
  150.     def bst_sort(a):
  151.         """
  152.        -------------------------------------------------------
  153.        Sorts an array using the Tree Sort algorithm.
  154.        Use: Sorts.bst_sort(a)
  155.        -------------------------------------------------------
  156.        Preconditions:
  157.            a - an array of comparable elements (?)
  158.        Postconditions:
  159.            Contents of a are sorted.
  160.        -------------------------------------------------------
  161.        """
  162.         bst = BST()
  163.  
  164.         for v in a:
  165.             bst.insert(v)
  166.  
  167.         a[:] = bst.traverse()
  168.         return
  169.  
  170.     @staticmethod
  171.     def shell_sort(a):
  172.         """
  173.        -------------------------------------------------------
  174.        Sorts an array using the Shell Sort algorithm.
  175.        Use: Sorts.shell_sort(a)
  176.        -------------------------------------------------------
  177.        Preconditions:
  178.            a - an array of comparable elements (?)
  179.        Postconditions:
  180.            Contents of a are sorted.
  181.        -------------------------------------------------------
  182.        """
  183.         n = len(a)
  184.         increment = n // 3
  185.  
  186.         while increment > 0:
  187.             i = increment
  188.  
  189.             while i < n:
  190.                 j = i
  191.                 temp = a[i]
  192.  
  193.                 while j >= increment and a[j - increment] > temp:
  194.                     Sorts._shift(a, j, j - increment)
  195.                     j = j - increment
  196.                 a[j] = temp
  197.                 i += 1
  198.  
  199.             increment = increment // 3
  200.         return
  201.  
  202.     @staticmethod
  203.     def merge_sort(a):
  204.         """
  205.        -------------------------------------------------------
  206.        Sorts an array using the Merge Sort algorithm.
  207.        Use: Sorts.merge_sort(a)
  208.        -------------------------------------------------------
  209.        Preconditions:
  210.            a - an array of comparable elements (?)
  211.        Postconditions:
  212.            Contents of a are sorted.
  213.        -------------------------------------------------------
  214.        """
  215.         Sorts._merge_sort_aux(a, 0, len(a) - 1)
  216.         return
  217.  
  218.     @staticmethod
  219.     def _merge_sort_aux(a, first, last):
  220.         """
  221.        -------------------------------------------------------
  222.        Divides an array into halves, sorts each half, then
  223.        merges the halves back together.
  224.        Use: Sorts._merge_sort_aux(a, first, last)
  225.        -------------------------------------------------------
  226.        Preconditions:
  227.            a - an array of comparable elements (?)
  228.            first - beginning of subarray of a (int)
  229.            last - end of subarray of a (int)
  230.        Postconditions:
  231.            Contents of a from first to last are sorted.
  232.        -------------------------------------------------------
  233.        """
  234.  
  235.         if first < last:
  236.             middle = (last - first) // 2 + first
  237.             Sorts._merge_sort_aux(a, first, middle)
  238.             Sorts._merge_sort_aux(a, middle + 1, last)
  239.             Sorts._merge(a, first, middle, last)
  240.         return
  241.  
  242.     @staticmethod
  243.     def _merge(a, first, middle, last):
  244.         """
  245.        -------------------------------------------------------
  246.        Merges two parts of an array together.
  247.        Use: Sorts._merge(a, first, middle, last)
  248.        -------------------------------------------------------
  249.        Preconditions:
  250.            a - an array of comparable elements (?)
  251.            first - beginning of subarray of a (int)
  252.            middle - middle of subarray of a (int)
  253.            last - end of subarray of a (int)
  254.        Postconditions:
  255.            Contents of a are sorted.
  256.        -------------------------------------------------------
  257.        """
  258.         temp = []
  259.         i = first
  260.         j = middle + 1
  261.  
  262.         while i <= middle and j <= last:
  263.  
  264.             if a[i] <= a[j]:
  265.                 # put leftmost element of left array into temp array
  266.                 temp.append(a[i])
  267.                 i += 1
  268.             else:
  269.                 # put leftmost element of right array into temp array
  270.                 temp.append(a[j])
  271.                 j += 1
  272.  
  273.         # copy any remaining elements from the left half
  274.         while i <= middle:
  275.             temp.append(a[i])
  276.             i += 1
  277.  
  278.         # copy any remaining elements from the right half
  279.         while j <= last:
  280.             temp.append(a[j])
  281.             j += 1
  282.  
  283.         # copy the temporary array back to the passed array
  284.         i = 0
  285.  
  286.         while i < len(temp):
  287.             a[first + i] = temp[i]
  288.             i += 1
  289.         return
  290.  
  291.     @staticmethod
  292.     def quick_sort(a):
  293.         """
  294.        -------------------------------------------------------
  295.        Sorts an array using the Quick Sort algorithm.
  296.        Use: Sorts.quick_sort(a)
  297.        -------------------------------------------------------
  298.        Preconditions:
  299.            a - an array of comparable elements (?)
  300.        Postconditions:
  301.            Contents of a are sorted.
  302.        -------------------------------------------------------
  303.        """
  304.         Sorts._quick_sort_aux(a, 0, len(a) - 1)
  305.         return
  306.  
  307.     @staticmethod
  308.     def _quick_sort_aux(a, first, last):
  309.         """
  310.        -------------------------------------------------------
  311.        Divides an array into halves, sorts each half, then
  312.        concatenates the halves back together.
  313.        Use: Sorts._quick_sort_aux(a, first, last)
  314.        -------------------------------------------------------
  315.        Preconditions:
  316.            a - an array of comparable elements (?)
  317.            first - beginning of subarray of a (int)
  318.            last - end of subarray of a (int)
  319.        Postconditions:
  320.            Contents of a from first to last are sorted.
  321.        -------------------------------------------------------
  322.        """
  323.         # to sort the subarray a[p:q] of array a into ascending order
  324.         if first < last:
  325.             # partitions a[first:last] into a[first:pivot] and a[pivot+1:last]
  326.             i = Sorts._partition(a, first, last)
  327.             Sorts._quick_sort_aux(a, first, i - 1)
  328.             Sorts._quick_sort_aux(a, i + 1, last)
  329.         return
  330.  
  331.     @staticmethod
  332.     def _partition(a, first, last):
  333.         """
  334.        -------------------------------------------------------
  335.        Divides an array into two parts.
  336.        Use: Sorts._partition(a, first, last)
  337.        -------------------------------------------------------
  338.        Preconditions:
  339.            a - an array of comparable elements (?)
  340.            first - beginning of subarray of a (int)
  341.            last - last of subarray of a (int)
  342.        Postconditions:
  343.            Contents of a from first to last are sorted.
  344.        -------------------------------------------------------
  345.        """
  346.         pivot_index = first
  347.         low = first
  348.         high = last - 1  # After we remove pivot it will be one smaller
  349.         # print("{} - {} - {}".format(a[first:pivot_index], a[pivot_index],
  350.         #                        a[pivot_index + 1:last]))
  351.         pivot_value = a[pivot_index]
  352.         a[pivot_index] = a[last]
  353.  
  354.         while low <= high:
  355.             # print("{} - {} - {}".format(a[first:pivot_index],
  356.             #        a[pivot_index], a[pivot_index + 1:last]))
  357.             while low <= high and a[low] < pivot_value:
  358.                 low = low + 1
  359.             while low <= high and a[high] >= pivot_value:
  360.                 high = high - 1
  361.             if low <= high:
  362.                 Sorts._swap(a, low, high)
  363.         Sorts._shift(a, last, low)
  364.         # a[last] = a[low]
  365.         a[low] = pivot_value
  366.         # print("{} - {} - {}".format(a[first:pivot_index], a[pivot_index],
  367.         #                   a[pivot_index + 1:last]))
  368.         # Return the new pivot position.
  369.         return low
  370.  
  371.     @staticmethod
  372.     def heap_sort(a):
  373.         """
  374.        -------------------------------------------------------
  375.        Sorts an array using the Heap Sort algorithm.
  376.        Use: Sorts.heap_sort(a)
  377.        -------------------------------------------------------
  378.        Preconditions:
  379.            a - an array of comparable elements (?)
  380.        Postconditions:
  381.            Contents of a are sorted.
  382.        -------------------------------------------------------
  383.        """
  384.         first = 0
  385.         last = len(a) - 1
  386.         Sorts._build_heap(a, first, last)
  387.         i = last
  388.  
  389.         while i > first:
  390.             Sorts._swap(a, i, first)
  391.             Sorts._reheap(a, first, i - 1)
  392.             i -= 1
  393.         return
  394.  
  395.     @staticmethod
  396.     def _build_heap(a, first, last):
  397.         """
  398.        -------------------------------------------------------
  399.        Creates a heap.
  400.        Use: Sorts._build_heap(a, first, last)
  401.        -------------------------------------------------------
  402.        Preconditions:
  403.            a - an array of comparable elements (list)
  404.            first - first element in array to process (int)
  405.            last - last element in array to process (int)
  406.        Postconditions:
  407.            Contents of a from first to last are sorted.
  408.        -------------------------------------------------------
  409.        """
  410.         i = last // 2
  411.  
  412.         while i >= first:
  413.             Sorts._reheap(a, i, last)
  414.             i -= 1
  415.         return
  416.  
  417.     @staticmethod
  418.     def _reheap(a, first, last):
  419.         """
  420.        -------------------------------------------------------
  421.        Establishes heap property in a.
  422.        Use: Sorts._reheap(a, first, last)
  423.        -------------------------------------------------------
  424.        Preconditions:
  425.            a - an array of comparable elements (?)
  426.            first - first element in array to process (int)
  427.            last - last element in array to process (int)
  428.        Postconditions:
  429.            Contents of a from first to last are heaped.
  430.        -------------------------------------------------------
  431.        """
  432.         done = False
  433.  
  434.         while 2 * first + 1 <= last and not done:
  435.             k = 2 * first + 1
  436.  
  437.             if k < last and a[k] < a[k + 1]:
  438.                 k += 1
  439.  
  440.             if a[first] >= a[k]:
  441.                 done = True
  442.             else:
  443.                 Sorts._swap(a, first, k)
  444.                 first = k
  445.         return
  446.  
  447.     @staticmethod
  448.     def comb_sort(a):
  449.         """
  450.        -------------------------------------------------------
  451.        Sorts an array using the Comb Sort algorithm.
  452.        Use: Sorts.comb_sort(a)
  453.        -------------------------------------------------------
  454.        Preconditions:
  455.            a - an array of comparable elements (?)
  456.        Postconditions:
  457.            Contents of a are sorted.
  458.        -------------------------------------------------------
  459.        """
  460.         n = len(a)
  461.         gap = n
  462.         done = False
  463.  
  464.         while gap > 1 or not done:
  465.             done = True
  466.             gap = int(gap / 1.3)
  467.  
  468.             if gap < 1:
  469.                 gap = 1
  470.  
  471.             i = 0
  472.             j = gap
  473.  
  474.             while j < n:
  475.                 if a[i] > a[j]:
  476.                     Sorts._swap(a, i, j)
  477.                     done = False
  478.                 i += 1
  479.                 j += 1
  480.         return
  481.  
  482.     @staticmethod
  483.     def cocktail_sort(a):
  484.         """
  485.        -------------------------------------------------------
  486.        Sorts an array using the Cocktail Sort algorithm.
  487.        Use: Sorts.cocktail_sort(a)
  488.        -------------------------------------------------------
  489.        Preconditions:
  490.            a - an array of comparable elements (?)
  491.        Postconditions:
  492.            Contents of a are sorted.
  493.        -------------------------------------------------------
  494.        """
  495.         n = len(a)
  496.         first = 0
  497.         last = n - 1
  498.  
  499.         while first < last:
  500.             # Initialize last_swapped to the beginning of the array.
  501.             # Stops bottom loop from executing if no swaps done by top loop.
  502.             last_swapped = 0
  503.             i = first
  504.  
  505.             while i < last:
  506.                 if a[i] > a[i + 1]:
  507.                     # test whether the two elements are in the correct order
  508.                     Sorts._swap(a, i, i + 1)
  509.                     last_swapped = i
  510.                 i += 1
  511.             last = last_swapped
  512.  
  513.             # Initialize first_swapped to the end of the array.
  514.             # Stops top loop from executing if no swaps done by bottom loop.
  515.             first_swapped = n - 1
  516.             i = last
  517.  
  518.             while i > first:
  519.                 if a[i] < a[i - 1]:
  520.                     # test whether the two elements are in the correct order
  521.                     Sorts._swap(a, i, i - 1)
  522.                     first_swapped = i
  523.                 i -= 1
  524.             first = first_swapped
  525.         return
  526.  
  527.     @staticmethod
  528.     def binary_insert_sort(a):
  529.         """
  530.        -------------------------------------------------------
  531.        Sorts an array using the Binary Insertion Sort algorithm.
  532.        Use: Sorts.binary_insert_sort(a)
  533.        -------------------------------------------------------
  534.        Preconditions:
  535.            a - an array of comparable elements (list)
  536.        Postconditions:
  537.            Contents of a are sorted.
  538.        -------------------------------------------------------
  539.        """
  540.         n = len(a)
  541.         i = 1
  542.  
  543.         while i < n:
  544.             ins = Sorts._bin_srch_i(a, 0, i, a[i])
  545.             # Move key bigger than save in a[1:n-1] one space to the right.
  546.             if ins < i:
  547.                 save = a[i]
  548.                 j = i - 1
  549.  
  550.                 while j > ins - 1:
  551.                     Sorts._shift(a, j + 1, j)
  552.                     # a[j + 1] = a[j]
  553.                     j -= 1
  554.                 a[ins] = save
  555.             i += 1
  556.         return
  557.  
  558.     @staticmethod
  559.     def _bin_srch_r(a, low, high, value):
  560.         """
  561.        -------------------------------------------------------
  562.        Sorts an array using the Binary Insertion Sort algorithm.
  563.        Use: Sorts._bin_srch_r(a)
  564.        Recursive algorithm.
  565.        -------------------------------------------------------
  566.        Preconditions:
  567.            a - an array of comparable elements (list)
  568.            low - starting point of a to search for value (int)
  569.            high - end point of a to search for value (int)
  570.            value - value to search for position in a (?)
  571.        Postconditions:
  572.            returns
  573.            mid - the insert point for value in a between low and high
  574.        -------------------------------------------------------
  575.        """
  576.         if low == high:
  577.             mid = low
  578.         else:
  579.             mid = low + ((high - low) // 2)
  580.  
  581.             if value > a[mid]:
  582.                 mid = Sorts._bin_srch_r(a, mid + 1, high, value)
  583.             elif value < a[mid]:
  584.                 mid = Sorts._bin_srch_r(a, low, mid, value)
  585.         return mid
  586.  
  587.     @staticmethod
  588.     def _bin_srch_i(a, low, high, value):
  589.         """
  590.        -------------------------------------------------------
  591.        Sorts an array using the Binary Insertion Sort algorithm.
  592.        Use: Sorts._bin_srch_r(a)
  593.        Iterative algorithm.
  594.        -------------------------------------------------------
  595.        Preconditions:
  596.            a - an array of comparable elements (list)
  597.            low - starting point of a to search for value (int)
  598.            high - end point of a to search for value (int)
  599.            value - value to search for position in a (?)
  600.        Postconditions:
  601.            returns
  602.            mid - the insert point for value in a between low and high
  603.        -------------------------------------------------------
  604.        """
  605.         found = False
  606.         mid = (low + high) // 2
  607.  
  608.         while low < high and not found:
  609.             # Find the middle of the current subarray.
  610.             if value > a[mid]:
  611.                 # Search the right subarray.
  612.                 low = mid + 1
  613.                 mid = (low + high) // 2
  614.             elif value < a[mid]:
  615.                 # Search the left subarray.
  616.                 high = mid
  617.                 mid = (low + high) // 2
  618.             else:
  619.                 found = True
  620.         return mid
  621.  
  622.     # Sort Utilities
  623.  
  624.     @staticmethod
  625.     def sort_test(a):
  626.         """
  627.        -------------------------------------------------------
  628.        Determines whether an array is is_sorted or not.
  629.        Use: sort_test(a)
  630.        -------------------------------------------------------
  631.        Preconditions:
  632.            a - an array of comparable elements (?)
  633.        Postconditions:
  634.            returns
  635.            is_sorted - True if contents of a are sorted,
  636.                False otherwise.
  637.        -------------------------------------------------------
  638.        """
  639.         is_sorted = True
  640.         n = len(a)
  641.         i = 0
  642.  
  643.         while is_sorted and i < n - 1:
  644.  
  645.             if a[i] <= a[i + 1]:
  646.                 i += 1
  647.             else:
  648.                 is_sorted = False
  649.         return is_sorted
  650.  
  651.     @staticmethod
  652.     def _swap(a, i, j):
  653.         """
  654.        -------------------------------------------------------
  655.        Swaps the data contents of two array elements.
  656.        Updates 'swaps'.
  657.        Use: Sorts._swap(a, i, j)
  658.        -------------------------------------------------------
  659.        Preconditions:
  660.            a - an array of comparable elements (?)
  661.            i - index of one value (int 0 <= i < len(a))
  662.            j - index of another value (int 0 <= j < len(a))
  663.        Postconditions:
  664.            Values in a[i] and a[j] are swapped.
  665.        -------------------------------------------------------
  666.        """
  667.         Sorts.swaps += 1
  668.  
  669.         temp = a[i]
  670.         a[i] = a[j]
  671.         a[j] = temp
  672.         return
  673.  
  674.     @staticmethod
  675.     def _shift(a, i, j):
  676.         """
  677.        -------------------------------------------------------
  678.        Shifts the contents of a[j] to a[i].
  679.        Updates 'swaps' - worth 1/3 of _swap
  680.        Use: Sorts._shift(a, i, j)
  681.        -------------------------------------------------------
  682.        Preconditions:
  683.            a - an array of comparable elements (?)
  684.            i - index of one value (int 0 <= i < len(a))
  685.            j - index of another value (int 0 <= j < len(a))
  686.        Postconditions:
  687.            Value in a[j] is copied to a[i].
  688.        -------------------------------------------------------
  689.        """
  690.         Sorts.swaps += 0.34
  691.  
  692.         a[i] = a[j]
  693.         return
  694.  
  695. #DATA STRUCTURES
  696. """
  697. -------------------------------------------------------
  698. [file name]
  699. [program description]
  700. -------------------------------------------------------
  701. Author:  Prayrit Khanna
  702. ID:      160596860
  703. Email:   khan6860@mylaurier.ca
  704. __updated__ = "2017-03-20"
  705. -------------------------------------------------------
  706. """
  707.  
  708. class Number:
  709.     """
  710.    -------------------------------------------------------
  711.    Wraps a class definition around integers.
  712.    Uses class attribute 'comparisons' to determine how many times
  713.    comparison functions are called on the class.
  714.    Use: print(Number.comparisons)
  715.    Use: Number.comparisons = 0
  716.    -------------------------------------------------------
  717.    """
  718.     comparisons = 0
  719.  
  720.     def __init__(self, data):
  721.         """
  722.        -------------------------------------------------------
  723.        Creates a Number object.
  724.        -------------------------------------------------------
  725.        Preconditions:
  726.            data - an integer (int)
  727.        Postconditions:
  728.            A Number object containing data is initialized.
  729.        -------------------------------------------------------
  730.        """
  731.         self.data = data
  732.         return
  733.  
  734.     def __str__(self):
  735.         """
  736.        -------------------------------------------------------
  737.        Creates a formatted string of Number data.
  738.        -------------------------------------------------------
  739.        Postconditions:
  740.          returns:
  741.          the formatted contents of data (str)
  742.        -------------------------------------------------------
  743.        """
  744.         return str(self.data)
  745.  
  746.     def __eq__(self, rs):
  747.         """
  748.        -------------------------------------------------------
  749.        Compares this Number against another Number for equality.
  750.        Use: n1 == n2
  751.        -------------------------------------------------------
  752.        Preconditions:
  753.          rs - [right hand side] Number to compare to (Number)
  754.        Postconditions:
  755.          returns:
  756.          result - True if data matches, False otherwise (boolean)
  757.        -------------------------------------------------------
  758.        """
  759.         Number.comparisons += 1
  760.         result = self.data == rs.data
  761.         return result
  762.  
  763.     def __lt__(self, rs):
  764.         """
  765.        -------------------------------------------------------
  766.        Determines if this Number comes before another.
  767.        Use: n1 < n2
  768.        -------------------------------------------------------
  769.        Preconditions:
  770.          rs - [right hand side] Number to compare to (Number)
  771.        Postconditions:
  772.          returns:
  773.          result - True if this Number precedes rs,
  774.          False otherwise (boolean)
  775.        -------------------------------------------------------
  776.        """
  777.         Number.comparisons += 1
  778.         result = self.data < rs.data
  779.         return result
  780.  
  781.     def __le__(self, rs):
  782.         """
  783.        -------------------------------------------------------
  784.        Determines if this Number precedes or is or equal to another.
  785.        Use: n1 <= n2
  786.        -------------------------------------------------------
  787.        Preconditions:
  788.          rs - [right hand side] Number to compare to (movie)
  789.        Postconditions:
  790.          returns:
  791.          result - True if this Number precedes or is equal to rs,
  792.          False otherwise (boolean)
  793.        -------------------------------------------------------
  794.        """
  795.         Number.comparisons += 1
  796.         result = self.data <= rs.data
  797.         return result
  798. #Lab_10
  799. """
  800. -------------------------------------------------------
  801. [file name]
  802. [program description]
  803. -------------------------------------------------------
  804. Author:  Prayrit Khanna
  805. ID:      160596860
  806. Email:   khan6860@mylaurier.ca
  807. __updated__ = "2017-03-20"
  808. -------------------------------------------------------
  809. """
  810.  
  811. # Imports
  812. import random
  813. from number import Number
  814. from sorts_array import Sorts
  815. from random import randint
  816. from copy import deepcopy
  817.  
  818. # Constants
  819. SIZE = 100  # Size of array to sort.
  820. XRANGE = 1000  # Range of values in random arrays to sort.
  821. TESTS = 100  # Number of random arrays to generate.
  822.  
  823. SORTS = (
  824.     ('Bubble Sort', Sorts.bubble_sort),
  825.     ('Insertion Sort', Sorts.insertion_sort),
  826.     ('Merge Sort', Sorts.merge_sort),
  827.     ('Quick Sort', Sorts.quick_sort),
  828.     ('Selection Sort', Sorts.selection_sort),
  829.     ('Bin. Ins. Sort', Sorts.binary_insert_sort),
  830.     ('BST Sort', Sorts.bst_sort),
  831.     ('Cocktail Sort', Sorts.cocktail_sort),
  832.     ('Comb Sort', Sorts.comb_sort),
  833.     ('Heap Sort', Sorts.heap_sort),
  834.     ('Shell Sort', Sorts.shell_sort)
  835. )
  836.  
  837.  
  838. def create_sorted():
  839.     """
  840.    -------------------------------------------------------
  841.    Create a sorted list of Number objects.
  842.    -------------------------------------------------------
  843.    Postconditions:
  844.        returns
  845.        values - a sorted list of SIZE Number objects.
  846.    -------------------------------------------------------
  847.    """
  848.     values = []
  849.     i = 0
  850.     while i< SIZE:
  851.         values.append(Number(i)) #turns i into an object rather than an integer
  852.         i += 1
  853.     return values
  854.  
  855.  
  856. def create_reversed():
  857.     """
  858.    -------------------------------------------------------
  859.    Create a reversed list of Number objects.
  860.    -------------------------------------------------------
  861.    Postconditions:
  862.        returns
  863.        values - a reversed list of SIZE Number objects.
  864.    -------------------------------------------------------
  865.    """
  866.  
  867.     values = []
  868.     i = SIZE
  869.     while i>0:
  870.         values.append(Number(i)) #turns i into an object rather than an integer
  871.         i -= 1
  872.     return values
  873.  
  874.  
  875. def create_randoms():
  876.     """
  877.    -------------------------------------------------------
  878.    Create a 2D list of Number objects.
  879.    -------------------------------------------------------
  880.    Postconditions:
  881.        returns
  882.        arrays - TEST lists of SIZE Number objects containing
  883.            values between 0 and XRANGE.
  884.    -------------------------------------------------------
  885.    """
  886.     arrays = []
  887.     i = 0
  888.     while i<TESTS: #we are using TESTS lists, to get average of comparisons
  889.         value = []
  890.         x = 0
  891.         while x<SIZE: #Generate random numbers for the smaller lists
  892.             value.append(Number(randint(0,100)))
  893.             x += 1
  894.         arrays.append(value) #adding the smaller lists in the giant list
  895.         i +=1
  896.     return arrays
  897.  
  898.  
  899. def test_sort(title, func):
  900.     """
  901.    -------------------------------------------------------
  902.    Test a sort function with Number data and print out
  903.    its comparisons for sorted, reversed, and random arrays
  904.    of data.
  905.    -------------------------------------------------------
  906.    Preconditions:
  907.        title - name of the sorting function to call (str)
  908.        func - the actual sorting function to call (function)
  909.    Postconditions:
  910.        prints the number of comparisons necessary to sort an
  911.        array: in order, in reverse order, and a list of arrays
  912.        in random order.
  913.    -------------------------------------------------------
  914.    """
  915.     Number.comparisons = 0 #reset values
  916.     Sorts.swaps = 0 #reset values
  917.     #Ordered list
  918.     order = create_sorted() #this creates a sorted list
  919.     func(deepcopy(order)) #function takes the parameter of the list, not 2D list, or numbers.
  920.     ordered_comparison = Number.comparisons
  921.     ordered_swaps = Sorts.swaps
  922.     #print("order:",Sorts.swaps)
  923.     Number.comparisons = 0 #reset values
  924.     Sorts.swaps = 0 #reset values
  925.     #print("order cleaned:",Sorts.swaps)
  926.    
  927.     #reversed list
  928.     reverse = create_reversed()
  929.     func(deepcopy(reverse))
  930.     reversed_comparison = Number.comparisons
  931.     reversed_swaps = Sorts.swaps
  932.     #print(Sorts.swaps)
  933.    
  934.     Number.comparisons = 0 #reset values
  935.     Sorts.swaps = 0 #reset values
  936.     #print(Sorts.swaps)
  937.    
  938.     #Random list
  939.     rand = create_randoms()
  940.     i = 0
  941.     while i<len(rand):
  942.         func(rand[i])
  943.         i += 1
  944.     random_comparison = Number.comparisons//100
  945.     random_swap = Sorts.swaps//100
  946.    
  947.    
  948.     print ("{:<14} {:>8.0f} {:>8.0f} {:>8.0f} {:>8.0f} {:>8.0f} {:>8.0f}".format(title, ordered_comparison, reversed_comparison, random_comparison, ordered_swaps, reversed_swaps, random_swap))
  949.     return
  950. #task2
  951. """
  952. -------------------------------------------------------
  953. [file name]
  954. [program description]
  955. -------------------------------------------------------
  956. Author:  Prayrit Khanna
  957. ID:      160596860
  958. Email:   khan6860@mylaurier.ca
  959. __updated__ = "2017-03-20"
  960. -------------------------------------------------------
  961. """
  962. from test_sorts_array import test_sort
  963. from sorts_array import Sorts
  964. sort = ('Insertion Sort', Sorts.insertion_sort)
  965. title = sort[0]
  966. func = sort[1]
  967. test_sort(title, func)
  968. #task3
  969. """
  970. -------------------------------------------------------
  971. [file name]
  972. [program description]
  973. -------------------------------------------------------
  974. Author:  Prayrit Khanna
  975. ID:      160596860
  976. Email:   khan6860@mylaurier.ca
  977. __updated__ = "2017-03-20"
  978. -------------------------------------------------------
  979. """
  980. from test_sorts_array import test_sort, SORTS
  981. from sorts_array import Sorts
  982. i = 0
  983. print ("{} |{:^15s}| |{:^30s}|".format("n: 100", "Comparisons", "Swaps"))
  984.  
  985. while i<len(SORTS):
  986.     sort = (SORTS[i])
  987.     title = sort[0]
  988.     func = sort[1]
  989.     test_sort(title, func)
  990.     i+= 1
  991.  
  992. #task4
  993. """
  994. -------------------------------------------------------
  995. [file name]
  996. [program description]
  997. -------------------------------------------------------
  998. Author:  Prayrit Khanna
  999. ID:      160596860
  1000. Email:   khan6860@mylaurier.ca
  1001. __updated__ = "2017-03-20"
  1002. -------------------------------------------------------
  1003. """
  1004. from test_sorts_array import test_sort, SORTS
  1005. from sorts_linked import Sorts
  1006. i = 0
  1007. while i<len(SORTS):
  1008.     sort = (SORTS[i])
  1009.     title = sort[0]
  1010.     func = sort[1]
  1011.     test_sort(title, func)
  1012.     i+= 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement