Search code examples
pythondictionaryfor-loophistogram

Histogram for list of elements python


Does anybody know how I can make this

Input

Explanation: <2> is the first input and shows the number of next inputs lines -> if the first input is n all the input lines are n+1

2 
purple 11,yellow 3,pink 1 
gray 8,blue 10,pink 12

and the last 2 lines are my next inputs(the user wants to collect and save their n days of selling Crayons and get Histogram of their sales

into this

Output

I want to print the line number and its list of words with their number's histogram(the "*"s actually)line by line

1
purple ***********
yellow ***
pink *
2
gray ********
blue **********
pink ************

I don't have a problem with getting inputs I just don't know what codes I should write to print this output.

PS: I stored sales in a list


Solution

  • You should just use .split() method several times to split the line by , and then to split every element by " ". Then you should print the color (first part of the element) with * * second part of the element. I used f strings, but you can just use + in the print(). Here is the code:

    lines = []
    for i in range(int(input())):
        lines.append(input())
    # making a list "lines" with all lines
    
    for j in range(len(lines)):
        print(j + 1)  # line number
        for element in lines[j].split(","):
            print(f'{element.split(" ")[0]} {"*" * int(element.split(" ")[1])}')  # color and stars
    

    Hope that helped! :)