MachineLove MachineLove - 2 months ago 9
Python Question

Unexpected error while trying to find the longest string

I failed to write a program that prints the longest substring of a string in which the letters occur in alphabetical order for my very first Python test.

The comment read


"Your program does meet what the question asks but also contradicts with rule number 4 and hence your answer will not be accepted"


So here was my attempt of the code :

def obtain_longest_substring(string):
current_substring = longest_substring = string[0]
for letter in string[1:]:
if letter >= current_substring[-1]:
current_substring += letter
if len(current_substring) > len(longest_substring):
longest_substring = current_substring
else:
current_substring = letter
return longest_substring


def main():
s = input("Enter a string: ")
print("Longest substring in alphabetical order is: " + obtain_longest_substring(s))

if __name__ == "__main__":
main()


But the solution that was expected had some rules that I had to follow. Rule Number 4 said:


For problems such as these, do not include input statements or define variables which are already mentioned. Our automated testing will provide values for you.


I am new to Python. Can anyone tell me what I am doing wrong?

Answer

The rule clearly states not to include input statements or define variables (which you also did).

You could try re-writing it as :

current_substring = longest_substring = s[0]
for letter in s[1:]:
    if letter >= current_substring[-1]:
        current_substring += letter
        if len(current_substring) > len(longest_substring):
            longest_substring = current_substring
    else:
        current_substring = letter

print("Longest substring in alphabetical order is: " +   str(longest_substring))