Python子字符串计数代码说明

时间:2015-01-19 15:54:18

标签: python

我正在寻找一个计算字符串中最长字母子字符串的程序。例如STR =' abcdkjcd'会产生' abcd'作为最长的子串。

使用这个网站和一些教程和功能解释,我找到了一个很好的答案,但是我真的想真正理解代码。 我有限的理解是,如果变量高于当前正在查看的变量,它会将每个角色与变量连接起来。

我注释了我的代码,并希望有人可以向我解释3行???

s='abc' # Sets a string value

def longeststr(str): # Defines the function to work out the longest substring
    longest=''  # Sets up a variable to store the longest value in with an empty string

    for i in range(len(str)): # Sets up the outside for loop to repeat the instructions below for the same amount of times as elements are in the string

        for j in range(i+1, len (str)): #For each element in the string started from the second element to the end, do the following...

            s=str[i:j+1] # Not sure??

            if ''.join(sorted(s)) == s: # If when try to join a sorted list of s is equal to s? Doesn't make sense??

                longest = max(longest, s, key = len)  # Not sure

            else:
                break # Exits the loop

    return 'Longest substring in alphabetical order is:' + longest # Returns value of longest string

感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

s = str [i:j + 1]是一个非常pythony的东西,称为切片。基本上它是从I到j + 1的子串。

if''。join(sorted(s))== s。如果您按字母顺序排序后当前查看的字符串相同,则按顺序

最长=最大(最长,s,键= len)。最长的是由Len变量确定的s或其自身的最大值

答案 1 :(得分:0)

示例中的变量i指向源字符串中的位置。

第二个循环,创建变量j,指向i指向的位置旁边的位置。

s=str[i:j+1] - 从源位置i提取子字符串到位置j

''.join(sorted(s))按字母顺序排序子字符串。如果sorted子串等于substring,则表示substring已经是字母子串。

以下只选择更大的值:存储在longest变量中的值或当前子串的len。

longest = max(longest, s, key = len)

答案 2 :(得分:0)

s='abc' # Sets a string value

def longeststr(str): # Defines the function to work out the longest substring, which accepts str as arg
    longest=''  # Sets up a variable to store the longest value in with an empty string

    for i in range(len(str)): # Sets up the first loop for i iterations from 0 to the lenght of the str (for i = 0;i<len(str);i++)
        for j in range(i+1, len (str)): #For each element next to the i-element 
            s=str[i:j+1] # slice string. eg str = 'abcd', i = 1, j=2, str[i:j+1] = 'bc'. for more information google 'python slice' So in this slice we start from fisrt and second literals, then from first and third, then ...., then from second and third and so on and on  

            if ''.join(sorted(s)) == s: # it is a little bit tricky. 

如果s =&#39; bca&#39;然后排序将给我们&#39; abc&#39;并且s不等于排序。但如果s =&#39; ABC&#39;然后排序(s)和s是等于我们正在寻找的

                longest = max(longest, s, key = len)  # according to docs: returns the largest item in an iterable or the largest of two or more arguments. if key (possible options for list.sort() function) is specified, it is used like a criteria for max function. 

            else:
                break # Exits the loop

    return 'Longest substring in alphabetical order is:' + longest # Returns value of longest string