How do I add letters? Can someone help? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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?

15th Oct 2020, 10:01 PM
...
... - avatar
9 Answers
+ 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.
15th Oct 2020, 10:55 PM
Brian
Brian - avatar
+ 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.
15th Oct 2020, 10:49 PM
Jayakrishna 🇮🇳
+ 1
Worked on Jayakrishna's and Brian's idea https://code.sololearn.com/cp0TpLP66jdF/?ref=app
15th Oct 2020, 11:23 PM
Ipang
+ 1
Thank you all, your explanation and examples helped
15th Oct 2020, 11:25 PM
...
... - avatar
15th Oct 2020, 11:38 PM
Zerokles
Zerokles - avatar
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)
15th Oct 2020, 10:12 PM
Zerokles
Zerokles - avatar
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 * * *
15th Oct 2020, 10:17 PM
...
... - avatar
15th Oct 2020, 10:46 PM
Bahhaⵣ
Bahhaⵣ - avatar
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))
15th Oct 2020, 11:23 PM
Zerokles
Zerokles - avatar