Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does the last letter doesn't add up where it belongs?

i am pretty new to coding in python and we have some programs to make for class.
The program needs to split without slicing or other functions the first part of a digit -> 12.5 becomes 12 and 5. I have so managed to make this which works only for the first part and then the last digit doesn’t add up where it belongs. Could you explain me why?

def decoupage(nombre:str)->(str,str):
    partie_entiere = ''
    partie_decimale = ''
    delimiteurs = [',','.']
    compte = 0
    for lettre in nombre:
        if lettre not in delimiteurs:
            if compte != 1:
                partie_entiere += lettre
        elif compte == 1:
                partie_decimale += lettre
        else:
            compte += 1
    return partie_entiere, partie_decimale


assert decoupage("12.5") == ('12', '5')
assert decoupage("12,5") == ('12', '5')
assert decoupage("0.5") == ('0', '5')
assert decoupage("12") == ('12', '0')

Tried to execute the code line by line and then i saw the problem, 12 finishes where it belongs "partie_entiere" then "partie_decimale" doesn’t have 5 in it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this?

def decoupage(word:str)->(str, str):
    entire_part = ''
    decimal_part = ''
    delimiters = [',','.']

    after = False
    for letter in word:
        if not after:
            after = letter in delimiters
            if letter not in delimiters:
                entire_part += letter
        else:
            decimal_part += letter

    if decimal_part == '':
        decimal_part = '0'
        
    return entire_part, decimal_part



assert decoupage("12.5") == ('12', '5')
assert decoupage("12,5") == ('12', '5')
assert decoupage("0.5") == ('0', '5')
assert decoupage("12") == ('12', '0')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading