【问题标题】:can anyone explain the python following code(i'm complete rookie)任何人都可以解释以下代码的python(我是完整的菜鸟)
【发布时间】:2017-12-28 02:19:38
【问题描述】:

编写一个程序,打印 s 中字母按字母顺序出现的最长子串。例如,如果s = 'azcbobobegghakl',那么你的程序应该按字母顺序打印最长的子串是:beggh。

在平局的情况下,打印第一个子字符串。例如,如果 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)

【问题讨论】:

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


    【解决方案1】:

    这闻起来像家庭作业,但是... 下面是cmets的解释:

    # 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)
    

    【讨论】:

    • 这确实是家庭作业,但我的挫败感让我来到了这里。非常感谢您的回答,您能否解释一下比较 y 和 x 将 y 分配给 x 的目的是什么?
    • "你的程序应该打印最长的子串"所以你建立一个子串,当你建立它时,每次它改变时你都会比较最后一个。当它更长时,你保存它。当它相等或更短时,您只需继续构建按字母顺序排列的子字符串。
    【解决方案2】:

    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'

    您的代码

    您一次遍历字符串一个字符(从第二个字符开始),并检查当前字符的 ASCII 值是否大于(或等于)前一个字符。如果是,则将该字符添加到y 字符串中,并将生成的字符串存储为y。如果不是,则将 y 替换为当前字符。最后,如果y 的字符多于x,则将x 中的字符串替换为y

    【讨论】:

    • 这正是我想要的。非常感谢您的努力。上帝保佑你。
    • 不客气。如果你愿意,你可以接受这个答案。
    猜你喜欢
    • 2011-02-28
    • 2015-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多