Python中的字母顺序

时间:2014-03-04 00:22:10

标签: python loops if-statement for-loop

好的,我对以下代码有疑问:

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中的每个项目,如果项目比myString [-1]''更多'是'w',那么我在i中添加字母加上项目在这种情况下,它将是'x'。

我在这之后就迷路了...所以从a - z:a> Z'那是怎么回事?那么当s [i]!= myString [-1]时它是如何跳过从s [i]中的'a'开始的。

对不起,我到处都是。无论如何,我试图在网上搜索地方,以帮助我学习这一点,但有些事情很难。我知道,在几个月内病了,我希望能更流利。

谢谢!

3 个答案:

答案 0 :(得分:1)

这里有一些关于控制流程的解释以及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

答案 1 :(得分:1)

# 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

答案 2 :(得分:0)

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

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