【发布时间】:2018-09-12 13:03:33
【问题描述】:
我的使用python按字母顺序查找最长子字符串的代码
我所说的按字母顺序排列的最长子串是什么意思? 如果输入是“asdefvbrrfqrstuvwxffvd”,则输出将是“qrstuvwx”
#we well use the strings as arrays so don't be confused
s='abcbcd'
#give spaces which will be our deadlines
h=s+' (many spaces) '
#creat outputs
g=''
g2=''
#list of alphapets
abc='abcdefghijklmnopqrstuvwxyz'
#create the location of x"the character the we examine" and its limit
limit=len(s)
#start from 1 becouse we substract one in the rest of the code
x=1
while (x<limit):
#y is the curser that we will move the abc array on it
y=0
#putting our break condition first
if ((h[x]==' ') or (h[x-1]==' ')):
break
for y in range(0,26):
#for the second character x=1
if ((h[x]==abc[y]) and (h[x-1]==abc[y-1]) and (x==1)):
g=g+abc[y-1]+abc[y]
x+=1
#for the third to the last character x>1
if ((h[x]==abc[y]) and (h[x-1]==abc[y-1]) and (x!=1)):
g=g+abc[y]
x+=1
if (h[x]==' '):
break
print ("Longest substring in alphabetical order is:" +g )
它没有结束,好像它处于无限循环中 我该怎么办? 我是初学者,所以我想要一些 for 循环而不是库中的函数 提前致谢
【问题讨论】:
-
@natn2323 不,线路是
h=s+' (many spaces) ' -
@Jonas 对于这样的行,我发现最好按照以下方式做一些事情:
A_SPACE = ' ',然后是h = s + A_SPACE*74(或者你有多少空格)。编辑 - 抱歉刚刚意识到你不是提问者 -
是否有使用
h的要求,还是您想做的事情? -
@natn2323 不,我只是用它来有一个可以称之为“结束”的地方我仍然是初学者,但我发现使用空格比数字更容易打破它,因为 s 可能会有所不同作为输入。
标签: python python-3.x edx