Showing posts with label string processing. Show all posts
Showing posts with label string processing. Show all posts

Friday, September 13, 2024

Extracting Underscored Words Using Python Generators

Extract Words Enclosed in Underscores using Python Generators

Extract Words Enclosed in Underscores using Python

๐Ÿ“š Table of Contents

๐Ÿงฉ Problem Statement

You are given a list of strings. Some words are wrapped in underscores like _example_.

Your task is to extract only those words that start and end with underscores.

⚙️ Step-by-Step Approach

1. Combine Input Strings

We merge all strings into one large string using join() to simplify processing.

2. Split into Words

We split the combined string using spaces to get individual words.

3. Filter Words

Check if a word starts and ends with _.

4. Use Generator (yield)

Instead of returning all results at once, we use yield to produce results lazily.

๐Ÿ’ป Code Example

def get_underscored(strings):
    combined = " ".join(strings)
    for word in combined.split():
        if word.startswith("_") and word.endswith("_"):
            yield word

# Input data
strings = [
    "This is a _test_ string",
    "Another _example_ here",
    "No underscores here",
    "Check _this_ out"
]

# Collect results
result = list(get_underscored(strings))
print(result)

๐Ÿ–ฅ️ CLI Output

$ python script.py
['_test_', '_example_', '_this_']

๐Ÿง  Interactive Learning

⚡ Try It Yourself (Interactive)

Enter multiple sentences (one per line). Words wrapped with underscores will be extracted instantly.


Output:





What does yield do?

yield pauses function execution and returns a value one at a time.

This makes it memory efficient.

Why use generators?
  • Efficient for large datasets
  • Lazy evaluation
  • Better performance

๐Ÿ’ก Key Takeaways

  • Generators use yield instead of return
  • They produce values one at a time
  • Useful for memory-efficient processing
  • Great for streaming or large inputs

Sunday, September 8, 2024

Removing Consecutive Duplicates from a String

String Processing: Remove Spaces & Condense Characters

String Processing: Remove Spaces & Condense Characters

You have a string consisting of various characters, including letters and dots, separated by spaces. The goal is to process this string to:

  • Remove all spaces
  • Condense consecutive duplicate characters into a single instance
  • Output the condensed characters as a continuous string

Solution Overview

1. Remove Spaces

Start by creating a list of characters from the string while ignoring any spaces. This step effectively filters out all the spaces, leaving only the non-space characters.

2. Condense Duplicates

Traverse the filtered list and remove consecutive duplicate characters. Only the first occurrence of each sequence is retained.

3. Output the Result

After condensing, output the characters as a continuous string without separators.

Step-by-Step Breakdown

Step 1: Filter Out Spaces

From the original string, extract all characters that are not spaces. This gives a list containing only relevant characters.

Step 2: Remove Consecutive Duplicates

Create a new list starting with the first character. Compare each character with the previous one and keep it only if it differs.

Step 3: Print the Result

Iterate through the condensed list and print each character consecutively.

Example CLI Output


Input:
a a a . . . b b c c . .

Processing:
- Remove spaces
- Condense duplicates

Output:
a.bc.

Python Implementation


s = "a a a . . . b b c c . ."

filtered = [c for c in s if c != " "]

result = [filtered[0]]
for c in filtered[1:]:
    if c != result[-1]:
        result.append(c)

print("".join(result))

๐Ÿ’ก Key Takeaways

  • Simplify input before processing
  • Adjacent comparison removes redundancy efficiently
  • Linear-time solutions scale well
  • Technique applies to logs, streams, and compression
Interactive HTML learning view • High contrast • Readable everywhere

Thursday, August 22, 2024

Character-by-Character Analysis: Identifying Vowels and Consonants in a Word

You need to create a program that analyzes a given word character by character. For each character, the program should determine whether it is a vowel or a consonant. The program should stop processing as soon as it encounters a non-alphabetic character.


1. **Input Handling**:
   - The program starts by reading a word from the user input.

2. **Processing Each Character**:
   - It then iterates through each character in the word.

3. **Character Check**:
   - For each character, the program first checks if it is an alphabetic character. If it is not, the program stops further processing.
   - If the character is alphabetic, it checks whether it is a vowel (i.e., one of the characters in the string `'aeiou'`).
   - Based on this check, it prints either "vowel" if the character is a vowel, or "consonant" if it is not.



This approach processes a word to classify each character as either a vowel or a consonant, stopping when encountering a non-alphabetic character. It provides a clear and straightforward way to analyze the types of characters in a given input.

Featured Post

How HMT Watches Lost the Time: A Deep Dive into Disruptive Innovation Blindness in Indian Manufacturing

The Rise and Fall of HMT Watches: A Story of Brand Dominance and Disruptive Innovation Blindness The Rise and Fal...

Popular Posts