• 牛客网-python-表示数值的字符串


    题目描述

    请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。

    自己实现

    class Solution:
        # s字符串
        def isNumeric(self, s):
            # write code here
            AllList = ['-','+','e','E','.','0','1','2','3','4','5','6','7','8','9']
            flag = 0
            for i in range(0,len(s)):
                if s[i] in AllList:
                    if (s[i]=='+' or s[i]=='-') and (i==0 or s[i-1]=='E' or s[i-1]=='e'):
                        continue
                    elif s[i]=='E' or s[i]=='e' and i!=0 and s[i-1] in AllList[6:] and i!=len(s)-1:
                        flag = 1
                        continue
                    elif s[i]=='.' and flag == 0 and i!=len(s)-1 and s[i+1] in AllList[5:]:
                        flag = 1
                        continue
                    elif s[i] in AllList[5:]:
                        continue
                    else:
                        return False
                else:
                    return False
            return True

    讨论区代码:

    #利用python中的正则模块进行匹配

    # -*- coding:utf-8 -*-
    class Solution:
        # s字符串
        def isNumeric(self, s):
            import re
            p=re.compile(r'^[+-]?d*(.d+)?([eE][+-]?d+)?$')
            return p.match(s)
    

      

  • 相关阅读:
    poj2886 Who Gets the Most Candies?
    poj1201 Intervals
    poj3109 Inner Vertices
    poj1990 MooFest
    poj3368 Frequent values
    NOIP练习赛题目6
    NOIP练习赛题目5
    NOIP练习赛题目4
    NOIP练习赛题目3
    NOIP练习赛题目2
  • 原文地址:https://www.cnblogs.com/ditingz/p/12257463.html
Copyright © 2020-2023  润新知