Generating list of strings, need to limit both the list length and the total length of strings (without filter?)

16 views
Skip to first unread message

Štěpán Balážik

unread,
Nov 10, 2022, 4:33:21 AM11/10/22
to Hypothesis users
Hi,

I'm trying to write a strategy that generates lists of strings of limited length where the sum of lengths is also limited. So far I came up with this:

from hypothesis.strategies import lists, text
LIMIT = 100
lists(text(max_size=20), max_size=20).filter(lambda strings: sum(len(s) for s in strings) < LIMIT)

This works but I suppose that I am getting a performance hit from using the filter.
Is there an obvious (or even less obvious) way to do it without the filter?

Thanks for any help you can provide.
Štěpán

Zac Hatfield Dodds

unread,
Nov 14, 2022, 11:01:30 AM11/14/22
to Štěpán Balážik, Hypothesis users
Hi Štěpán,

You could also express this with a .map(), taking the longest acceptable prefix of the generated list.  For example:

from hypothesis.strategies import lists, text
LIMIT = 100
def trim(ls):
    while sum(len(s) for s in strings) > LIMIT:
        ls = ls[:-1]
    return ls
lists(text(max_size=20), max_size=20).map(trim)

I'd also suggest asking such questions on https://stackoverflow.com/questions/tagged/python-hypothesis - more people are around to answer, and the answers are more likely to be found by others who have similar questions :-)

Best,
Zac


--
You received this message because you are subscribed to the Google Groups "Hypothesis users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to hypothesis-use...@googlegroups.com.
To view this discussion on the web, visit https://groups.google.com/d/msgid/hypothesis-users/1be4fccb-581f-4286-a561-1af748200e3an%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages