python字符串循环中输出错误

syl*_*let 4 python string

我在python(2.7)上有一个赋值,让我得到一个字符串的输出.在第4个问题中,要求提供早先出现的字母表.这个测试只是句子每个单词的第一个字符.示例:"这是一个句子",结果应为"a",因为它是字母表的第一个字母.

这是我的代码(包括以前的作业问题)

def GetNumWords ( Sentence ):
    Count = 0
    Length = len( Sentence )
    Index = 0
    while Index < Length:
        Char = Sentence [ Index ]
        if Char != ' ':
            Count += 1
            while Char != ' ' and Index < Length:
                Char = Sentence [ Index ]
                Index += 1
        else:
            Index += 1
    return Count

def GetWordNum ( Sentence, WordNum ):
    Count = 0
    Length = len( Sentence )
    Index = 0
    Word = ''   
    while Index < Length:
        Char = Sentence [ Index ]
        if Char != ' ':
            Count += 1
            while Char != ' ' and Index < Length:
                Char = Sentence [ Index ]
                Index += 1
                if Count == WordNum:
                    Word = Word + Char
        else:
            Index += 1
    if Word == '':
        return ''
    else:
        return Word

def GetFirstLetter ( Sentence, SpecificNum):
    TheWord = GetWordNum ( Sentence, SpecificNum )
    if TheWord == '':
        return ''
    else:
        FirstLetter = TheWord [ 0 ]
        return FirstLetter

def GetEarliestLetter ( Sentence ):
    CurrentMinNum = 1
    CurrentMin = GetFirstLetter ( Sentence, CurrentMinNum )
    LastWord = GetNumWords ( Sentence )
    if CurrentMin == '':
        return ''
    else:
        while CurrentMinNum <=  LastWord:
            FirstLetter = CurrentMin
            if FirstLetter < CurrentMin:
                CurrentMin = FirstLetter
                CurrentMinNum += 1
            else:
                break
        return CurrentMin
Run Code Online (Sandbox Code Playgroud)

这样做会给我第一个单词的第一个字母,而不是字母顺序中最早的字母.

我哪里做错了?过去两天我看过这个,我看不出我做错了什么.

foz*_*foz 6

我想你可能会让它过于复杂.

>>> s = "this is a sentence"
>>> min(c for c in s if c.isalpha())
'a'
Run Code Online (Sandbox Code Playgroud)

  • 没有外部库,min和isalpha是在函数/方法中构建的 (3认同)
  • @sylvainpissardmaillet:如果该程序只应测试每个单词的第一个字符,你需要***在你的问题中明确说明_. (3认同)