In: Computer Science
python3
Design a class named Histogram to display a histogram of data. The Histogram class contains the following
and draw_vertical_histogram() method in the Histogram class. This method takes 3 parameters:
For example, consider the following code fragment:
h2 = Histogram([['May', 3], ['Bob', 7], ['Mike', 2]]) print(h2) h2.draw_vertical_histogram()
produces:
x_width=5 y_width=10, data=[['May', 3], ['Bob', 7], ['Mike', 2]] * * * * * * * * * * * * --------------- May Bob Mike
Note: column width is specified by the value of x_width
For example:
Test | Result |
---|---|
h2 = Histogram([['May', 3], ['Bob', 7], ['Mike', 2]]) print(h2) h2.draw_vertical_histogram() |
x_width=5 y_width=10, data=[['May', 3], ['Bob', 7], ['Mike', 2]] * * * * * * * * * * * * --------------- May Bob Mike |
h2 = Histogram([['a', 2, 7], ['b', 1, 4], ['c', 8, 3]]) h2.draw_vertical_histogram(y_index=2) |
* * * * * * * * * * * * * * --------------- a b c |
If you have any doubts, please give me comment...
class Histogram:
def __init__(self, data, x_width=5, y_width=10):
self.data = data
self.x_width = x_width
self.y_width = y_width
def __str__(self):
return "x_width="+str(self.x_width)+", y_width="+str(self.y_width)+", data="+str(self.data)
def draw_vertical_histogram(self, x_index=0, y_index=1):
maximum = 0
for d in self.data:
if d[y_index]>maximum:
maximum = d[y_index]
for i in range(maximum-1, -1, -1):
for d in self.data:
if i<d[y_index]:
print('%-*s'%(self.x_width, "*"), end='')
else:
print('%-*s'%(self.x_width, " "), end='')
print()
print('-'*(self.x_width*len(self.data)))
for d in self.data:
print("%-*s"%(self.x_width, d[x_index]), end='')
print()
h2 = Histogram([['May', 3], ['Bob', 7], ['Mike', 2]])
print(h2)
h2.draw_vertical_histogram()
h2 = Histogram([['a', 2, 7], ['b', 1, 4], ['c', 8, 3]])
h2.draw_vertical_histogram(y_index=2)