Search code examples
pythonpython-3.x

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?


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))