Nếu bạn quan tâm đến hiệu suất (và tôi không khuyên bạn nên), cách tiếp cận dựa trên thử là chiến thắng rõ ràng (so với cách tiếp cận dựa trên phân vùng hoặc cách tiếp cận regrec), miễn là bạn không mong đợi nhiều chuỗi không hợp lệ, trong trường hợp đó có khả năng chậm hơn (có lẽ là do chi phí xử lý ngoại lệ).
Một lần nữa, tôi không đề nghị bạn quan tâm đến hiệu suất, chỉ cung cấp cho bạn dữ liệu trong trường hợp bạn thực hiện việc này 10 tỷ lần một giây hoặc một cái gì đó. Ngoài ra, mã dựa trên phân vùng không xử lý ít nhất một chuỗi hợp lệ.
$ ./floatstr.py
F ..
phân vùng buồn: 3.1102449894
phân vùng hạnh phúc: 2.09208488464
..
lại buồn: 7.76906108856
hạnh phúc: 7.09421992302
..
thử buồn: 12.1525540352
cố gắng hạnh phúc: 1.44165301323
.
================================================== ====================
FAIL: test_partition (__main __. ConvertTests)
-------------------------------------------------- --------------------
TracBack (cuộc gọi gần đây nhất vừa qua):
Tệp "./floatstr.py", dòng 48, trong test_partition
self.failUnless (is_float_partition ("20e2"))
Khẳng địnhError
-------------------------------------------------- --------------------
Chạy thử nghiệm 8 trong 33.670
FAILED (thất bại = 1)
Đây là mã (Python 2.6, regrec lấy từ câu trả lời của John Gietzen ):
def is_float_try(str):
try:
float(str)
return True
except ValueError:
return False
import re
_float_regexp = re.compile(r"^[-+]?(?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b)(?:[eE][-+]?[0-9]+\b)?$")
def is_float_re(str):
return re.match(_float_regexp, str)
def is_float_partition(element):
partition=element.partition('.')
if (partition[0].isdigit() and partition[1]=='.' and partition[2].isdigit()) or (partition[0]=='' and partition[1]=='.' and pa\
rtition[2].isdigit()) or (partition[0].isdigit() and partition[1]=='.' and partition[2]==''):
return True
if __name__ == '__main__':
import unittest
import timeit
class ConvertTests(unittest.TestCase):
def test_re(self):
self.failUnless(is_float_re("20e2"))
def test_try(self):
self.failUnless(is_float_try("20e2"))
def test_re_perf(self):
print
print 're sad:', timeit.Timer('floatstr.is_float_re("12.2x")', "import floatstr").timeit()
print 're happy:', timeit.Timer('floatstr.is_float_re("12.2")', "import floatstr").timeit()
def test_try_perf(self):
print
print 'try sad:', timeit.Timer('floatstr.is_float_try("12.2x")', "import floatstr").timeit()
print 'try happy:', timeit.Timer('floatstr.is_float_try("12.2")', "import floatstr").timeit()
def test_partition_perf(self):
print
print 'partition sad:', timeit.Timer('floatstr.is_float_partition("12.2x")', "import floatstr").timeit()
print 'partition happy:', timeit.Timer('floatstr.is_float_partition("12.2")', "import floatstr").timeit()
def test_partition(self):
self.failUnless(is_float_partition("20e2"))
def test_partition2(self):
self.failUnless(is_float_partition(".2"))
def test_partition3(self):
self.failIf(is_float_partition("1234x.2"))
unittest.main()