Home > Blockchain >  Defining the lines in a vertical histogram
Defining the lines in a vertical histogram

Time:03-06

I'm trying to create a function that returns a vertical histogram where the height of each column corresponds to an integer from a list. I have written some code that I think would work if I could find a way to define each line.

If the goal is not clear I'm trying to write a program with a function that takes a list (ex. [1, 5, 2, 4]) and returns a vertical histogram consisting of asterisks like this:

 *  
 * *
 * *
 ***
****

Below is the code that I think could work if I manage to define row in a nice way.

def render_histogram(values):
    histogram = []
    for y in range(max(values), 0, -1):
        row = ()
        histogram.append(row)
    return '\n'.join(histogram)

My first idea would be to check for every column if the number in question is equal or greater than y, but I don't know how I would write this as code.

CodePudding user response:

My first idea would be to check for every column if the number in question is equal or greater than y, but I don't know how I would write this as code.

Yes, that is the right approach. You can do that as follows:

    row = ''.join(' ' if x < y else '*' for x in values)

The rest of your code is fine, but you could also turn that for loop into list comprehension, so that you get this function:

def render_histogram(values):
    return '\n'.join(
        ''.join(' ' if x < y else '*' for x in values)
        for y in range(max(values), 0, -1)
    )

CodePudding user response:

This code calculates maximum value of the list, and fill the difference of each item with blank spaces:

def render_histogram(values):
    max_val = max(values)   # Max value in list
    result = []
    for item_val in values:
        bar = " " * (max_val-item_val)     # Fill with spaces
        bar  = "*" * item_val              # Fill with "*"
        result.append(bar)
    return result


data = [1, 5, 2, 4]
hist =  render_histogram(data)
for line in hist:
    print(line)

# Prints: 
#     *
# *****
#    **
#  ****
  • Related