reverse alternating group of letters
Tue Dec 31 2024 05:05:03 GMT+0000 (Coordinated Universal Time)
Saved by
@sooraz3871
#python
def reverse_alternating_groups(s):
result = [] # List to store the final result
group = "" # Temporary string to hold each group (either digits or letters)
reverse = False # Flag to indicate whether to reverse the group
for i in range(len(s)):
if s[i].isalpha():
# Add character to the current group of letters
group += s[i]
else:
# If we encounter a non-letter (digit), process the current group
if group:
# Reverse the group if needed and append it to the result
if reverse:
result.append(group[::-1]) # Reverse the letters group
else:
result.append(group) # Leave the letters group as it is
group = "" # Reset the group for the next set of characters
# Append the digit to the result (digits are unchanged)
result.append(s[i])
# Toggle the reverse flag for the next group of letters
reverse = not reverse
# Process any remaining group (in case the string ends with letters)
if group:
if reverse:
result.append(group[::-1]) # Reverse the last letters group if needed
else:
result.append(group)
# Return the result as a joined string
return ''.join(result)
# Example usage:
input_str_1 = "abc123def456ghi789jkl"
output_str_1 = reverse_alternating_groups(input_str_1)
print(output_str_1) # Output: "cba123def456ihg789jkl"
input_str_2 = "a1b2c3d"
output_str_2 = reverse_alternating_groups(input_str_2)
print(output_str_2) # Output: "a1b2c3d"
content_copyCOPY
Comments