Python中的字母顺序

2024-09-30 05:28:22 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我有关于以下代码的问题:

s = "wxyabcd"

myString = s[0]
longest = s[0]
for i in range(1, len(s)):
    if s[i] >= myString[-1]:
        myString += s[i]
        if len(myString) > len(longest):
            longest = myString
    else:
        myString = s[i]
print longest

回答:“abcd” w wx公司 wxy公司 一 ab型 abc公司 abcd

我是Python新手,我正试图了解其中一些循环是如何工作的,但我很困惑。这找到了字母顺序中最长的字符串。。。实际的答案是“abcd”,但我知道它经历的过程是一个接一个的。在

问题:有人能帮我看完代码吗?这样我就能更好地理解它了吗?因为有7个字符,我假设它的开头是:“对于1-7范围内的每一个项目,如果这个项目是'more'而不是myString[-1],也就是'w',那么我加上字母加上I中的项目,在这个例子中它是'x'。在

在这之后我就迷路了。。。那么从a-z:a>;z?是这样吗?那么当s[i]!=myString[-1]是否跳过从s[i]中的“a”开始。在

对不起,我到处都是。不管怎样,我试着在网上搜索一些地方来帮助我学习这些,但是有些事情很难做到。我知道几个月后我就会掌握窍门,希望能说得更流利。在

谢谢你!在


Tags: 项目代码inforlenlongestif字母
3条回答
# s is a 7 character string
s = "wxyabcd"

# set `mystring` to be the first character of s, 'w'
myString = s[0]

# set `longest` to be the first character of s, 'w'
longest = s[0]

# loop from 1 up to and not including length of s (7)
# Which equals for i in (1,2,3,4,5,6):
for i in range(1, len(s)):

    # Compare the character at i with the last character of `mystring`
    if s[i] >= myString[-1]:

        # If it is greater (in alphabetical sense)
        # append the character at i to `mystring`
        myString += s[i]

        # If this makes `mystring` longer than the previous `longest`,
        # set `mystring` to be the new `longest`
        if len(myString) > len(longest):
            longest = myString

    # Otherwise set `mystring` to be a single character string
    # and start checking from index i
    else:
        myString = s[i]

# `longest` will be the longest `mystring` that was formed,
# using only characters in descending alphabetic order
print longest

下面是对控制流的一点解释,以及Python索引的原理,希望能有所帮助:

s = "wxyabcd"

myString = s[0] # 'w'
longest = s[0] # 'w' again, for collecting other chars
for i in range(1, len(s)): # from 1 to 7, exclusive of 7, so 2nd index to last
    if s[i] >= myString[-1]: # compare the chars, e.g. z > a, so x and y => True
        myString += s[i] # concatenate on to 'w'
        if len(myString) > len(longest): # evident?
            longest = myString # reassign longest to myString
    else:
        myString = s[i] # reassign myString to where you are in s.
print longest

我能想到的两种方法(快速)

def approach_one(text): # I approve of this method!
    all_substrings = list()
    this_substring = ""
    for letter in text:
        if len(this_substring) == 0 or letter > this_substring[-1]:
            this_substring+=letter
        else:
            all_substrings.append(this_substring)
            this_substring = letter
    all_substrings.append(this_substring)
    return max(all_substrings,key=len)

def approach_two(text):
    #forthcoming

相关问题 更多 >

    热门问题