SORU
3 ŞUBAT 2010, ÇARŞAMBA


Python bir tamsayı uzunluğu

Python, nasıl bir tamsayı basamak buluyor musunuz?

CEVAP
3 ŞUBAT 2010, ÇARŞAMBA


Dize dönüştürme olmadan

import math
digits = int(math.log10(n)) 1

Ayrıca sıfır ve negatif sayılar işlemek için

import math
if n > 0:
    digits = int(math.log10(n)) 1
elif n == 0:
    digits = 1
else:
    digits = int(math.log10(-n)) 2 #  1 if you don't count the '-' 

Muhtemelen bir fonksiyon:) koymak istersin

İşte bazı kriterler. len(str()) bile oldukça küçük sayılar için zaten arkasında

timeit math.log10(2**8)
1000000 loops, best of 3: 746 ns per loop
timeit len(str(2**8))
1000000 loops, best of 3: 1.1 µs per loop

timeit math.log10(2**100)
1000000 loops, best of 3: 775 ns per loop
 timeit len(str(2**100))
100000 loops, best of 3: 3.2 µs per loop

timeit math.log10(2**10000)
1000000 loops, best of 3: 844 ns per loop
timeit len(str(2**10000))
100 loops, best of 3: 10.3 ms per loop

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • BaaaStuds's channel

    BaaaStuds's

    10 Mart 2009
  • Bennythecoder

    Bennythecode

    25 Mart 2008
  • lane182videos

    lane182video

    6 EKİM 2011