简体   繁体   中英

Python different output when casting the recursive call with str function

I want the result to be of Type String, so i tried to cast the recursive call with str function

When returning a result of Type int the function below works fine

def factor(n: int) -> int:
    if n <= 1:
        return 1
    return n * factor(n - 1)


print("factorial 5=", factor(5))

Output:

factorial 5= 120

But when casting the recursive call to str str(n * factor(n - 1)) i got a different result

def factor(n: int) -> str:
    if n <= 1:
        return 1
    return str(n * factor(n - 1))


print("factorial 5=", factor(5))

Output:

factorial 5= 222222222222222222222222222222222222222222222222222222222222

What am i doing wrong?

The recursion depends on being called recursively with an int argument. Therefore, you need a wrapper like

def factor(n: int) -> str:
    def factor_internal(n: int):
        if n <= 1:
            return 1
        return n*factor_internal(n - 1)
    
    return str(factor_internal(n))


print("factorial 5=", factor(5))

In your implementation, the multiplication n*factor(n-1) is a multiplication of an integer n with a string factor(n-1) . And in Python, this results in a concatenation of strings, n -times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM