Python 2.7 Python2.7-计算输出中的项数

Python 2.7 Python2.7-计算输出中的项数,python-2.7,Python 2.7,我需要计算输出中的项目数。 例如,我创建了这个: a =1000000 while a >=10: print a a=a/2 我如何计算执行了多少减半步骤? 谢谢你有两种方法:经验性方法和可预测性方法 a =1000000 import math print("theorical iterations {}".format(int(math.log2(a//10)+0.5))) counter=0 while a >=10: counter+=1

我需要计算输出中的项目数。 例如,我创建了这个:

a =1000000
while a >=10:
    print a
    a=a/2
我如何计算执行了多少减半步骤?
谢谢

你有两种方法:经验性方法和可预测性方法

a =1000000

import math
print("theorical iterations {}".format(int(math.log2(a//10)+0.5)))

counter=0
while a >=10:
    counter+=1
    a//=2

print("real iterations {}".format(counter))
我得到:

theorical iterations 17
real iterations 17
实验方法只计算迭代次数,而预测方法依赖于
log2
a
的四舍五入(到上限)结果(与算法的复杂度相匹配)


(四舍五入到上限,因为如果大于16,则需要17次迭代)

感谢您的回复。不明白你在那里做了什么?最后加上C=0和C++给了我一个合成错误。我编辑了代码。您可以打印c以找出a减半的次数。在循环期间将其存储在变量中。
theorical iterations 17
real iterations 17