Skip to content

Instantly share code, notes, and snippets.

@kwikwag
Last active April 4, 2016 17:02
Show Gist options
  • Save kwikwag/11fe7228a4fe4f82054d70e6580f6c1b to your computer and use it in GitHub Desktop.
Save kwikwag/11fe7228a4fe4f82054d70e6580f6c1b to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import re
import fastnumbers
def is_int1(v):
try:
int(v)
return True
except ValueError:
return False
def is_int2(v):
return v.lstrip('+-').isdigit()
def is_float1(v):
try:
float(v)
return True
except:
return False
_float_regexp = re.compile(r"^[-+]?(?:[Nn][Aa][Nn]|[Ii][Nn][Ff](?:[Ii][Nn][Ii][Tt][Yy])?|(?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][-+]?[0-9]+\b)?)$").match
def is_float2(v):
return True if _float_regexp(v) else False
def is_float3(v):
return fastnumbers.isfloat(v)
def test_for_inputs(func, inputs):
for s in inputs:
func(s)
import timeit
import itertools
if __name__ == '__main__':
number = 100000
inputs = ["238764", "2", "sdkjhf", "4398265.238476"]
exponents = ['', 'e3', 'e+3', 'e-3', 'e03', 'e+03', 'e-03', 'ee3']
exponents += [ s.upper() for s in exponents ]
inputs += [ ''.join(t) for t in list(itertools.product(['', '+', '-', '+-', '.'], ['', '1', '1.', '.1', '0x1', '..'], exponents)) ]
special_values = ['Inf', 'NaN', 'Infinity', 'Infi']
special_values += [ s.upper() for s in special_values ] + [ s.lower() for s in special_values ]
inputs += [ ''.join(t) for t in list(itertools.product(['', '+', '-'], special_values)) ]
# for func in ["is_int1", "is_int2", "is_float1", "is_float2", "is_float3"]:
for func in ["is_float1", "is_float2", "is_float3"]:
for s in inputs:
print 'func=%s, input=%s, answer=%s' % (func, s, str( locals()[func](s) ))
print 'func=%s, time=%f' % (func, timeit.timeit('test_for_inputs(%s, inputs)' % (func,), setup='from __main__ import %s, inputs, test_for_inputs' % (func,), number=number))
@kwikwag
Copy link
Author

kwikwag commented Apr 4, 2016

I commented out the is_int tests for my tests, as apparent in the gist.

Timing outputs on my machine:

func=is_float1, time=46.657828
func=is_float2, time=30.435496
func=is_float3, time=10.895729

Results agrees for all inputs between those three methods, except for the special values.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment