Python | Merge adjacent Digit characters

Python | Merge adjacent Digit characters

In this tutorial, we will merge adjacent digit characters in a string. This means that if two or more digit characters are adjacent in a string, they should be merged to form a single number.

Problem Statement:

Given a string containing a mix of characters, merge adjacent digit characters to form a single number.

Example:

Input:

s = "a12bc34d5ef" 

Output:

"a12bc34d5ef" 

Step-by-Step Solution:

  1. Iterate over the String: Loop through each character in the string.
  2. Check if the Character is a Digit: If it's a digit and the previous character was also a digit, append it to the current number string. Otherwise, append the current number string to the result and start a new number string.
  3. Construct the Result String: Construct the result string using the characters and merged numbers.

Here's the implementation:

def merge_adjacent_digits(s): if not s: return "" merged = [] number_str = "" for char in s: if char.isdigit(): number_str += char else: if number_str: merged.append(number_str) number_str = "" merged.append(char) # Append any remaining number string to the result if number_str: merged.append(number_str) return ''.join(merged) # Test s = "a12bc34d5ef" print(merge_adjacent_digits(s)) # Expected Output: "a12bc34d5ef" 

Explanation:

For the string s:

  • The digit characters 1 and 2 are adjacent, so they are merged to form 12.
  • The digit characters 3 and 4 are adjacent, so they are merged to form 34.
  • The other characters remain unchanged.

The merge_adjacent_digits function iterates through the string and identifies sequences of digit characters, merging them into a single number string. It then constructs the result string with these merged numbers and other characters. The time complexity of this solution is O(n), where n is the length of the string.


More Tags

bucket facet-wrap multiprocessing ntp git-bash appium-android implicit static angular-bootstrap module

More Programming Guides

Other Guides

More Programming Examples