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 groupsof built-in #297

Closed
evhub opened this issue Jul 26, 2017 · 6 comments
Closed

Add groupsof built-in #297

evhub opened this issue Jul 26, 2017 · 6 comments

Comments

@evhub
Copy link
Owner

evhub commented Jul 26, 2017

Something like

def groupsof(n, iterable):
    """Split iterable into groups (tuples) of length n.
    If the length of iterable is not divisible by n, the last group may be of size < n."""
    iterator = iter(iterable)
    while True:
        group = [next(iterator)]
        for _ in range(1, n):
            try:
                group.append(next(iterator))
            except StopIteration:
                break
        yield tuple(group)
        if len(group) != n:
            break
@evhub evhub added this to the v1.3.0 milestone Jul 26, 2017
@evhub
Copy link
Owner Author

evhub commented Jul 26, 2017

Should probably be a class, though, not a function, like map, filter, enumerate, count, etc.

@evhub evhub modified the milestone: v1.3.0 Aug 4, 2017
@kbaskett248
Copy link
Contributor

I'm working on implementing this feature. I just need to finish up the tests and add documentation.

@evhub
Copy link
Owner Author

evhub commented Aug 26, 2017

@kbaskett248 Awesome! Make sure you're working against develop, not master, then just submit a PR once you've got something you want me to take a look at!

@kbaskett248
Copy link
Contributor

kbaskett248 commented Aug 26, 2017

Sure thing. One question about the n argument: should I be validating it at all? Perhaps raise a TypeError if it can't be coerced to an int? Or maybe a ValueError if it is non-positive?

I implemented it using range like you suggested, so it does throw a TypeError when the __iter__ method is called. It might be better to check that in __init__ so the crash happens where the error is made.

You are free to pass in negative numbers or zero, however, which achieves the same results as passing in 1. This seems really unintuitive, so I think that may be worth raising an exception.

@evhub
Copy link
Owner Author

evhub commented Aug 26, 2017

@kbaskett248 Raising an exception seems like a good idea, go for it! Also, just to check, you're putting this in header.py_template, correct?

@kbaskett248
Copy link
Contributor

Yes, I am.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants