Python Histogram Generator: Ordering and Visualization
To implement a function that generates a histogram based on an ordered list, follow these steps:
- Define the function: Let's name it 'histogram_order'.
- Add parameters: The function should accept two parameters: the input list and the desired ordering ('Ascending' or 'Descending').
- Conditional statement: Use an 'if-elif' statement to check the 'ordering' parameter.
- Sorting:
- If 'ordering' is 'Ascending', sort the list in ascending order using the 'sort()' method.
- If 'ordering' is 'Descending', sort the list in descending order using 'sort(reverse=True)'.
- Iterate and Print: Iterate through the sorted list. For each element, print a row of '' characters, with the number of '' characters equal to the element's value.
- Test: Test the function with an example list and ordering.
Here's the Python implementation:
def histogram_order(lst, ordering):
if ordering == 'Ascending':
lst.sort()
elif ordering == 'Descending':
lst.sort(reverse=True)
for num in lst:
print('*' * num)
# Example usage
lst = [2, 6, 8, 4]
ordering = 'Ascending'
histogram_order(lst, ordering)
This will output the following histogram:
**
******
********
********
In this example, the list is sorted in ascending order, and the histogram visually represents the distribution of the data. Each number in the list corresponds to the number of '*' characters in the corresponding row of the histogram.
原文地址: https://www.cveoy.top/t/topic/pfNW 著作权归作者所有。请勿转载和采集!