python - Longest string in alphabetic order -
python - Longest string in alphabetic order -
this code works fine strings, except ones lastly char needed.
s='abcdefghijklmnopqrstuvwxyz' sub ='' test =s[0] n in range(len(s)-1): if len(test) > len(sub): sub = test if s[n] >= s[n-1]: test += s[n] else: test = s[n] print 'longest substring in alphabetic order is: ' + str(sub)
how suggest possibility doing this?
thank in advance guys!
ps:
thanks answers far. problem that, no matter range type, sub variable, print, doesn't chars want. loop finishes before :\ maybe it's problem programme itself.
any tips? :)
your problem range(len(s)-1)
. range generates list upper limit parameter value-1 don't need subtract1 len(s), use:
range(len(s))
from https://docs.python.org/2/library/functions.html#range
range(stop) range(start, stop[, step]) versatile function create lists containing arithmetic progressions. used in loops. arguments must plain integers. if step argument omitted, defaults 1. if start argument omitted, defaults 0. total form returns list of plain integers [start, start + step, start + 2 * step, ...]. if step positive, lastly element largest start + * step less stop; if step negative, lastly element smallest start + * step greater stop. step must not zero
on other hand, labeling question python2.7 assume using 2.7. if case, more efficient utilize xrange
instead range
because way utilize iterator instead generating list.
edit
from comments question, can alter code to:
s='caabcdab' sub ='' test =s[0] in range(1,len(s)+1): n = i%len(s) if len(test) > len(sub): sub = test if >= len(s): break if s[n] >= s[n-1]: test += s[n] else: test = s[n] print 'logest substring in alphabetic order is: ' + str(sub)
python python-2.7
Comments
Post a Comment