EDIT . I know that a question with a similar problem has already been asked in SO, but I am interested to find out the problem in this particular piece of code. I also know that this problem can be solved without using recursion.
The challenge is to write a program that finds (and prints) the longest substring in which letters appear in alphabetical order. If more than 1 equally long sequences were found, then you need to print the first. For example, the output for the string abczabcd would be abcz .
I solved this problem with recursion, which seemed to pass my manual tests. However, when I run a set of automatic tests that generate random strings, I noticed that in some cases the output is incorrect. For example:
if s = 'hixwluvyhzzzdgd' , output hix instead of luvy
if s = 'eseoojlsuai' , exit eoo instead of jlsu
if s = 'drurotsxjehlwfwgygygxz' , exit dru instead of ehlw
After some time, I could not understand what is especially important in these lines, which cause an error.
This is my code:
pos = 0 maxLen = 0 startPos = 0 endPos = 0 def last_pos(pos): if pos < (len(s) - 1): if s[pos + 1] >= s[pos]: pos += 1 if pos == len(s)-1: return len(s) else: return last_pos(pos) return pos for i in range(len(s)): if last_pos(i+1) != None: diff = last_pos(i) - i if diff - 1 > maxLen: maxLen = diff startPos = i endPos = startPos + diff print s[startPos:endPos+1]
python recursion
Eugene s
source share