代码之家  ›  专栏  ›  技术社区  ›  OrigamiDarknessDragon

将输入乘以5,得到每个数字的位数,但我的代码需要重新编写

  •  1
  • OrigamiDarknessDragon  · 技术社区  · 1 年前

    我试图将输入*5乘以输入的幂。 我试过这个:

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

    我试过(n=-2),但它没有给我-10(正确答案),而是给了我-50 为什么当n为负时,它不能输出正确的数字?

    2 回复  |  直到 1 年前
        1
  •  3
  •   Momo    1 年前

    -当转换为字符串时,2的长度为2,因为它对负号进行计数。因此,它正在计算 5 ** 2 * -2 = -50 .

    在计数数字时,您希望忽略负号。你可以试试 len(str(abs(n))) ,它将忽略负号并给出正确答案。

        2
  •  1
  •   Cheap Nightbot    1 年前

    您可以通过将输入转换为字符串来直接检查输入的长度:

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

    也许你可以试试这个(不确定它是好是坏,但会像你预期的那样工作):

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