0
How do I add letters? Can someone help?
Write a function that takes as input a string and prints a histogram of letter counts. A histogram can be done using stars characters. output: to be or not to be B * * E * * N * O * * * * R * T * * * My code: https://code.sololearn.com/cXiOU0wR2ZLi/#py def histogram(items): for n in items: output = "" times = n while( times > 0 ): output += "*" times = times - 1 print(output) histogram([7, 0, 2, 6]) I figured out how to do it for numbers but how can I change it to make it look like the output?
9 odpowiedzi
+ 4
I will presume the input is all uppercase. Build a dictionary of letters as the keys, and integer count as the value. As you scan each letter of the input string, check if it is in the dictionary. If not found, add it with count 1, else increment its count.
To print the histogram in sorted order, loop through a list of "A" to "Z" as lookup keys, check if the key is in the dictionary. If found, print its histogram.
+ 2
Take the input. Sort it first. And make a dictionary from the input "letters as keys and count(letter) as value.
So you get like {{ 'B' : 2}, {'E':2},....}.
Now with that key and value form pattern...
Key "*" *value.
+ 1
Worked on Jayakrishna's and Brian's idea
https://code.sololearn.com/cp0TpLP66jdF/?ref=app
+ 1
Thank you all, your explanation and examples helped
+ 1
In one line lol
https://code.sololearn.com/cu6cpYu0a5L5/?ref=app
0
I'm not quite sure how you want the output to look.
If you want to print them in a sorted order, you can just sort the items before the loop. You can do items.sort() or items = sorted(items). You can even just do for n in sorted(items).
If you want it to show what number is being described by the stars similar to your example output, you can modify your print statement like this:
print(n, output)
0
Zerokles, I want the output to look like this..... if I were to inout 'to be or not too be' I want a star for the amount of letters being repeated, for instance
to be or not to be
B * *
E * *
N *
O * * * *
R *
T * * *
0
https://code.sololearn.com/cI4DjuK2uHep/?ref=app
an attempt :)
...
0
... Ahh, I thought you wanted to have similar output when you do it with numbers. I guess I understood your question wrong.
Like some have said, you can use a dictionary to record the number occurrences of each letter. If you want it to be sorted, you can sort the string first before you iterate through it.
Another thing you can do:
def histogram(string):
for i in sorted(set(string)):
print(i.upper(), '*' * string.count(i))