Python Forum
Help with extracting characters from string - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Help with extracting characters from string (/thread-41621.html)



Help with extracting characters from string - valentino1337 - Feb-19-2024

For our project we need to extract single characters from a given string which are separated from each other by the increasing number of places. Each extracted character must be exactly one place more apart from its predecessor than the one before. We need to use a string formed from the extracted characters as an input for the next phase of the project. Does anyone know how to solve this.

Example:
Input string: "A clown has a red nose.".
Output string: "A lnsee".


RE: Help with extracting characters from string - DeaD_EyE - Feb-19-2024

I separated the task in two subtasks.

First Task: Generator to generate indices
Second Task: Join the text. The indices from the generator are used to get the characters.

def index_gen(end):
    """
    GeneratorFunction for indicies

    The generator yield numbers from 0 to < end.
    Example:
    
    >>> list(index_gen(20))
    [0, 1, 3, 6, 10, 15]
    """
    
    current = 0
    step = 1
    
    while current < end:
        yield current
        current += step
        step += 1


def task(text):
    """
    >>> text = "A clown has a red nose."
    >>> task(text)
    'A lnsee'
    """
    return "".join(text[idx] for idx in index_gen(len(text)))


if __name__ == "__main__":
    # Input string: "A clown has a red nose.".
    # Output string: "A lnsee".
    text = "A clown has a red nose."

    print(text)
    print(task(text))
    



RE: Help with extracting characters from string - Pedroski55 - Feb-19-2024

Well, DeaD_EyE does it cooler!

Interesting however!

# shortcut to the first 2 places
result = [s[0], s[1]]
diff = 1
for l in range(2, len(s)):
    diff +=l
    if len(s) < diff:
        break
    result.append(s[diff])
    restring = ''.join(result)
    print(restring)