Python Function for Sorting and Creating Histograms
This code implements a Python function that sorts a list of numbers based on an ordering parameter and creates a histogram to visually represent the data. It leverages the sorted() function for sorting and constructs the histogram using '>' symbols.
def order_and_histogram(lst, ordering):
if ordering == 'Ascending':
ordered_lst = sorted(lst)
elif ordering == 'Descending':
ordered_lst = sorted(lst, reverse=True)
else:
return 'Invalid ordering parameter'
histogram = ''
for num in ordered_lst:
histogram += '>' * num + '\n'
return histogram
# Example usage
lst = [2, 6, 8, 4]
ordering = 'Ascending'
print(order_and_histogram(lst, ordering))
Explanation:
-
Function Definition:
- The function
order_and_histogram(lst, ordering)takes a listlstand a stringorderingas input.
- The function
-
Ordering Logic:
- It checks the
orderingparameter:- If it's 'Ascending', it sorts the list using
sorted(lst). - If it's 'Descending', it sorts the list in reverse order using
sorted(lst, reverse=True). - If it's neither, it returns an error message.
- If it's 'Ascending', it sorts the list using
- It checks the
-
Histogram Creation:
- A string
histogramis initialized to store the histogram representation. - The function iterates through the ordered list
ordered_lst:- For each
numin the list, it addsnumnumber of '>' symbols to thehistogramstring followed by a newline character ('\n').
- For each
- A string
-
Output:
- The function returns the final
histogramstring, which is a visual representation of the sorted data.
- The function returns the final
Example Usage:
- The code demonstrates using the function with the list
[2, 6, 8, 4]andorderingset to 'Ascending'. - The output is a histogram with rows of '>' symbols corresponding to the sorted numbers, visually displaying the data's distribution.
原文地址: https://www.cveoy.top/t/topic/pfNJ 著作权归作者所有。请勿转载和采集!