I am trying to get a bar graph-like output using the lists below in the set intervals.
list = [1,1,2,2,5,6,7,8,23,23,24,25,34,35,45,45,46,50]
intervals = ["01-05","06-10","11-15","16-20","21-25","26-30","31-35","36-40","41-45","46-50"]
count = [0,0,0,0,0,0,0,0,0,0]
I think I am supposed to use a for loop to run through the list values and add onto each index of the count list according to the index of the intervals list. Then turn the count values into asterisks. I've tried doing this but I just could not get it right and loops are definitely not my forte. I am sorry if this is a very basic question, the help is much appreciated!
This is an example of the output I am trying to achieve:
01-05 : **
06-10 : ***
11-15 : *
15-20 : ****
21-25 : *******
26-30 : **
31-35 : ****
36-40 : ****
41-45 : *
46-50 : ********
CodePudding user response:
list = [1,1,2,2,5,6,7,8,23,23,24,25,34,35,45,45,46,50]
intervals = ["01-05","06-10","11-15","16-20","21-25","26-30","31-35","36-40","41-45","46-50"]
count = [0,0,0,0,0,0,0,0,0,0]
#Calculate the count
for i in list:
if i>4 and i%5==0:
i-=1
count[i//5] =1
#Print the data
for i,j in zip(intervals,count):
print(f'{i} : {j*"*"}')
CodePudding user response:
If you want more customization over intervals, printing character etc. you can create a function (not optimized though) like,
def print_as_bargraph(data, intervals, char = "*"):
for sub in intervals:
a, b = sub
count = len([x for x in data if x in range(a, b 1)])
row = "{:02}-{:02} : {}".format(*sub, count*char)
print(row)
data_list = [1,1,2,2,5,6,7,8,23,23,24,25,34,35,45,45,46,50]
interval1 = [(5*i-4, 5*i) for i in range(1, 11)]
interval2 = [(10*i-10, 10*i) for i in range(1, 6)]
print("Original data:")
print(data_list)
print("\nIntervals are,")
print(f"1. {interval1}")
print(f"\n2. {interval2}")
print("\nWithin first interval using '*':\n")
print_as_bargraph(data_list, interval1)
print("\nWithin second interval using '-':")
print_as_bargraph(data_list, interval2, "-")
Note : Try to avoid using built-in tokens or functions (here 'list') as variable name as there may be name conflict, you can use 'list_' also. You can get a proper coding style guide in PEP 8 -- Style Guide for Python Code.