Python-Indexing-我不明白这段代码是如何工作的

时间:2016-09-15 22:25:03

标签: python python-3.x

我不明白的是如何索引字符串s =" azcbobobegghakl"会正确地给我答案' beggh'如果我按字母顺序寻找最长的子串。这段代码如何告诉计算机' beggh'按字母顺序排列?我认为索引只是给字符串中的每个字母增加了一个数字,直到字符串结束?我调整了一些代码并且它有效,但我实际上并不了解代码的工作原理。

s = "azcbobobegghakl"
longest = s[0]
current = s[0]
for c in s[1:]:
    if c >= current[-1]:
        current += c
    else:
        if len(current) > len(longest):
            longest = current
        current = c
print "Longest substring in alphabetical order is:", longest

3 个答案:

答案 0 :(得分:1)

>=按字典顺序比较两个字符;表达

if c >= current[-1]:

测试c(单个字符),是相同还是更大'比current[-1](另一个单个字符。字符串按字典顺序按其代码点值排序; a小于b,因为字符a位于b之前Unicode标准:

>>> 'a' > 'b'
False
>>> 'a' < 'b'
True

因此,如果字符后来出现,则字符仅会添加到current。字母表中的字符比current的最后一个字符。如果他们不这样做,则测试到目前为止的序列的长度,并从c开始 new 子串。

答案 1 :(得分:1)

表达式c >= current[-1]按字典顺序将每个字符与字符串中的前一个字符进行比较。更简单:

>>> 'a' >= 'a'
True
>>> 'b' >= 'a'
True
>>> 'b' >= 'c'
False
>>> 'z' >= 'a'
True

因此,所有代码所做的就是累积每个字符>=最后一个字符的运行,并保持最长的字符。

答案 2 :(得分:1)

s = "azcbobobegghakl"

# initialize vars to first letter in string
longest = s[0]
current = s[0]

# start iterating through rest of string
for c in s[1:]:

    # c is the letter of current iteration and current[-1]
    # is the last letter of the current string. Every character 
    # has an ASCII value so this is checking the character's 
    # numerical values to see if they are in alphabetical order (a<b<c etc.)
    if c >= current[-1]:

        # so if c is bigger than current[-1] (meaning it comes
        # after in the alphabet, then we want to add it to current
        current += c
    else:
        # if c was smaller then we want to check if the alphabetic
        # string we just read is longer than the previous longest
        if len(current) > len(longest):
            longest = current

        # start the current string over beginning with the letter in c
        current = c
print "Longest substring in alphabetical order is:", longest