Advertisement
acclivity

pyLongestAscendingSubstring

Feb 16th, 2021 (edited)
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.46 KB | None | 0 0
  1. # A function to find the longest substring of ascending value characters
  2.  
  3.  
  4. def longest_ascending_substring(s1):
  5.     last_char = chr(255)            # Initialise last_char to the highest ASCII value (simplifies later process)
  6.     s1 += chr(0)                    # Append the lowest ASCII value to our input string (simplifies processing)
  7.     substring = ""                  # Initialise an empty variable for substring
  8.     longest_substring = ""          # Initialise a variable that will hold the longest substring encountered
  9.  
  10.     for ch in s1:                   # Examine one character at a time from the input string
  11.         if ch < last_char:                          # end of an ascending sequence
  12.             # An ascending sequence has ended. Was it the longest such sequence found so far?
  13.             if len(substring) > len(longest_substring):
  14.                 longest_substring = substring       # remember the longest substring so far
  15.             substring = ""          # start a new empty substring
  16.         substring += ch             # add current character to current sub-string
  17.         last_char = ch              # remember the last character for sequence checking
  18.     return(longest_substring)
  19.  
  20.  
  21. tests = ["abcbad", "abcbcde", "gkcmqqfebrtvxp", "jollyhockeystick"]
  22. for test in tests:
  23.     print(test, " >> ", longest_ascending_substring(test))
  24.  
  25. # Results:-
  26. #
  27. # abcbad  >>  abc
  28. # abcbcde  >>  bcde
  29. # gkcmqqfebrtvxp  >>  brtvx
  30. # jollyhockeystick  >>  lly
  31.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement