Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # A function to find the longest substring of ascending value characters
- def longest_ascending_substring(s1):
- last_char = chr(255) # Initialise last_char to the highest ASCII value (simplifies later process)
- s1 += chr(0) # Append the lowest ASCII value to our input string (simplifies processing)
- substring = "" # Initialise an empty variable for substring
- longest_substring = "" # Initialise a variable that will hold the longest substring encountered
- for ch in s1: # Examine one character at a time from the input string
- if ch < last_char: # end of an ascending sequence
- # An ascending sequence has ended. Was it the longest such sequence found so far?
- if len(substring) > len(longest_substring):
- longest_substring = substring # remember the longest substring so far
- substring = "" # start a new empty substring
- substring += ch # add current character to current sub-string
- last_char = ch # remember the last character for sequence checking
- return(longest_substring)
- tests = ["abcbad", "abcbcde", "gkcmqqfebrtvxp", "jollyhockeystick"]
- for test in tests:
- print(test, " >> ", longest_ascending_substring(test))
- # Results:-
- #
- # abcbad >> abc
- # abcbcde >> bcde
- # gkcmqqfebrtvxp >> brtvx
- # jollyhockeystick >> lly
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement