Advertisement
Python253

array_manipulation

May 24th, 2024
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.56 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: array_manipulation.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.    This script enables manipulation of arrays by allowing users to insert or remove elements at the end or a specific index.
  10.    It also provides visualization capabilities by plotting the array values with a smooth spline passing through them.
  11.  
  12. Requirements:
  13.    - Python 3.x
  14.    - matplotlib
  15.    - scipy
  16.  
  17. Functions:
  18.    - insertEnd(arr, n, length, capacity):
  19.        Inserts a value at the end of the array.
  20.    - removeEnd(arr, length):
  21.        Removes a value from the end of the array.
  22.    - insertMiddle(arr, i, n, length):
  23.        Inserts a value at a specific index in the array.
  24.    - removeMiddle(arr, i, length):
  25.        Removes a value from a specific index in the array.
  26.    - printArr(arr, capacity):
  27.        Prints the array.
  28.    - plotArr(arr, length):
  29.        Plots the array values with a smooth spline passing through them.
  30.  
  31. Usage:
  32.    - Run the script and input the number of elements in the array and the array values.
  33.    - Follow the menu prompts to perform array manipulations or visualization.
  34.    - Choices include inserting/removing values, printing the array, plotting the array, and exiting the program.
  35.  
  36. Additional Notes:
  37.    - The smooth spline is generated using interpolation techniques.
  38.    - The area under the smooth spline is filled with a transparent color for visualization.
  39. """
  40.  
  41. import numpy as np
  42. import matplotlib.pyplot as plt
  43. from scipy.interpolate import make_interp_spline
  44. from decimal import Decimal
  45.  
  46. def insertEnd(arr, n, length, capacity):
  47.     """
  48.    Inserts a value at the end of the array.
  49.  
  50.    Parameters:
  51.        arr (list): The array.
  52.        n (Decimal): The value to insert.
  53.        length (int): The current length of the array.
  54.        capacity (int): The maximum capacity of the array.
  55.    """
  56.     if length < capacity:
  57.         arr[length] = Decimal(n)
  58.  
  59. def removeEnd(arr, length):
  60.     """
  61.    Removes a value from the end of the array.
  62.  
  63.    Parameters:
  64.        arr (list): The array.
  65.        length (int): The current length of the array.
  66.    """
  67.     if length > 0:
  68.         arr[length - 1] = Decimal(0)
  69.  
  70. def insertMiddle(arr, i, n, length):
  71.     """
  72.    Inserts a value at a specific index in the array.
  73.  
  74.    Parameters:
  75.        arr (list): The array.
  76.        i (int): The index to insert at.
  77.        n (Decimal): The value to insert.
  78.        length (int): The current length of the array.
  79.    """
  80.     for index in range(length - 1, i - 1, -1):
  81.         arr[index + 1] = arr[index]
  82.     arr[i] = Decimal(n)
  83.  
  84. def removeMiddle(arr, i, length):
  85.     """
  86.    Removes a value from a specific index in the array.
  87.  
  88.    Parameters:
  89.        arr (list): The array.
  90.        i (int): The index to remove from.
  91.        length (int): The current length of the array.
  92.    """
  93.     for index in range(i + 1, length):
  94.         arr[index - 1] = arr[index]
  95.     arr[length - 1] = Decimal(0)  # Set the last element to 0
  96.  
  97. def printArr(arr, capacity):
  98.     """
  99.    Prints the array.
  100.  
  101.    Parameters:
  102.        arr (list): The array.
  103.        capacity (int): The maximum capacity of the array.
  104.    """
  105.     for i in range(capacity):
  106.         print(f"{i}: {arr[i]}")
  107.  
  108. def plotArr(arr, length):
  109.     """
  110.    Plots the array values with a smooth spline passing through them.
  111.  
  112.    Parameters:
  113.        arr (list): The array.
  114.        length (int): The current length of the array.
  115.    """
  116.     x = np.arange(length)
  117.     y = arr[:length]
  118.  
  119.     # Check if all array values are zeros
  120.     if all(value == Decimal(0) for value in y):
  121.         print("Array is all zeros. No plot generated.")
  122.         return
  123.  
  124.     # Generate a smooth spline passing through the array points
  125.     spline = make_interp_spline(x, y)
  126.     x_smooth = np.linspace(x.min(), x.max(), 1000)
  127.     y_smooth = spline(x_smooth)
  128.  
  129.     # Plot the array and spline
  130.     plt.figure(figsize=(10, 6))
  131.     plt.plot(x_smooth, y_smooth, color='red', linewidth=2, label='Smooth Spline')
  132.     plt.fill_between(x_smooth, y_smooth, color='pink', alpha=0.75)  # Fill under the spline with color
  133.     plt.scatter(x, y, color='blue', marker='o', label='Array Points')
  134.     for i, txt in enumerate(y):
  135.         plt.annotate(f"{str(txt).rstrip('0').rstrip('.')}", (x[i], y[i]), textcoords="offset points", xytext=(0,10), ha='center')
  136.     plt.xlabel('Index')
  137.     plt.ylabel('Value')
  138.     plt.title('Array Plot')
  139.     plt.legend()
  140.     plt.grid(True)
  141.     plt.show()
  142.  
  143. def main():
  144.     """
  145.    Main function to demonstrate array manipulation and plotting.
  146.    """
  147.     capacity = 10
  148.     arr = [Decimal(0)] * capacity
  149.     length = 0
  150.  
  151.     num_values = int(input("How many values do you want to add to the array (up to 10)? "))
  152.     num_values = min(num_values, capacity)
  153.  
  154.     print("Enter the values one by one:")
  155.     for i in range(1, num_values + 1):  # Adjusted to start input at 1
  156.         value = Decimal(input(f"Enter value {i}: "))
  157.         insertEnd(arr, value, length, capacity)
  158.         length += 1
  159.  
  160.     while True:
  161.         print("\n  :: Manipulations Menu ::\n")
  162.         print("1. Insert value at the end")
  163.         print("2. Remove value from the end")
  164.         print("3. Insert value at a specific index")
  165.         print("4. Remove value from a specific index")
  166.         print("5. Print array")
  167.         print("6. Plot array")
  168.         print("7. Exit")
  169.  
  170.         choice = input("\nEnter your choice: ")
  171.  
  172.         if choice == '1':
  173.             n = Decimal(input("\nEnter value to insert: "))
  174.             insertEnd(arr, n, length, capacity)
  175.             length += 1
  176.         elif choice == '2':
  177.             removeEnd(arr, length)
  178.             if length > 0:
  179.                 length -= 1
  180.         elif choice == '3':
  181.             i = int(input("\nEnter index to insert at: "))
  182.             n = Decimal(input("\nEnter value to insert: "))
  183.             if i >= 0 and i < length:
  184.                 insertMiddle(arr, i, n, length)
  185.                 length += 1
  186.         elif choice == '4':
  187.             i = int(input("\nEnter index to remove from: "))
  188.             if i >= 0 and i < length:
  189.                 removeMiddle(arr, i, length)
  190.                 if length > 0:
  191.                     length -= 1
  192.         elif choice == '5':
  193.             print("Array:")
  194.             printArr(arr, capacity)
  195.         elif choice == '6':
  196.             plotArr(arr, length)
  197.         elif choice == '7':
  198.             print("\nExiting Program... GoodBye!\n")
  199.             break
  200.         else:
  201.             print("\nInvalid choice! Please try again.\n")
  202.  
  203. if __name__ == "__main__":
  204.     main()
  205.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement