Valid Number-Python 3 Solution


  • 0

    [Python 3 Solution: built-in try-except]

    Type of given 's' is a string.
    To convert 's' to number, not string, we use int() or float().

    For example,
    (1) If s is '5' (type: string), we can try: s=int(s) ==> s is 5 (type: int).
    (2) If s is '0.5'(type: string), we can try: s=float(s) ==> s is 0.5(type: float).
    (3) If s is '5'(type:string), we can also try: s=float(s)==> s is 5.0 (type: float)

    but, if s is 'abc' or 'smdkfsd10', s is not a number. Therefore, int() or float() would not work.

    We can apply these principles to solve this problem.

    class Solution:
       def isNumber(self, s):
           self.s=s
           try:
               float(s)
               return True
           except:
               return False
    

  • 0
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.