路线:
正数
y
,lg y
的二进制对数是指数x
,y == 2 ** x
。例如,自lg 8 = 3
以来8 == 2 ** 3
, 自lg(1024) = 10
,1024 == 2 ** 10
和lg(1025) ≈ 10.0014
以来lg(2013.15) ≈ 10.9752
{。}}lgCeil(x)
。实现
x
,它返回二进制日志的上限x ≥ 1
math
。请勿导入while
模块。相反,使用lgCeil(8)
循环。3
返回lgCeil(1024)
;10
返回lgCeil(1025)
,lgCeil(2013.15)
和11
都返回def lgCeil(x): startNum = 0 numOfTimes = 0 base = 2 integer = base * 2 while not(integer >= x): startNum = 2 numOfTimes = numOfTimes + 1 integer = integer * base numOfTimes = numOfTimes + startNum if (integer <= x): base**(numOfTimes+1) return numOfTimes print (lgCeil(8)) print (lgCeil(1024)) print (lgCeil(1025)) print (lgCeil(2013.15)) print (lgCeil(4))
。
我的代码:
{{1}}
我不确定我需要修理什么。
答案 0 :(得分:1)
你应该用值而不是上升来降低到零。 我写了一个工作样本,但它使用了移位,所以你的教授很可能你没有写它。你不应该简单地复制它!尝试理解并重现它!
# This is not Java, functions are lowercase with underscore.
def lg_ceil(value):
'''
calculate the n for 2^n <= value < 2^(n + 1) with a while loop (actually a bad idea)
'''
# make sure we have an int
value = int(value)
# not defined for values <= 1
if value <= 1:
return
result = 0
# as long as value != 0
while value:
# shift value one bit, this equals / 2 with integers.
value = value >> 1
# count the numbers of shifts
result += 1
# the result is the number shifts minus 1.
return result - 1
答案 1 :(得分:1)
这比你做的更简单 更简单 - 你有大致正确的实现(增加一个数字,直到你等于或超过输入),但有很多破坏事物的复杂性。
def lgCeil(x):
startNum = 0
numOfTimes = 0 # why two values to keep count?
base = 2
integer = base * 2 # what about numbers <= 2?
while not(integer >= x): # why not 'integer < x'?
startNum = 2 # always resets to 2 - why?
numOfTimes = numOfTimes + 1 # could just be '+= 1'
integer = integer * base # could just be '*= base'
numOfTimes = numOfTimes + startNum # always adding on a fixed 2
if (integer <= x):
base**(numOfTimes+1) # this line doesn't actually contribute to output
return numOfTimes
考虑这个更简单的实现:
def log_ceil(num, base=2):
"""Calculate the 'ceiling log' for the specified number."""
val = 0
while (base ** val) < num:
val += 1
return val
这也符合style guide。
答案 2 :(得分:1)
def lgCeil(x):
numOfTimes = 0
base=2
integer = 2
while not(integer >= x):
numOfTimes = numOfTimes + 1
integer = integer * base
return numOfTimes+1
答案 3 :(得分:1)
正如jonrsharpe指出的那样,你的代码最小化修正如下:
def lgCeil(x):
if (x <= 1):
return 0
startNum = 0
numOfTimes = 0
base = 2
integer = base * 1
while not(integer >= x):
startNum = 0
numOfTimes = numOfTimes + 1
integer = integer * base
numOfTimes = numOfTimes + startNum
if (integer <= x):
base**(numOfTimes+1)
return numOfTimes+1
print (lgCeil(1))
print (lgCeil(1.1))
print (lgCeil(2))
print (lgCeil(2.1))
print (lgCeil(4))
print (lgCeil(4.1))
print (lgCeil(8))
print (lgCeil(1024))
print (lgCeil(1025))
print (lgCeil(2013.15))
虽然我添加了关于x = 1的异常(Klaus D.也提及)(实际上对于0 如果您不打算使用全新版本,这只是总结一下。
答案 4 :(得分:0)
这个单行怎么样:
In [7]: len(bin(int(2013.15)).strip("0b"))
Out[7]: 11
Tweak需要支持确切的权力,例如1024,留给读者练习。