任何人都可以解释python下面的代码(我是完整的菜鸟)

时间:2017-12-28 02:19:39

标签: python string python-3.x for-loop

编写一个程序,打印s中最长的子字符串,其中字母按字母顺序出现。例如,如果s = 'azcbobobegghakl',则您的程序应按字母顺序打印最长子字符串:beggh。

在tie的情况下,打印第一个子字符串。例如,如果s ='abcbc

s = "azcbobobegghakl"

x = s[0]

y = s[0]


for i in range (1, len(s)): 

    if s[i] >= s[i-1]:
        y += s[i]   

    else:
        y = s[i]  

    if len(y) > len(x):
        x = y               
print(x)

2 个答案:

答案 0 :(得分:3)

这闻起来像家庭作业,但...... 以下是评论解释:

# assign a string to a variable named s
s = "azcbobobegghakl"

# assign the zeroth character of the string s to x
x = s[0]

# assign the zeroth character of the string s to y    
y = s[0]


# loop through a range of numbers starting at 1 and going to the length of s
# within each loop, the variable i tells us which iteration of the loop
# we're currently in.    
for i in range(1, len(s)): 
    # compare the character in s at the position equal 
    # to the current iteration number to see if it's greater 
    # than or equal to the one before it. Alphabetic characters 
    # compared like this will evaluate as numbers corresponding 
    # to their position in the alphabet. 
    if s[i] >= s[i-1]:
        # when characters are in alphabetical order, add them to string y
        y += s[i]   
    else:
        # when the characters are not in alphabetical order, replace y with
        # the current character
        y = s[i]  
    # when the length of y is greater than of x, assign y to x
    if len(y) > len(x):
        x = y
# after finishing the loop, print x
print(x)

答案 1 :(得分:0)

python中的string类包含__lt____eq__数据模型方法,这使我们能够做到 -

str1 = 'aaa'
str2 = 'bbb'
str3 = 'aaa'

assert str2 < str1   # Will lead to AssertionError
                     # '<' calls the __lt__() method of the string class

assert str1 == str3  # No AssertionError
                     #'==' calls the __eq__() method of the string class

string类中的这些特定数据模型方法比较字符串中每个字符的ASCII值。英语字母表中每个字符的ASCII值顺序增加,即'A'< 'B'&lt; 'C'。

您的代码

一次循环字符串一个字符(从第二个字符开始),并检查当前字符是否具有比之前更大(或相等)的ASCII值。如果是,则将该字符添加到y字符串,并将结果字符串存储为y。如果不是,则y被当前字符替换。最后,如果y的字符数超过x,则将x内的字符串替换为y