Advertisement
Python253

quick_select_demo

Jun 24th, 2024 (edited)
365
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.93 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: quick_select_demo.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.    This script demonstrates the Quick Select algorithm to find the k-th smallest element in an array.
  10.  
  11. Requirements:
  12.    - Python 3.x
  13.  
  14. Functions:
  15.    - quick_select(arr, k):
  16.        Returns the k-th smallest element from the list `arr`.
  17.  
  18. Usage:
  19.    - Run the script to see the Quick Select algorithm in action.
  20.  
  21. Example:
  22.  
  23.                :: QUICK SELECT DEMO ::
  24.  
  25.        Array: [3, 2, 1, 5, 4]
  26.        k = 2 (looking for the 3rd smallest element)
  27.        Result: 3
  28.  
  29.        Quick Select Complete!
  30.  
  31.            Exiting Program...   GoodBye!
  32.  
  33. Additional Notes:
  34.    - Quick Select is efficient for finding the k-th smallest element in an unsorted array, with an average time complexity of O(n).
  35. """
  36.  
  37. import random
  38.  
  39. def quick_select(arr, k):
  40.     """
  41.    Returns the k-th smallest element of list `arr`.
  42.    
  43.    Args:
  44.        arr (list): List of elements from which to find the k-th smallest element.
  45.        k (int): Index of the smallest element to find (0-based).
  46.  
  47.    Returns:
  48.        int: The k-th smallest element in the list `arr`.
  49.  
  50.    Example Output:
  51.    
  52.                :: QUICK SELECT DEMO ::
  53.  
  54.        Array: [3, 2, 1, 5, 4]
  55.        k = 2 (looking for the 3rd smallest element)
  56.        Result: 3
  57.        
  58.        Quick Select Complete!
  59.  
  60.                Exiting Program...   GoodBye!
  61.  
  62.    """
  63.     if len(arr) == 1:
  64.         return arr[0]
  65.  
  66.     pivot = random.choice(arr)
  67.  
  68.     lows = [el for el in arr if el < pivot]
  69.     highs = [el for el in arr if el > pivot]
  70.     pivots = [el for el in arr if el == pivot]
  71.  
  72.     if k < len(lows):
  73.         return quick_select(lows, k)
  74.     elif k < len(lows) + len(pivots):
  75.         return pivots[0]
  76.     else:
  77.         return quick_select(highs, k - len(lows) - len(pivots))
  78.  
  79. def main():
  80.     """
  81.    Main function to demonstrate quick select.
  82.  
  83.    It initializes an example array, uses quick_select function to find
  84.    the k-th smallest element, and prints the original array and the result.
  85.    """
  86.     print("\n\t\t:: QUICK SELECT DEMO ::\n")
  87.    
  88.     # Example array
  89.     arr = [3, 2, 1, 5, 4]
  90.     k = 2  # looking for the 3rd smallest element, index 2
  91.  
  92.     # Print the original array
  93.     arr_str = "["
  94.     for index, num in enumerate(arr):
  95.         if index == 0:
  96.             arr_str += f"{num}"  # No leading space needed for the first number
  97.         else:
  98.             arr_str += f", {num}"  # Add a leading space for single-digit numbers
  99.     arr_str += "]"
  100.     print(f"Array: {arr_str}")
  101.  
  102.     # Perform quick select
  103.     result = quick_select(arr, k)
  104.  
  105.     # Print the result
  106.     print(f"k = {k} (looking for the {k+1}rd smallest element)")
  107.     print(f"Result: {result}")
  108.  
  109.     # Print completion message
  110.     print("\nQuick Select Complete!\n\n\tExiting Program...   GoodBye!")
  111.  
  112. if __name__ == "__main__":
  113.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement