-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdetermine-if-the-number-is-valid.py
69 lines (57 loc) · 1.42 KB
/
determine-if-the-number-is-valid.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
class STATE:
START, INTEGER, DECIMAL, UNKNOWN, AFTER_DECIMAL = range(5)
def get_next_state(current_state, ch):
if (current_state == STATE.START or
current_state == STATE.INTEGER):
if ch == '.':
return STATE.DECIMAL
elif ch >= '0' and ch <= '9':
return STATE.INTEGER
else:
return STATE.UNKNOWN
if current_state == STATE.DECIMAL:
if ch >= '0' and ch <= '9':
return STATE.AFTER_DECIMAL
else:
return STATE.UNKNOWN
if current_state == STATE.AFTER_DECIMAL:
if ch >= '0' and ch <= '9':
return STATE.AFTER_DECIMAL
else:
return STATE.UNKNOWN
return STATE.UNKNOWN
def is_number_valid(s):
if not s:
return True
i = 0
if s[i] == '+' or s[i] == '-':
i = i + 1
current_state = STATE.START
for c in s[i:]:
current_state = get_next_state(current_state, c)
if current_state == STATE.UNKNOWN:
return False
i = i + 1
if current_state == STATE.DECIMAL:
return False;
return True
def test(s, expected):
is_valid = is_number_valid(s)
print(s, is_valid)
assert is_valid == expected
def main():
test("4.325", True)
test("4.325a", False)
test("x4.325", False)
test("4.32.5", False)
test("4325", True)
test("1.", False)
test("1.1.", False)
test("1.1.1", False)
test("1.1.1.", False)
test("+1.1.", False)
test("+1.1", True)
test("-1.1.", False)
test("-1.1", True)
test("", True)
main()