Home > Blockchain >  Generating a simple histogram from list of values
Generating a simple histogram from list of values

Time:10-01

I am taking an introductory level Python course. In one of my problems, I am supposed to make a function called def render_histogram. In this function, I am supposed to take a list of values and when I print the function for some list, I should get out a histogram composed of columns of "*" with a height equal to the number in the list.

Super simple histogram.

The histogram in the picture corresponds to the list [5, 4, 2, 7, 0, 3, 10]. This is my code so far:

def render_histogram(values):
    st = ""
    rows = []
    for value in values:
        rows.append("*" * value)
    rowrow = (list(map(list,rows)))
    st  = "\n".join(rowrow[0])
    return st
print(render_histogram([5, 4, 2, 7, 0, 3, 10]))

CodePudding user response:

This approach creates another list height which determines when the loop should start printing * based on the value of the element as compared to the maximum value. For the list [5, 4, 2, 7, 0, 3, 10], the output is as given below.

def render_histogram(lst):
    n = len(lst)
    height = [0]*n
    maxval = max(lst)
    for i in range(n):
        height[i] = maxval-lst[i]
    
    for i in range(maxval):
        for j in range(n):
            if (i >= height[j]):
                print("*", end = " ")
            else:
                print(" ", end = " ")
        print("\n")

Output

            * 

            *

            *

      *     *

      *     *

*     *     *

* *   *     *

* *   *   * *

* * * *   * *

* * * *   * *

CodePudding user response:

The render_histogram function in this code will return the 'chart' as a string that can then be printed out.

def render_histogram(vals):
  height = max(vals)
  chart = []
  for h in range(height, 0, -1):
    row = []
    row = ['*' if val>=h else ' ' for val in vals]
    chart.append(''.join(row))
  return '\n'.join(chart)

print(render_histogram([5, 4, 2, 7, 0, 3, 10]))
      *
      *
      *
   *  *
   *  *
*  *  *
** *  *
** * **
**** **
**** **

CodePudding user response:

This does the trick:

def render_histogram(values):
    for i in range(max(values), 0, -1):
        print("".join("*" if val >= i else " " for val in values))

edit: If you need the function to return a string:

def render_histogram(values):
    rows = []
    for i in range(max(values), 0, -1):
        rows.append("".join("*" if val >= i else " " for val in values))
    return "\n".join(rows)

or in a single, ugly line:

def render_histogram(values):
    return "\n".join("".join("*" if val >= i else " " for val in values) for i in range(max(values), 0, -1))
  • Related