Advertisement
Guest User

Untitled

a guest
Sep 30th, 2016
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.28 KB | None | 0 0
  1. def is_number(s):
  2. try:
  3. float(s)
  4. return True
  5. except ValueError:
  6. return False
  7.  
  8. >>> a = "03523"
  9. >>> a.isdigit()
  10. True
  11. >>> b = "963spam"
  12. >>> b.isdigit()
  13. False
  14.  
  15. >>> float('NaN')
  16. nan
  17.  
  18. '3.14'.replace('.','',1).isdigit()
  19.  
  20. '3.14.5'.replace('.','',1).isdigit()
  21.  
  22. def is_number(s):
  23. try:
  24. complex(s) # for int, long, float and complex
  25. except ValueError:
  26. return False
  27.  
  28. return True
  29.  
  30. def is_number(s):
  31. try:
  32. float(s) # for int, long and float
  33. except ValueError:
  34. try:
  35. complex(s) # for complex
  36. except ValueError:
  37. return False
  38.  
  39. return True
  40.  
  41. def parse(string):
  42. try:
  43. return float(string)
  44. except Exception:
  45. throw TypeError
  46.  
  47. def try_parse(string, fail=None):
  48. try:
  49. return float(string)
  50. except Exception:
  51. return fail;
  52.  
  53. def monkey_patch():
  54. if(!hasattr(float, 'parse')):
  55. float.parse = parse
  56. if(!hasattr(float, 'try_parse')):
  57. float.try_parse = try_parse
  58.  
  59. float.parse('giggity') // throws TypeException
  60. float.parse('54.3') // returns the scalar value 54.3
  61. float.tryParse('twank') // returns None
  62. float.tryParse('32.2') // returns the scalar value 32.2
  63.  
  64. from __future__ import print_function
  65. import timeit
  66.  
  67. prep_base = '''
  68. x = 'invalid'
  69. y = '5402'
  70. z = '4.754e3'
  71. '''
  72.  
  73. prep_try_method = '''
  74. def is_number_try(val):
  75. try:
  76. float(val)
  77. return True
  78. except ValueError:
  79. return False
  80.  
  81. '''
  82.  
  83. prep_re_method = '''
  84. import re
  85. float_match = re.compile(r'[-+]?d*.?d+(?:[eE][-+]?d+)?$').match
  86. def is_number_re(val):
  87. return bool(float_match(val))
  88.  
  89. '''
  90.  
  91. fn_method = '''
  92. from fastnumbers import isfloat
  93.  
  94. '''
  95.  
  96. print('Try with non-number strings', timeit.timeit('is_number_try(x)',
  97. prep_base + prep_try_method), 'seconds')
  98. print('Try with integer strings', timeit.timeit('is_number_try(y)',
  99. prep_base + prep_try_method), 'seconds')
  100. print('Try with float strings', timeit.timeit('is_number_try(z)',
  101. prep_base + prep_try_method), 'seconds')
  102. print()
  103. print('Regex with non-number strings', timeit.timeit('is_number_re(x)',
  104. prep_base + prep_re_method), 'seconds')
  105. print('Regex with integer strings', timeit.timeit('is_number_re(y)',
  106. prep_base + prep_re_method), 'seconds')
  107. print('Regex with float strings', timeit.timeit('is_number_re(z)',
  108. prep_base + prep_re_method), 'seconds')
  109. print()
  110. print('fastnumbers with non-number strings', timeit.timeit('isfloat(x)',
  111. prep_base + 'from fastnumbers import isfloat'), 'seconds')
  112. print('fastnumbers with integer strings', timeit.timeit('isfloat(y)',
  113. prep_base + 'from fastnumbers import isfloat'), 'seconds')
  114. print('fastnumbers with float strings', timeit.timeit('isfloat(z)',
  115. prep_base + 'from fastnumbers import isfloat'), 'seconds')
  116. print()
  117.  
  118. Try with non-number strings 2.39108395576 seconds
  119. Try with integer strings 0.375686168671 seconds
  120. Try with float strings 0.369210958481 seconds
  121.  
  122. Regex with non-number strings 0.748660802841 seconds
  123. Regex with integer strings 1.02021503448 seconds
  124. Regex with float strings 1.08564686775 seconds
  125.  
  126. fastnumbers with non-number strings 0.174362897873 seconds
  127. fastnumbers with integer strings 0.179651021957 seconds
  128. fastnumbers with float strings 0.20222902298 seconds
  129.  
  130. >>> "1221323".isdigit()
  131. True
  132.  
  133. >>> "12.34".isdigit()
  134. False
  135. >>> "12.34".replace('.','',1).isdigit()
  136. True
  137. >>> "12.3.4".replace('.','',1).isdigit()
  138. False
  139.  
  140. >>> '-12'.lstrip('-')
  141. '12'
  142.  
  143. >>> '-12.34'.lstrip('-').replace('.','',1).isdigit()
  144. True
  145. >>> '.-234'.lstrip('-').replace('.','',1).isdigit()
  146. False
  147.  
  148. >>> s = u"345"
  149. >>> s.isnumeric()
  150. True
  151.  
  152. >>> s = "345"
  153. >>> u = unicode(s)
  154. >>> u.isnumeric()
  155. True
  156.  
  157. if str.isdigit():
  158. returns TRUE or FALSE
  159.  
  160. def is_number(s):
  161. try:
  162. n=str(float(s))
  163. if n == "nan" or n=="inf" or n=="-inf" : return False
  164. except ValueError:
  165. try:
  166. complex(s) # for complex
  167. except ValueError:
  168. return False
  169. return True
  170.  
  171. import time
  172. import re
  173.  
  174. check_regexp = re.compile("^d*.?d*$")
  175.  
  176. check_replace = lambda x: x.replace('.','',1).isdigit()
  177.  
  178. numbers = [str(float(x) / 100) for x in xrange(10000000)]
  179.  
  180. def is_number(s):
  181. try:
  182. float(s)
  183. return True
  184. except ValueError:
  185. return False
  186.  
  187. start = time.time()
  188. b = [is_number(x) for x in numbers]
  189. print time.time() - start # returns 4.10500001907
  190.  
  191. start = time.time()
  192. b = [check_regexp.match(x) for x in numbers]
  193. print time.time() - start # returns 5.41799998283
  194.  
  195. start = time.time()
  196. b = [check_replace(x) for x in numbers]
  197. print time.time() - start # returns 4.5110001564
  198.  
  199. try:
  200. myvar.append( float(string_to_check) )
  201. except:
  202. continue
  203.  
  204. def is_number_tryexcept(s):
  205. """ Returns True is string is a number. """
  206. try:
  207. float(s)
  208. return True
  209. except ValueError:
  210. return False
  211.  
  212. import re
  213. def is_number_regex(s):
  214. """ Returns True is string is a number. """
  215. if re.match("^d+?.d+?$", s) is None:
  216. return s.isdigit()
  217. return True
  218.  
  219.  
  220. def is_number_repl_isdigit(s):
  221. """ Returns True is string is a number. """
  222. return s.replace('.','',1).isdigit()
  223.  
  224. funcs = [
  225. is_number_tryexcept,
  226. is_number_regex,
  227. is_number_repl_isdigit
  228. ]
  229.  
  230. a_float = '.1234'
  231.  
  232. print('Float notation ".1234" is not supported by:')
  233. for f in funcs:
  234. if not f(a_float):
  235. print('t -', f.__name__)
  236.  
  237. scientific1 = '1.000000e+50'
  238. scientific2 = '1e50'
  239.  
  240.  
  241. print('Scientific notation "1.000000e+50" is not supported by:')
  242. for f in funcs:
  243. if not f(scientific1):
  244. print('t -', f.__name__)
  245.  
  246.  
  247.  
  248.  
  249. print('Scientific notation "1e50" is not supported by:')
  250. for f in funcs:
  251. if not f(scientific2):
  252. print('t -', f.__name__)
  253.  
  254. def str_to_type (s):
  255. """ Get possible cast type for a string
  256.  
  257. Parameters
  258. ----------
  259. s : string
  260.  
  261. Returns
  262. -------
  263. float,int,str,bool : type
  264. Depending on what it can be cast to
  265.  
  266. """
  267. try:
  268. f = float(s)
  269. if "." not in s:
  270. return int
  271. return float
  272. except ValueError:
  273. value = s.upper()
  274. if value == "TRUE" or value == "FALSE":
  275. return bool
  276. return type(s)
  277.  
  278. str_to_type("true") # bool
  279. str_to_type("6.0") # float
  280. str_to_type("6") # int
  281. str_to_type("6abc") # str
  282. str_to_type(u"6abc") # unicode
  283.  
  284. s = "6.0"
  285. type_ = str_to_type(s) # float
  286. f = type_(s)
  287.  
  288. def string_or_number(s):
  289. try:
  290. z = int(s)
  291. return z
  292. except ValueError:
  293. try:
  294. z = float(s)
  295. return z
  296. except ValueError:
  297. return s
  298.  
  299. def is_number(var):
  300. try:
  301. if var == int(var):
  302. return True
  303. except Exception:
  304. return False
  305.  
  306. def isFloat(s):
  307. realFloat = 0.1
  308.  
  309. if type(s) == type(realFloat):
  310. return True
  311. else:
  312. return False
  313.  
  314. False # s = 5
  315. True # s = 1.2345
  316.  
  317. import sys
  318.  
  319. def fix_quotes(s):
  320. try:
  321. float(s)
  322. return s
  323. except ValueError:
  324. return '"{0}"'.format(s)
  325.  
  326. for line in sys.stdin:
  327. input = line.split()
  328. print input[0], '<- c(', ','.join(fix_quotes(c) for c in input[1:]), ')'
  329.  
  330. number = raw_input("Enter a number: ")
  331. if re.match(r'^d+$', number):
  332. print "It's integer"
  333. print int(number)
  334. elif re.match(r'^d+.d+$', number):
  335. print "It's float"
  336. print float(number)
  337. else:
  338. print("Please enter a number")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement