与えられた数字のケタ数
Posted feedbacks - Python
何も考えずに超簡単に。 (4, 1000) (3, 100) (8, 10000000) (6, 100000) (7, 1000000) (1, 1)
1 2 3 4 5 6 7 8 9 10 11 12 13 | def getKetaAndKurai(num):
s = str(num)
keta = len(s)
kurai = int("1" + "0" * (keta - 1))
return (keta, kurai)
print getKetaAndKurai(2469)
print getKetaAndKurai(600)
print getKetaAndKurai(12378990)
print getKetaAndKurai(414879)
print getKetaAndKurai(3141592)
print getKetaAndKurai(1)
|
とりあえず。
1 | f = lambda i: (len(str(i)), 10 ** (len(str(i)) - 1))
|
0とか負数のときはどうすればいいんだろう。適当に処理しておいたけど。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
def digits(n):
"""
returns count of digits and order of most siginificant digit.
>>> digits(2469)
(4, 1000)
>>> digits(600)
(3, 100)
>>> digits(1)
(1, 1)
>>> digits(0)
(1, 1)
>>> digits(-100)
(3, 100)
"""
if n < 0:
n = -n
s = str(n)
return (len(s), 10 ** (len(s) - 1))
def _test():
import doctest
doctest.testmod()
if __name__ == '__main__':
_test()
|
>計算量を考えるなら、log使うのがベストですよね。 必ずしもそうとは言えないんじゃないでしょうか。 このコードを私の環境(Linux PowerPC 200MHz)で動かすとこんな感じでした。 >>> time_it(num_digits_log, 99999) 6.8320038318634033 >>> time_it(num_digits_str, 99999) 5.2861831188201904 >>> time_it(num_digits_log, 99999) 6.8249599933624268 >>> time_it(num_digits_str, 99999) 5.2954750061035156
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import math
import time
def time_it(f, count):
tic = time.time()
for i in xrange(1, count):
f(i)
toc = time.time()
return toc - tic
def num_digits_log(n):
return int(math.log10(n)) + 1
def num_digits_str(n):
return len(str(n))
|
定義の曖昧な問題を作ったお詫びとして、小数と複素数にも対応してみました(仮)。 あと文字列って元からほぼリストなんですね。わざわざlist()で分解してました。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | def float_place(num):
if num<0 : num=num*-1
item = str(num)
if isinstance(num,float):
try: point = item.index(".")
except: point = item.index(",")
return ( len(item[:point]),len(item[point+1:]) )
else:
return len(item),1
def place(num):
"とりあえず小数の0も1ケタで。"
res = {}
if isinstance(num,complex):
num2= num.imag
num = num.real
res['complex'],res['cfloat'] = float_place(num2)
res['int'],res['float'] = float_place(num)
for i in res:#最大桁の位を追加
res[i] = (res[i],10**(res[i]-1))
return res
place(-1234.5-12.345j)
|
重複部分を排除してみました。
1 2 | import math
f = lambda n: (lambda x:(1+x,10**x))(int(math.log(n,10)))
|
無駄な括弧を取り除いて63バイトにしてみました。
1 | import math;f=lambda n:lambda x=int(math.log(n,10)):(1+x,10**x)
|





susu
#3396()
Rating0/0=0.00
このお題はsusuさんの投稿です。ご投稿ありがとうございます。
[ reply ]