有人能解释一下python下面的代码吗(我是一个完全的新手)
编写一个程序,打印字母按字母顺序排列的s的最长子字符串。例如,如果有人能解释一下python下面的代码吗(我是一个完全的新手),python,string,python-3.x,for-loop,Python,String,Python 3.x,For Loop,编写一个程序,打印字母按字母顺序排列的s的最长子字符串。例如,如果s='azcbobobeghakl',则程序应按字母顺序打印最长的子字符串:beggh 如果是领带,请打印第一个子字符串。例如,如果s='abcbc s=“azcbobebeghakl” x=s[0] y=s[0] 对于范围(1,len)中的i: 如果s[i]>=s[i-1]: y+=s[i] 其他: y=s[i] 如果len(y)>len(x): x=y 打印(x) 这闻起来像是家庭作业,但是。。。 以下是解释以下内容的评论:
s='azcbobobeghakl'
,则程序应按字母顺序打印最长的子字符串:beggh
如果是领带,请打印第一个子字符串。例如,如果s='abcbc
s=“azcbobebeghakl”
x=s[0]
y=s[0]
对于范围(1,len)中的i:
如果s[i]>=s[i-1]:
y+=s[i]
其他:
y=s[i]
如果len(y)>len(x):
x=y
打印(x)
这闻起来像是家庭作业,但是。。。
以下是解释以下内容的评论:
# 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)
python中的
string
类包含lt\uuuuuuuuu
,eq\uuuuuuuu
数据模型方法,这使我们能够-
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
str1='aaa'
str2=‘bbb’
str3=‘aaa’
断言str2 #这确实是家庭作业,但我的挫折让我来到了这里。我真的很感激你的回答,你能解释一下比较y和x的目的吗?将y指定给x?“你的程序应该打印最长的子字符串”,这样你就可以构建一个子字符串,并且在构建它的过程中,每次它发生变化时,你都会与最后一个进行比较。当它更长时,你保存它。当它相等或更短时,您只需继续构建字母顺序的子字符串。这正是我想要的。非常感谢,非常感谢你的努力。上帝保佑你,不客气。如果你愿意,你可以接受这个答案。