Advertisement
Guest User

Untitled

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