I am trying to make this recursive function work, but the only output I am getting is:
azcbobobegghakl
a
Here is the prompt:
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"
Here is my code:
s = "azcbobobegghakl"
current_string = s[0]
longest_string = s[0]
n = 0
def sorting_string(n):
if n == len(s):
return 0
if ord(s[n]) <= ord(s[n 1]):
current_string = current_string s[n]
return (n * sorting_string(n 1))
if len(current_string) > len(longest_string):
longest_string = current_string
else:
return (n * sorting_string(n 1))
else:
current_string.clear()
return sorting_string(n 1)
print(s)
print(longest_string)
CodePudding user response:
You never called your function. Add in
sorting_string(s)
before the print
CodePudding user response:
You're getting that output because you aren't calling the function you created. All you're doing is calling your last two print statements, which will always be azcbobobegghakl
and a
since you aren't actually changing their values.