Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Filename: array_manipulation.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- Description:
- This script enables manipulation of arrays by allowing users to insert or remove elements at the end or a specific index.
- It also provides visualization capabilities by plotting the array values with a smooth spline passing through them.
- Requirements:
- - Python 3.x
- - matplotlib
- - scipy
- Functions:
- - insertEnd(arr, n, length, capacity):
- Inserts a value at the end of the array.
- - removeEnd(arr, length):
- Removes a value from the end of the array.
- - insertMiddle(arr, i, n, length):
- Inserts a value at a specific index in the array.
- - removeMiddle(arr, i, length):
- Removes a value from a specific index in the array.
- - printArr(arr, capacity):
- Prints the array.
- - plotArr(arr, length):
- Plots the array values with a smooth spline passing through them.
- Usage:
- - Run the script and input the number of elements in the array and the array values.
- - Follow the menu prompts to perform array manipulations or visualization.
- - Choices include inserting/removing values, printing the array, plotting the array, and exiting the program.
- Additional Notes:
- - The smooth spline is generated using interpolation techniques.
- - The area under the smooth spline is filled with a transparent color for visualization.
- """
- import numpy as np
- import matplotlib.pyplot as plt
- from scipy.interpolate import make_interp_spline
- from decimal import Decimal
- def insertEnd(arr, n, length, capacity):
- """
- Inserts a value at the end of the array.
- Parameters:
- arr (list): The array.
- n (Decimal): The value to insert.
- length (int): The current length of the array.
- capacity (int): The maximum capacity of the array.
- """
- if length < capacity:
- arr[length] = Decimal(n)
- def removeEnd(arr, length):
- """
- Removes a value from the end of the array.
- Parameters:
- arr (list): The array.
- length (int): The current length of the array.
- """
- if length > 0:
- arr[length - 1] = Decimal(0)
- def insertMiddle(arr, i, n, length):
- """
- Inserts a value at a specific index in the array.
- Parameters:
- arr (list): The array.
- i (int): The index to insert at.
- n (Decimal): The value to insert.
- length (int): The current length of the array.
- """
- for index in range(length - 1, i - 1, -1):
- arr[index + 1] = arr[index]
- arr[i] = Decimal(n)
- def removeMiddle(arr, i, length):
- """
- Removes a value from a specific index in the array.
- Parameters:
- arr (list): The array.
- i (int): The index to remove from.
- length (int): The current length of the array.
- """
- for index in range(i + 1, length):
- arr[index - 1] = arr[index]
- arr[length - 1] = Decimal(0) # Set the last element to 0
- def printArr(arr, capacity):
- """
- Prints the array.
- Parameters:
- arr (list): The array.
- capacity (int): The maximum capacity of the array.
- """
- for i in range(capacity):
- print(f"{i}: {arr[i]}")
- def plotArr(arr, length):
- """
- Plots the array values with a smooth spline passing through them.
- Parameters:
- arr (list): The array.
- length (int): The current length of the array.
- """
- x = np.arange(length)
- y = arr[:length]
- # Check if all array values are zeros
- if all(value == Decimal(0) for value in y):
- print("Array is all zeros. No plot generated.")
- return
- # Generate a smooth spline passing through the array points
- spline = make_interp_spline(x, y)
- x_smooth = np.linspace(x.min(), x.max(), 1000)
- y_smooth = spline(x_smooth)
- # Plot the array and spline
- plt.figure(figsize=(10, 6))
- plt.plot(x_smooth, y_smooth, color='red', linewidth=2, label='Smooth Spline')
- plt.fill_between(x_smooth, y_smooth, color='pink', alpha=0.75) # Fill under the spline with color
- plt.scatter(x, y, color='blue', marker='o', label='Array Points')
- for i, txt in enumerate(y):
- plt.annotate(f"{str(txt).rstrip('0').rstrip('.')}", (x[i], y[i]), textcoords="offset points", xytext=(0,10), ha='center')
- plt.xlabel('Index')
- plt.ylabel('Value')
- plt.title('Array Plot')
- plt.legend()
- plt.grid(True)
- plt.show()
- def main():
- """
- Main function to demonstrate array manipulation and plotting.
- """
- capacity = 10
- arr = [Decimal(0)] * capacity
- length = 0
- num_values = int(input("How many values do you want to add to the array (up to 10)? "))
- num_values = min(num_values, capacity)
- print("Enter the values one by one:")
- for i in range(1, num_values + 1): # Adjusted to start input at 1
- value = Decimal(input(f"Enter value {i}: "))
- insertEnd(arr, value, length, capacity)
- length += 1
- while True:
- print("\n :: Manipulations Menu ::\n")
- print("1. Insert value at the end")
- print("2. Remove value from the end")
- print("3. Insert value at a specific index")
- print("4. Remove value from a specific index")
- print("5. Print array")
- print("6. Plot array")
- print("7. Exit")
- choice = input("\nEnter your choice: ")
- if choice == '1':
- n = Decimal(input("\nEnter value to insert: "))
- insertEnd(arr, n, length, capacity)
- length += 1
- elif choice == '2':
- removeEnd(arr, length)
- if length > 0:
- length -= 1
- elif choice == '3':
- i = int(input("\nEnter index to insert at: "))
- n = Decimal(input("\nEnter value to insert: "))
- if i >= 0 and i < length:
- insertMiddle(arr, i, n, length)
- length += 1
- elif choice == '4':
- i = int(input("\nEnter index to remove from: "))
- if i >= 0 and i < length:
- removeMiddle(arr, i, length)
- if length > 0:
- length -= 1
- elif choice == '5':
- print("Array:")
- printArr(arr, capacity)
- elif choice == '6':
- plotArr(arr, length)
- elif choice == '7':
- print("\nExiting Program... GoodBye!\n")
- break
- else:
- print("\nInvalid choice! Please try again.\n")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement