Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add everything_between #19

Open
CodyKochmann opened this issue Dec 26, 2018 · 0 comments
Open

add everything_between #19

CodyKochmann opened this issue Dec 26, 2018 · 0 comments

Comments

@CodyKochmann
Copy link
Owner

this is really handy for things like scope parsing, should have been added a long time ago.

from generators import window
from collections import deque

def everything_between(pipe, before, after):
    if type(before)==type(after):
        output_type = ''.join if isinstance(before, str) else type(before)
    else:
        output_type = list
    
    before = tuple(before) if hasattr(before, '__len__') else (before,)
    after = tuple(after) if hasattr(after, '__len__') else (after,)
    
    pipe = window(pipe, max(len(before), len(after)))
    pipe = ((i[0], i[:len(before)]==before, i[:len(after)]==after) for i in pipe)
    
    output = deque()
    
    for i, is_before, is_after in pipe:
        if is_before:
            output.clear()
            for _ in range(len(before)-1):
                next(pipe)
        elif is_after and output:
                yield output_type(output)
                output.clear()
        else:
            output.append(i)
    
if __name__ == '__main__':
    s = 'hello world hello world'
    print(
        list(
            everything_between(
                s, 'o', 'l'
            )
        )
    )
    print(
        list(
            everything_between(
                s, 'he', 'wo'
            )
        )
    )
    print(list(
        everything_between(b'hello world hello world', b'he', b'wo')
    ))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant