Home > OS >  Why is my recursion function skipping a letter?
Why is my recursion function skipping a letter?

Time:09-13

Based on the prompt, my input should read "beggh", but my code is for some reason skipping the H. I've tried everything I can think of.

Prompt: Assume s is a string of lower case characters.

Write a program that prints the longest substring of s in which the letters occur in alphabetical order. Please use s = 'azcbobobegghakl' to test your codes. Your program should print

Longest substring in alphabetical order is: beggh In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print

Longest substring in alphabetical order is: abc

s = "azcbobobegghakl"
current_string = ''
longest_string = ''
n = 0
​
​
def sorting_string(n):
    global current_string
    global longest_string
    if n == (len(s) - 1):  
        return 0
    elif ord(s[n]) <= ord(s[n 1]):
        
        
        if len(current_string) <= 1:
            current_string = current_string   s[n]
            return sorting_string(n   1)
        
        if ord(s[n 1]) > ord(current_string[-1]):
                current_string = current_string   s[n]
        
        else:
            if ord(s[n]) >= ord(current_string[-1]):
                current_string = current_string   s[n]
            
        
            
        if len(current_string) > len(longest_string):
            longest_string = current_string
            
        else:
            current_string = ''
            
        return sorting_string(n   1)
​
        
    else:
        current_string = ''
​
        return sorting_string(n   1)
        
​
print(s)
sorting_string(n)
print(longest_string)
print(current_string)
print(ord("g"))
print(ord("h"))

output

azcbobobegghakl
begg
ak
103
104

CodePudding user response:

Because as soon as your index n reaches the letter h, elif ord(s[n]) <= ord(s[n 1]): returns False and neither current_string = current_string s[n] nor longest_string = current_string is executed.

CodePudding user response:

there are a lot of operations going on in your code, of which, many are not required.

I tried to simplify the problem and here I'm with my final code:

string = "azcbobobegghakl"
longest_str = string[0]
current_str = string[0]
for i in string[1:]:
    if i >= current_str[-1]:
        current_str  = i
        if len(current_str) > len(longest_str):
            longest_str = current_str
    else:
        current_str = i
print (longest_str)
  • You don't need to compare ord values when you can directly compare alphabets.
  • Related