Print multiple numbers with a separator between them, but do not put the separator after the last

Asked

Viewed 328 times

5

Make a program that reads two integers, representing the start and end values of a range and print the multiples of 5 between them.

My code:

valores = input().split()    
numero1 = int(valores[0])    
numero2 = int(valores[1])    
for n in range(numero1, numero2+1):

    if n % 5 == 0:

        print(n, end='|')

Note that the numbers are separated by |, but cannot have this character after the last number.

  • A possibility is from the second on to print a| before the number.

2 answers

9


An alternative is to use join:

print('|'.join(str(n) for n in range(numero1, numero2 + 1) if n % 5 == 0))

Although it seems the same thing from another answer, has a difference. There was created a list containing the numbers, after this list was passed to join. Here I went directly to Generator Expression, which does not create the list. Thus, join iterates by the numbers and already building the final string (not that you will have that performance difference - even more so ranges with few values - but it’s important to know that you can build what you need without creating lists - or any other structures - no need).


But there is actually another way to optimize the code. If the idea is to print only multiples of 5, there is no reason why the range be 1 to 1 and go testing if each number is divisible by 5 (since between 2 multiples, another 4 numbers will be tested without need). Instead, you can simply start at a multiple of 5 and do the range go 5 by 5:

numero1 = # ler o número
numero2 = # ler o número

# se não for múltiplo de 5, ajustar para o próximo múltiplo
resto = numero1 % 5
if resto != 0:
    numero1 += 5 - resto

# range pula de 5 em 5
print('|'.join(map(str, range(numero1, numero2 + 1, 5))))

That way, I just need to test if the first number is divisible by 5. If it is, you don’t have to do anything. If it’s not, I set to the next multiple (for example, if it’s 7, set to 10). As I now know I’m starting with a multiple of 5, the range can iterate from 5 to 5, and so I don’t need to test within the loop if the numbers are divisible by 5 (actually no longer needs the for: I can pass the range directly, because now it will only have multiples of 5).

An alternative to join is to print the range directly:

numero1 = # ler o número
numero2 = # ler o número

# se não for múltiplo de 5, ajustar para o próximo múltiplo
resto = numero1 % 5
if resto != 0:
    numero1 += 5 - resto

print(*range(numero1, numero2 + 1, 5), sep='|')

Note the asterisk before the range: it serves to make the unpacking of the values of range (it’s as if I passed each of them separately to print), and the parameter sep indicates the character that will be printed between the elements (is more or less than the another answer suggested, but without needing to create the list).


Another alternative is to use enumerate, iterating by the numbers and their respective indexes. Thus, you do not print the character | only for the first element:

numero1 = # ler o número
numero2 = # ler o número

# se não for múltiplo de 5, ajustar para o próximo múltiplo
resto = numero1 % 5
if resto != 0:
    numero1 += 5 - resto

for i, n in enumerate(range(numero1, numero2 + 1, 5)):
    if i > 0: # não é o primeiro número, coloca o separador
        print('|', end='')
    print(n, end='')

Or don’t use the index, simply check that the number is equal to the first:

numero1 = # ler o número
numero2 = # ler o número

# se não for múltiplo de 5, ajustar para o próximo múltiplo
resto = numero1 % 5
if resto != 0:
    numero1 += 5 - resto

for n in range(numero1, numero2 + 1, 5):
    if n != numero1: # não é o primeiro número, coloca o separador
        print('|', end='')
    print(n, end='')
  • His last 2 examples (enumerate and without index) are printing numbers not multiples of five: 1, 6, 11, 16...

  • 1

    @Evilmaax I left the complete code in all examples to avoid further confusion :-)

  • Boooa, thanks @hkotsubo

  • Thank you very much, I did not know this Join and nor this map, now I understand its uses and thanks also for demonstrating various ways of doing .

4

Without considering that you are not handling the input, an easy way to join the numbers would be to put them all in a list of strings and use the method join() to print the result.

This method is smart enough to do exactly what you want, ie just put the separator between the elements.

The code of the loop for and the condition if is all in a list comprehension. Each element is converted to the type str, so that the join() work.

Would look like this:

valores = input().split()    
numero1 = int(valores[0])    
numero2 = int(valores[1])

lista = [str(n) for n in range(numero1, numero2+1) if n % 5 == 0]

print('|'.join(lista)) 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.