我正在尝试构建某种“动态子字符串”,它是由给定string中的循环构建的。规则是我需要按字母顺序找到最长的substring,如果我有一个潮流,我需要计算这两个值,并打印具有较大值的那个。
我读到在python中,字符已经被赋予了一个数值,因此a比b更小;知道这一点,我写了以下内容:
s = "abcsaabcpaosdjaf"
ans = []
# Loop over the string
for i in range(len(s)-1):
if s[i] < s[i+1]:
#evaluate if it is in order and build the new string
ans = s[i]+s[i+1]
#print the result
print(ans)我的问题是,我不知道如何动态地-我不确定这是否是正确的方式-生成子字符串ans,现在我有了s[i]+s[i+1],但它只给了我一个包含两个字符的列表,实际上是按字母顺序排列的,并且固定为两个。我怎么做才能让它按原样构建呢?
发布于 2017-10-15 12:50:51
尝尝这个。希望评论能解释得够多,但如果你不明白,请不要问。
s= "abcsaabcpaosdjaf"
best_answer = ''
current_answer = s[0]
# Loop over the string
for i in s[1:]:
# look to see if this letter is after the
# last letter in the current answer.
if ord(i) > ord(current_answer[-1]):
# if it is, add the letter to the current
# answer
current_answer += i
else:
# if it is not, we check if the current
# answer is longer than the best
# answer, and update it to the best
# answer if it is.
if len(current_answer) > len(best_answer):
best_answer = current_answer
# We then set the current answer
# to just the last letter read.
current_answer = i发布于 2017-10-16 13:41:19
import itertools
s= "abcsaabcpaosdjaf"
result = max(
(
list(next(sub)) + [b for a, b in sub]
for ascending, sub in itertools.groupby(zip(s,s[1:]), lambda x: x[0] <= x[1])
if ascending
),
key=len
)
print (''.join(result))致谢给this
https://stackoverflow.com/questions/46751527
复制相似问题