【问题标题】:Enter inputs only power of 2输入仅输入 2 的幂
【发布时间】:2015-07-17 06:11:39
【问题描述】:

这是一个简单的问题,但我被困住了。

我正在编写一个简单的程序来获取一个输入值,该值是2 的不同倍数。也就是说,它必须是2^x 的形式,包括1,即2^0=1

所以,唯一有效的输入是1, 2, 4, 8, 16, 32, 等。如果用户输入3,我的程序会抛出错误。我还将输入从1 限制为8192(其中8192 = 2**13)。如果用户输入10000-30,我会抛出一个错误。

这是我目前所拥有的。

def checkValue():
maxValue = 8192
while True:
    try:
        intValue = int(input('Please enter integer: '))
    except ValueError:
        print("Value must be an integer!")
        continue
    else:
        if intValue < 1:
            print("Value cannot be less than 1")
            continue
        elif intValue > 8192: 
            print("Value cannot be greater than 8192")
            continue
        else:
            return("The value is equal to " + str(intValue) )

必须有一种简单的方法来测试输入是否为2 的幂。不过,我不确定如何在我当前的代码中加入这样的测试。由于我只接受 14 值作为有效输入(即 1 和高达 2**13 的值),也许这是最有效的测试?

感谢任何建议。谢谢。

【问题讨论】:

    标签: python input types


    【解决方案1】:

    只需使用以 2 为底的对数即可,并检查数字是否为整数:

    float.is_integer(math.log(x, 2)) # test if number is whole
    

    【讨论】:

    • @ShanZhengYang 如果对你有用,请在旁边打勾标记为答案。
    • 目前,我的 intValue 在函数内部。如何使用稍后在代码中输入到 input() 中的内容?目前,稍后使用intValue 会导致错误。
    • return 你想要的值并将返回的值赋给一个变量。
    • return 放在第一个while 循环之外,然后将该值分配给我希望稍后使用的变量?那么return intValue 然后value = intValue?我会试试的
    【解决方案2】:

    如果你检查输入的intValuelog2是否为整数-

    import math
    if int(math.log2(intValue)) == math.log2(intValue):
        return("The value is equal to " + str(intValue) )
    else:
        # print error...
    

    例如,如果intValue 为 32,您将获得 True,但对于 33,您将获得 False

    此外,您还可以检查 math.log2(intValue) 是否小于或等于 13,以满足您在小于 8192 之间的值的其他约束。

    【讨论】:

      【解决方案3】:

      你可以测试:

      (math.log(n,2)).is_integer()
      

      【讨论】:

        【解决方案4】:

        这个怎么样?

        def checkValue():
            maxValue = 8192
            while True:
                try:
                    intValue = int(input('Please enter integer: '))
                except ValueError:
                    print("Value must be an integer!")
                    continue
                else:
                    if intValue in [1, 2, 4, 8, 16, 32]:
                        return("The value is equal to " + str(intValue))
                    elif intValue < 1:
                        print("Value cannot be less than 1")
                        continue
                    elif intValue > 8192: 
                        print("Value cannot be greater than 8192")
                        continue
                    else:
                        return("Error")
        

        【讨论】:

        • 这是最简单的实现。谢谢!
        猜你喜欢
        • 2014-04-26
        • 2018-01-27
        • 1970-01-01
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多