简体   繁体   English

找出数字是否为 3 的幂的 Python 程序:给出不正确的输出

[英]Python program to find out if a number is power of 3: Giving incorrect output

def if_powerof_3(n):
    var = None
    power  = 0
    if n % 3 == 0:
        while var == 1:
            var = n / 3
            power = power + 1
            if not var % 3 == 0:
                return "{} is not a power of 3".format(n)
                break
            else:
                n = var
        else:
            return "{} is a power of 3".format(n)
    else:
        return "{} is not a power of 3".format(n)

print if_powerof_3(18)

Output : 18 is a power of 3输出:18 是 3 的幂

It is totally unexpected and a wrong output obviously but not able to figure where is my code going logically wrong and printing a mathematically incorrect output这是完全出乎意料的,显然是一个错误的输出,但无法弄清楚我的代码在哪里逻辑错误并打印出数学上不正确的输出

why are you using so many if else it can be done much simpler like this你为什么要使用这么多,否则它可以像这样更简单地完成

def if_powerof_3(n):
    var = n
    power  = 0
    while var>1:
        if var%3 ==0:
            var=var/3
            power=power+1
        else:
             return "{} is not a power of 3".format(n)
    return "{} is a power of 3".format(n)
print (if_powerof_3(27))

https://gist.github.com/bondnotanymore/9afc91cb1730c9b9f637326fafc69371 https://gist.github.com/bondnotanymore/9afc91cb1730c9b9f637326fafc69371

This is improved piece of code with a little more robustness added.这是改进的一段代码,增加了更多的健壮性。

Output输出

C:\Python27\python.exe 
C:/Users/kapil/PycharmProjects/KapilsucksatPython/py/O.py
16 is not even a multiple of 3
27 is a number, which is 3th power of 3
21 is not a power of 3, but just a multiple of 3
243 is a number, which is 5th power of 3
729 is a number, which is 6th power of 3

Process finished with exit code 0进程以退出代码 0 结束

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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