Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Filename: array_plot_smooth_spline.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- Description:
- This script generates a plot of an array of values with a smooth spline passing through the array points.
- It also calculates the sum and average of the array, and plots the maximum area rectangular histogram.
- Requirements:
- - Python 3.x
- - matplotlib
- - numpy
- - scipy
- Functions:
- - max_area_histogram(heights): Calculates the maximum area of a rectangular histogram given an array of heights.
- Usage:
- - Run the script and input the number of elements in the array and the array values.
- - The script will plot the array values with a smooth spline passing through them.
- - It will also display the sum and average of the array, and calculate the maximum area rectangular histogram.
- Example Output:
- Enter the number of elements in the array: 6
- Enter the array elements one by one. Hit Enter after each value:
- 2
- 5
- 3
- 2
- 5
- 3
- Array: [2, 5, 3, 2, 5, 3]
- Sum of the array: 20
- Average of the array: 3.3333333333333335
- Maximum area rectangular histogram: 12
- Additional Notes:
- - The smooth spline is generated using interpolation techniques.
- - The area under the smooth spline is filled with a transparent color for visualization.
- """
- # Get Essential Imports
- import matplotlib.pyplot as plt
- import numpy as np
- from scipy.interpolate import make_interp_spline
- def max_area_histogram(heights):
- """
- Calculate the maximum area of a rectangular histogram given an array of heights.
- This function implements the histogram algorithm to calculate the maximum area
- that can be obtained from a rectangular histogram formed by the given heights.
- Parameters:
- heights (list): A list of integers representing the heights of the histogram bars.
- Returns:
- int: The maximum area of the rectangular histogram.
- """
- stack: list = []
- max_area = 0
- index = 0
- while index < len(heights):
- if not stack or heights[index] >= heights[stack[-1]]:
- stack.append(index)
- index += 1
- else:
- top_of_stack = stack.pop()
- area = (heights[top_of_stack] * ((index - stack[-1] - 1) if stack else index))
- max_area = max(max_area, area)
- while stack:
- top_of_stack = stack.pop()
- area = (heights[top_of_stack] * ((index - stack[-1] - 1) if stack else index))
- max_area = max(max_area, area)
- return max_area
- # Input
- while True:
- try:
- n = int(input("Enter the number of elements in the array: "))
- if n <= 0:
- print("Please enter a positive integer for the number of elements.")
- continue
- print("Enter the array elements one by one. Hit Enter after each value:")
- array_heights = []
- for i in range(n):
- height = int(input())
- array_heights.append(height)
- # Output the array
- print("Array:", array_heights)
- # Calculate and output the sum of the array
- array_sum = sum(array_heights)
- print("Sum of the array:", array_sum)
- # Calculate the average of the array
- array_average = array_sum / n
- print("Average of the array:", array_average)
- # Generate a smooth spline passing through the array points
- x = np.arange(n)
- y = array_heights
- spline = make_interp_spline(x, y)
- x_smooth = np.linspace(0, n-1, 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(array_heights):
- plt.annotate(str(txt), (x[i], y[i]), textcoords="offset points", xytext=(0,10), ha='center')
- plt.xlabel('Index')
- plt.ylabel('Value')
- plt.title('Array Plot with Smooth Spline')
- plt.legend()
- plt.grid(True)
- plt.show()
- # Calculate and output the maximum area rectangular histogram
- print("Maximum area rectangular histogram:", max_area_histogram(array_heights))
- break
- except ValueError:
- print("Invalid input. Please enter a valid integer.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement