forked from devAmoghS/Python-Interview-Problems-for-Practice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
is_numeric.py
94 lines (85 loc) · 1.34 KB
/
is_numeric.py
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# Given a string, return True if it
# is a numeric data type, False otherwise
def is_numeric(input_str):
data_types = [
int,
float,
complex,
lambda T: int(T, 2), # binary
lambda T: int(T, 8), # octal
lambda T: int(T, 16), # hex
]
for dtype in data_types:
try:
dtype(input_str)
return True
except ValueError:
pass
return False
tests = [
"0",
"0.",
"00",
"123",
"0123",
"+123",
"-123",
"-123.",
"-123e-4",
"-.8E-04",
"0.123",
"(5)",
"-123+4.5j",
"0b0101",
" +0B101 ",
"0o123",
"-0xABC",
"0x1a1",
"12.5%",
"1/2",
"½",
"3¼",
"π",
"Ⅻ",
"1,000,000",
"1 000",
"- 001.20e+02",
"NaN",
"inf",
"-Infinity",
]
for s in tests:
print(s, "---", is_numeric(s))
"""
OUTPUT:
0 --- True
0. --- True
00 --- True
123 --- True
0123 --- True
+123 --- True
-123 --- True
-123. --- True
-123e-4 --- True
-.8E-04 --- True
0.123 --- True
(5) --- True
-123+4.5j --- True
0b0101 --- True
+0B101 --- True
0o123 --- True
-0xABC --- True
0x1a1 --- True
12.5% --- False
1/2 --- False
½ --- False
3¼ --- False
π --- False
Ⅻ --- False
1,000,000 --- False
1 000 --- False
- 001.20e+02 --- False
NaN --- True
inf --- True
-Infinity --- True
"""