Rodrigo Girão Serrão 🐍🚀 @mathspp.com · Sep 5

Here's a fun way of counting words in a string in Python. This doesn't split the string then count, so it'll work for ridiculously large strings (e.g. files you can't load into memory) Plus, I had fun making it branchless (i.e., without explicit `if`s) by doing arithmetic with the flag `in_word` 😅

2 likes 2 replies

?

Replies

ax3man1ac · Sep 5

My take: sum(in_word for in_word, _ in itertools.groupby('Hello, world!', lambda ch: ch not in whitespace))

Rodrigo Girão Serrão 🐍🚀 · Sep 5

For a more compact approach, see this comment using `itertools.groupby` in a brilliant way: bsky.app/profile/ax3m...