我试图构建某种"动态子字符串"这是在给定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
,现在我有{{ 1}}但是这只给了我一个实际上按字母顺序排列的两个字符的列表,它只固定为两个。我怎么能以它构建它的方式来做它?
答案 0 :(得分:0)
试试这个。希望能够充分解释这些评论,但如果您不理解,请随便提出。
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
答案 1 :(得分:0)
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
的信用