我想写一个程序来计算字符串中最长的字母子字符串。 例如,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
感谢您的任何帮助。
s=str[i:j+1] 是一个非常pythony的东西,称为切片。基本上它是从 I 到 str 的 j+1 的子字符串。
如果 ''.join(sorted(s)) == s. 如果您当前查看的字符串在按字母顺序排序后相同,则按顺序排列
最长 = 最大值(最长,s,键 = len)。最长是 s 或自身由 Len 变量确定的最大值
示例中的变量i
指向源字符串中的位置。
第二个循环,创建变量j
,该变量指向i
所指向的位置旁边的位置。
s=str[i:j+1]
- 从源字符串中提取子字符串,从位置i
到位置j
''.join(sorted(s))
按字母顺序对子字符串进行排序。如果排序的子字符串等于子字符串,则意味着子字符串已经是按字母顺序排列的子字符串。
以下只是选择更大的值:存储在当前子字符串longest
变量或 len 中的值。
longest = max(longest, s, key = len)
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 = 'BCA',那么 sorted(s) 将给我们 'abc',而 s 将不等于 sorted(s)。但是如果 s = ' abc' 那么排序(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