-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathValid_Number.py
67 lines (56 loc) · 2.45 KB
/
Valid_Number.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
class Solution:
def isNumber(self, s: str) -> bool:
# Define state transitions for the finite state machine
transitions = {
'Start': {'digit': 'Integer', 'sign': 'Sign', 'dot': 'Dot'},
'Sign': {'digit': 'Integer', 'dot': 'Dot'},
'Integer': {'digit': 'Integer', 'dot': 'Fraction', 'e': 'Exponent'},
'Dot': {'digit': 'Fraction'},
'Fraction': {'digit': 'Fraction', 'e': 'Exponent'},
'Exponent': {'digit': 'Exp_number', 'sign': 'Exp_sign'},
'Exp_sign': {'digit': 'Exp_number'},
'Exp_number': {'digit': 'Exp_number'}
}
# Define valid ending states for a valid number
valid_end_states = {'Integer', 'Fraction', 'Exp_number'}
# Function to determine the type of character
def get_char_type(char):
if char.isdigit():
return 'digit'
if char in '+-':
return 'sign'
if char in 'eE':
return 'e'
if char == '.':
return 'dot'
return None # Invalid character
# Start in the 'Start' state
current_state = 'Start'
# Process each character in the input string
for char in s:
char_type = get_char_type(char) # Get the character type
# If the character type is invalid or not allowed from the current state
if not char_type or char_type not in transitions[current_state]:
return False
# Move to the next state based on the current state and character type
current_state = transitions[current_state][char_type]
# Check if the final state is one of the valid end states
return current_state in valid_end_states
# Test cases
solution = Solution()
# Example 1
print(solution.isNumber("0")) # Output: True
# Example 2
print(solution.isNumber("e")) # Output: False
# Example 3
print(solution.isNumber(".")) # Output: False
# Additional test cases
print(solution.isNumber("3.14")) # Output: True
print(solution.isNumber("-42")) # Output: True
print(solution.isNumber("1e10")) # Output: True
print(solution.isNumber("1E-10")) # Output: True
print(solution.isNumber("+.8")) # Output: True
print(solution.isNumber("-.5e2")) # Output: True
print(solution.isNumber("+-5")) # Output: False
print(solution.isNumber("12e")) # Output: False
print(solution.isNumber("1.2.3")) # Output: False