Please write a Python program to create a histogram. It must read text from stdin and…
- User
Please write a Python program to create a histogram. It must read text from stdin and output text to stdout. One line of output will correspond with one line of input. Each line of input will be two fields separated by a space. The first field will be a text label. The 2nd will be a numeric value. The output will be a histogram made out of ascii text characters. Each line will have three fields. The text label will be the first and will be left aligned. The 2nd will be the value, right aligned. The third will be a bar of the histogram, left aligned. The bar will have a width the length of which will be proportional to the value of the 2nd field. The maximum width of the output shall be the width of the console terminal if this can be determined, or 80 otherwise. As a header please print the maximum, minimum, mean and std deviation of the values.
- Assistant
Here's a Python program that fulfills your requirements using the
statisticsmodule for calculations andshutil.get_terminal_size()for determining the terminal width. It reads input from stdin and outputs the histogram to stdout.pythonimport sys import statistics import shutil # Read input and calculate statistics data = [] for line in sys.stdin: label, value = line.strip().split() data.append((label, int(value))) labels, values = zip(*data) max_val = max(values) min_val = min(values) mean_val = statistics.mean(values) std_dev = statistics.stdev(values) # Determine terminal width terminal_width = shutil.get_terminal_size().columns or 80 # Print header print(f"Max: {max_val}, Min: {min_val}, Mean: {mean_val:.2f}, Std Dev: {std_dev:.2f}") # Print histogram for label, value in data: bar_width = int((value / max_val) * (terminal_width - len(label) - 5)) bar = '#' * bar_width print(f"{label:<{terminal_width - len(bar) - 2}} {value:>5} {bar}")
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.