Python:最接近目标的力量

时间:2015-09-06 04:06:13

标签: python target

我试图找到大于或等于目标值的最接近2的幂。必须使用for循环来实现此目的。但是,我不确定将什么作为范围值,以便在达到所需值时,指数将停止增加i,而是退出for循环。谢谢你的帮助。

target = int(input("Enter target number: "))
def power_of_two(target):

    x = 2
    change = 0
    power = 0
    for i in range():
        number = x ** change
        change = i
    if number >= target:
        power = number
    return power
p = power_of_two(target)
print("The closest power of 2 >= {0:d} is {1:d}." .format(target, p))

2 个答案:

答案 0 :(得分:2)

因为您必须使用:

def power_of_two(target):
    if target > 1:
        for i in range(1, int(target)):
            if (2 ** i >= target):
                return 2 ** i
    else:
        return 1

假设您希望该值大于或等于2 ^ 0

答案 1 :(得分:1)

我已更正您的代码,以便它可以正常工作。我认为你从错误中学得最好:)

target = int(input("Enter target number: "))

def power_of_two(target):
    x = 2
    change = 0
    power = 0
    for i in range(target+1):
                       # target is okay for this, function terminates anyway
                       # add one to avoid error if target=0
        number = x ** change
        change = i
        if number >= target:  # you had indentation errors here and following
            power = number    
            return power

p = power_of_two(target)
print("The closest power of 2 >= {0:d} is {1:d}." .format(target, p))

您可以使用对数为2的对数找到范围结束的完美值,但是无论如何您都不需要for循环;)

作为一个建议:也许看一下2的幂的二进制表示。你可以使用带有位移的for循环。

编辑:我自己有缩进错误,因为这里有奇怪的格式化系统......也许你以前没有这些:D