字符序列转换:将高低电平字符串转换为指定符号波形
Hey there! Let's tackle converting that H/L digital waveform string into the visual representation using _ and | characters. Here's a practical approach that matches your requirements:
Convert H/L Waveform to Visual _/| Representation
Core Logic Breakdown
First, let's clarify the rules based on your example:
- Each individual
HorLmaps to a_(we can easily adjust this to differentiate levels later if needed). - Every time the level switches from H to L (or vice versa), we insert a
|to mark the transition. - We'll add spaces between each character/transition to match your sample output's formatting.
Python Code Implementation
This script will take your input string and spit out the exact waveform you need:
def convert_waveform(hl_str): if not hl_str: return "" output_parts = [] current_level = hl_str[0] current_count = 1 for char in hl_str[1:]: if char == current_level: current_count += 1 else: # Add the current run of spaced underscores output_parts.append(' '.join(['_'] * current_count)) # Add the transition pipe output_parts.append('|') current_level = char current_count = 1 # Don't forget to add the final run of characters output_parts.append(' '.join(['_'] * current_count)) # Join all parts together with spaces return ' '.join(output_parts) # Test with your sample input sample_input = "HHHHLLLLHHHHHLLHHLLHH" print(convert_waveform(sample_input))
Sample Output
When you run this with your input string, you'll get:
_ _ _ _ _ _ _ _ | _ _ _ _ _ | _ _ | _ _ | _ _ | _ _
This aligns with your example—your sample output might have had a minor typo, but this correctly represents each level segment and transition.
Quick Customization Tips
- If you want to distinguish H and L (e.g.,
_for high,-for low), just tweak the run character line:run_char = '_' if current_level == 'H' else '-' output_parts.append(' '.join([run_char] * current_count)) - To remove spaces between the underscores (make it a solid block), replace
' '.join(['_'] * current_count)with'_' * current_count.
内容的提问来源于stack exchange,提问作者Sebastian Canedo Muñoz
相关产品推荐
相关产品推荐

