Advertisement
CrayonCrayoff

Code Wars: Alphabet Slices

Jan 22nd, 2025 (edited)
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.88 KB | None | 0 0
  1. def solution(s: str) -> str:
  2.     # initialize a list to record the output. (A list because it'll be easier to manipulate later)
  3.     output = []
  4.  
  5.     idx = 0
  6.     while idx < len(s):
  7.         # initialize a temporary list to store the current sequence
  8.         temp = [s[idx]]
  9.         idx += 1
  10.         # keep advancing while we're in bounds and the current and previous characters are consecutive
  11.         while idx < len(s) and ord(s[idx]) - ord(s[idx-1]) == 1:
  12.             temp.append(s[idx])
  13.             idx += 1
  14.         # if the while loop ended and we didn't add any letters, just add the letter we were on
  15.         # Otherwise, extend the output with the reverse of the temporary list
  16.         if len(temp) > 1:
  17.             output.extend(temp[::-1])
  18.         else:
  19.             output.extend(temp)
  20.  
  21.     # we have to return a string, so join the output list
  22.     return "".join(output)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement