【面試題20】表示數值的字符串

Python題解
在這裏插入圖片描述

class Solution:
    # s字符串
    def isNumeric(self, s):
        if not s:return False
        def scanUnsignedInteger(s, i):
            before = i
            while i != len(s) and '0' <= s[i] <= '9':
                i += 1
            return i>before, i
        def scanInteger(s, i):
            if i != len(s) and s[i] in ['+', '-']:
                i += 1
            return scanUnsignedInteger(s, i)

        i = 0
        #1.先檢查小數點前面是否有整數
        numeric, i = scanInteger(s, i)
        #2.如果有小數點,檢查小數點之後是否是一個無符號數
        if i != len(s) and s[i] == ".":
            i += 1
            tmp, i = scanUnsignedInteger(s, i)
            #這裏的or表示容忍三種情況:有整數沒有小數、有整數有小數和沒有整數有小數。
            numeric = numeric or tmp
        #3.如果有指數部分,判斷指數後面是否爲整數
        if i != len(s) and s[i] in ['E', 'e']:
            i += 1
            tmp, i = scanInteger(s, i)
            #這裏的and意思是e前面必須有整數,有e後面必須要有整數
            numeric = numeric and tmp
        return numeric and i == len(s)

考點

  • 考查對字符串的編程能力;
  • 考查分析問題的能力,能夠從不同類型數值中分析出規律;
  • 考查思維的全面性。要全面考慮數值整數、小數、指數部分的特點,比如哪些部分可以出現正負號,而哪些部分不能出現,寫完代碼之後應能夠完備的測試用例來驗證自己的代碼。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章