Reputation: 163
An example like:
print("1.")
draw_histogram({'a': 2, 'c': 7, 'b': 5})
print("2.")
draw_histogram({'a': 0, 'c': 5, 'b': 7, 'f': 0})
I'm trying to get a series of stars. The number of stars printed is given by the value corresponding to the key. The keys are printed in alphabetical order. The key is not printed if the corresponding value is a number less than 1. I tried the function below,it doesn't work.
def draw_histogram(histogram_dict):
dicts = list(histogram_dict.keys())
for key in dicts:
if histogram_dict[key] < 1:
print (len(str(histogram_dict[key]))*"*")
expected:
1.
a: **
b: *****
c: *******
2.
b: *******
c: *****
Upvotes: 0
Views: 231
Reputation: 21
The following code answer your question.
def draw_histogram(histogram_dict):
dicts = list(histogram_dict.keys())
for key in dicts:
if histogram_dict[key] < 1:
print "{} - {}".format(key, int(histogram_dict[key])*"*")
else:
print "{} - {}".format(key, int(histogram_dict[key]) * "*")
print("1.")
draw_histogram({'a': 2, 'c': 7, 'b': 5})
print("2.")
draw_histogram({'a': 0, 'c': 5, 'b': 7, 'f': 0})
Output:
1. a: ** c: ******* b: ***** 2 a: c: ***** b: ******* f:P.N: This code developed on python 2.7
Upvotes: 0
Reputation: 14131
def draw_histogram(histogram_dict):
for key in histogram_dict:
if histogram_dict[key] >= 1:
print (key + ": " + histogram_dict[key]*"*")
First, you don't need to create list of keys - if you iterate over a dictionary, you automatically iterate over its keys.
Second, you want to print if histogram_dict[key]
is greater than or equal to 1
, and not less than 1
.
Third, you erroneously compute number of asterisks (stars) but they are already in your dictionary, as values.
Upvotes: 0
Reputation: 5425
Try this:
def draw_histogram(histogram_dict):
dicts = list(histogram_dict.keys())
for key in sorted(dicts):
if histogram_dict[key] >= 1:
print(key + ": " + histogram_dict[key] * "*")
print("1.")
draw_histogram({'a': 2, 'c': 7, 'b': 5})
print("2.")
draw_histogram({'a': 0, 'c': 5, 'b': 7, 'f': 0})
You were doing < 1
which only printed values less than 1 whereas you wanted >= 1
. Also, doing len(str(number)) * "*"
doesn't make sense; that gives the number of digits which isn't what you want. Finally, do sorted()
to display them in alphabetical order.
Upvotes: 1