2

I am suppose to take in an input and return true or false depending on whether the input is a valid number. Here are some examples:

"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
" -90e3   " => true
" 1e" => false
"e3" => false
" 6e-1" => true
" 99e2.5 " => false
"53.5e93" => true
" --6 " => false
"-+3" => false
"95a54e53" => false

I have a list of all of the valid characters and I decided to use slicing notation to see which character in the 0th index of the input matches any of the valid ones. However, the code is misreading the input 9 as false. This is my full code at the moment. I haven't yet checked for all conditions:

class Solution:
    def isNumber(self, s: str) -> bool:
        valid_char = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '+', 'e', '.']
        str_lst = list(s)

        if str_lst[0] in valid_char[0:10]:
            return True
        else:
            return False
1

2 Answers 2

3

The best way to go for this in my opinion is using a try/except clause to try to cast the strings to float:

"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
" -90e3   " => true
" 1e" => false
"e3" => false
" 6e-1" => true
" 99e2.5 " => false
"53.5e93" => true
" --6 " => false
"-+3" => false
"95a54e53" => false

Let's generate a list with the strings above:

l = ["0", " 0.1 ", "abc", "1 a", "2e10", " -90e3   ", " 1e", "e3", 
     " 6e-1", " 99e2.5 ", "53.5e93", " --6 ", "-+3", "95a54e53"]

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

list(map(is_number, l))
# [True, True, False, False, True, True, False, False, True, False, 
#  True, False, False, False]
Sign up to request clarification or add additional context in comments.

1 Comment

This is pretty smart. You're basically using the Python's error mechanism as a part of your code without having to build an entire algorithm to see if each char is valid. I've upvoted and accepted your answer. If you think that this was a well asked question, could you give me an upvote as well?
3

Well first off there is no need to convert s to str(s) if you're not planing to change s, which you're probably not going to. Slicing works pretty much the same on strings as it does on lists. If you really want to check if s is a valid python number you can use

inp = input('input character: ')
def is_valid_num(s):
    try: 
        float(inp)
        return True
    except ValueError:
        return False

2 Comments

I've already accepted yatu's answer but I'll give you an upvote for the correct approach. If you think that this was a well asked question, could you give me an upvote as well?
Thanks :) Yeah it's a kind of well known approach to this situation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.