Go through a list and return as many asterisks as indicated by the number entered

1

I have an exercise in which I am asked to create a "Histogram" from the data entered by keyboard and stored in a python list.

For example, I enter some numbers by keyboard and add them to a python list: lista[4, 9, 7] . The prompt should show me the following:

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

At the moment I have made this code, but I do not know what it fails:

lista=[]
v=0

def procedimiento(num):
    for i in range(num): 
        print("*",end=" ")


while v!=4:
    num=int(input("Introduce num astericos para histograma: "))
    lista.append(num)
    v=v+1


    procedimiento(num)

Thanks in advance

    
asked by sergio 09.12.2017 в 18:04
source

2 answers

0

You are calling your function responsible for printing the histogram (if it is not an error of indentation when you paste the code) in each iteration of while , so you mix the impression with the inputs and without a line break between them ( end = " " ). You should first save the numbers in the list as you do and when you finish iterating over the list or directly send the list to the function procedimiento .

If the number of elements to be entered is defined before the cycle, use a for and not a while , it is more efficient and more "pythonic".

To print the asterisks instead of another cycle you can simply:

print("*" * num)

For example, using two separate functions you can do the following:

def imprimir_histograma(barras):
    for num in barras: 
        print("*" * num)

def ingresar_datos(n): 
    lista=[] 
    for _ in range(n):
        num = int(input("Introduce num astericos para histograma: "))
        lista.append(num)
    return lista

lista = ingresar_datos(3)
imprimir_histograma(lista)

Exit:

Introduce num astericos para histograma: 4
Introduce num astericos para histograma: 9
Introduce num astericos para histograma: 7
****
*********
*******
    
answered by 09.12.2017 / 18:28
source
0

Another alternative is to take advantage of the fact that when you multiply a text string by an integer, python repeats that number of times the string.

For example, this code is used if the user enters the data in the form 4 9 7 (separated by spaces):

datos_histograma = input('Introduce num astericos para histograma: ') # recibe los datos
lista_histograma = [int(d) for d in datos_histograma.split()] # los convierte en int y los junta en una lista
for d in lista_histograma:
    print(d * '*') # repetir d veces el caracter '*'

Result:

Introduce num astericos para histograma: 4 7 9
****
*******
*********
    
answered by 10.12.2017 в 02:51