How can I add a hyphen between all even numbers of a value?

Asked

Viewed 388 times

7

Good morning, could someone help me with a code please, I need to insert a hyphen (-) between two even numbers. For example, if you receive the number 02368859 as input, the output of the program should be: 0-236-8-859 I did so, but you are in error.

num = input("Digite um número:")

def separador(num):
    num = list(num)
    fim = 1
    i = 0
    saida=''
    while i <len(num):
        if int(num[i])%2==0:
            saida+=num[i]
            if int(num[fim])%2==0:
                 saida+='-'
            i+=1
            fim+=1
        else:
            saida+=num[i]
            i+=1
            fim+=1        
    print(saida)

separador(num)

4 answers

5


Regular Expressions

You can do this with regular expressions:

([02468]{2,})

Captures any sequence formed by the numbers 0, 2, 4, 6 or 8 with two or more of size. After capturing the sequences of even numbers just replace by itself by adding the hyphen:

'-'.join(grupo_capturado)  # '-'.join('28') = '2-8'

So the code stays:

import re

def adiciona_separador(matches):
    return '-'.join(matches.group(0))

resultado = re.sub(r'([02468]{2,})', adiciona_separador, '02368859')

print(resultado)  # 0-236-8-859

If you want to do a function for that:

def separador(numero, separador='-'):
    return re.sub(
        r'([02468]{2,})', 
        lambda matches: separador.join(matches.group(0)), 
        numero
    )

print( separador('02368859') )  # 0-236-8-859

See working on Repl.it | Ideone


Forma Iterativa

Iteratively, as you tried to do, you can go directly through the string, do not need to convert it to a list. In Python strings are iterable as well. You can iterate over the characters in this string adding them into a string and whenever you find an even number you check whether the last value of this string is also even, if yes, you add a hyphen before adding the current number.

def separador(entrada):
    resultado = ''

    for caractere in entrada:
        if caractere in '02468':
            if len(resultado) > 0 and resultado[-1] in '02468':
                resultado += '-'
        resultado += caractere

    return resultado

print(separador('02368859'))  # 0-236-8-859

See working on Repl.it | Ideone

  • Okay, I’ll study her here. Thank you very much Anderson.

  • Ball show! :)

  • You got practically on a command line, congratulations. I see I have to study hard yet.

  • 1

    @Rafaelm. I’ve added a shape that’s basically what you’ve done, only a more streamlined form.

  • I was analyzing and lacked a little more logic in mine. This yours became simple and good.

  • 1

    If I were to do this exercise, my initial attempt would be similar to your approach with regex, but using Lookahead to insert the hyphens. Example: re.sub(r'([02468])((?=([02468])))', r'\1-\2', '02368859')

  • @Gabriel Does not want to post this alternative as an answer?

  • @Andersoncarloswoss Feito.

Show 3 more comments

3

  • I’ll look at the references Gabriel. Thank you.

1

I found another approach in pure Python, quite similar to @Andersoncalos iteration code.

In it, I repeat each item from 0 to penultimate, adding this number to the output. And I check that both item "a" (current iteration index) and item "b" (current index + 1) are pairs. If so, I also add the "-" between them.

This would be function:

def separador2(num):
    saida = ''
    pares = '02468'
    for indice in range(len(num)-1):
        saida += num[indice] # Já adiciono o algarismo
        if num[indice] in pares and num[indice+1] in pares: # Se o "indice+1" for par também...
            saida += '-'
    saida += num[-1] #Adiciono o último caractere que eu omiti
    return saida

assert separador2('02368859') == '0-236-8-859'
  • 1

    It seems to me it’s the same logic as yours, but only with the bow it’s instead of the while.

  • 2

    Good morning Breno, I liked the pure approach. Really good. Vlw.

0

I did it the way @Breno mentioned, but with small modifications to adapt to the proposed exercise.

num = input("Informe os valores:")
def separador(num):
saida = ''
pares = '02468'

for x in range(len(num)-1):
    saida += num[x]
    if num[x] in pares and num[x+1] in pares:
        saida += '-'
saida += num[-1]
print(saida)


separador(num)

Browser other questions tagged

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