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

Multiply an input by 5 raised to the number of digits of each numbers, but my code needs reworking

I’m trying to multiply an input * 5 raised to the power of the input.
I tried this:

def multiply(n):
return 5 ** len(str(n)) * n

I tried (n = -2), but instead of giving me -10, which is the correct answer, it gave me -50
Why doesn’t this output the correct numbers when n is negative?

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 :

you are directly checking the length of your input by casting it to string:

>>> n = -2
>>> str(n)
'-2' # String with length of two -> '-' and '2' (string 2)
>>> len(str(n))
2

Maybe you can try this (not sure if it’s good or bad, but will work as you expected):

# The dirty way.. 

def multiply(num: int):
    # Initialize a variable to keep track of length
    length = 0
    
    # Convert the input to string and iterate over it
    for n in str(num):

        # If the current character is int, increment the length variable
        try:
            if isinstance(int(n), int):
                length += 1

        # Above code will raise error for '-', catch here
        except ValueError:
            pass

    return 5 ** length * num

# Try with the input -2 again
print(multiply(-2))

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