Skip to content

Commit a9058ee

Browse files
author
Amogh Singhal
authored
Create is_numeric.py
1 parent 9cda457 commit a9058ee

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

is_numeric.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# Given a string, return True if it
2+
# is a numeric data type, False otherwise
3+
4+
def is_numeric(input_str):
5+
6+
data_types = [int, float, complex,
7+
lambda T: int(T, 2), # binary
8+
lambda T: int(T, 8), # octal
9+
lambda T: int(T, 16) # hex
10+
]
11+
12+
for dtype in data_types:
13+
try:
14+
dtype(input_str)
15+
return True
16+
except ValueError:
17+
pass
18+
return False
19+
20+
tests = [
21+
'0', '0.', '00', '123', '0123', '+123', '-123', '-123.', '-123e-4', '-.8E-04',
22+
'0.123', '(5)', '-123+4.5j', '0b0101', ' +0B101 ', '0o123', '-0xABC', '0x1a1',
23+
'12.5%', '1/2', '½', '3¼', 'π', 'Ⅻ', '1,000,000', '1 000', '- 001.20e+02',
24+
'NaN', 'inf', '-Infinity']
25+
26+
for s in tests:
27+
print(s,"---",is_numeric(s))
28+
29+
"""
30+
OUTPUT:
31+
32+
0 --- True
33+
0. --- True
34+
00 --- True
35+
123 --- True
36+
0123 --- True
37+
+123 --- True
38+
-123 --- True
39+
-123. --- True
40+
-123e-4 --- True
41+
-.8E-04 --- True
42+
0.123 --- True
43+
(5) --- True
44+
-123+4.5j --- True
45+
0b0101 --- True
46+
+0B101 --- True
47+
0o123 --- True
48+
-0xABC --- True
49+
0x1a1 --- True
50+
12.5% --- False
51+
1/2 --- False
52+
½ --- False
53+
3¼ --- False
54+
π --- False
55+
Ⅻ --- False
56+
1,000,000 --- False
57+
1 000 --- False
58+
- 001.20e+02 --- False
59+
NaN --- True
60+
inf --- True
61+
-Infinity --- True
62+
"""

0 commit comments

Comments
 (0)