Python 2.7 - Count number of items in Output

I need to count the number of items in my output. So for example i created this:

a =1000000
while a >=10:
    print a
    a=a/2

How would i count how many halving steps were carried out? Thanks

Upvotes: 0

Views: 759

Answers (2)

Prajjwal Srivastav
Prajjwal Srivastav

Reputation: 392

c = 0
a = 1000000 
while a >= 10: 
  print a
  a = a / 2
  c = c + 1

Upvotes: 0

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

You have 2 ways: the empiric way and the predictible way.

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))

I get:

theorical iterations 17
real iterations 17

The experimental method just counts the iterations, whereas the predictive method relies on the rounded (to upper bound) result of log2 value of a (which matches the complexity of the algorithm).

(It's rounded to upper bound because if it's more than 16, then you need 17 iterations)

Upvotes: 1

Related Questions