Ramon Zarazua B.
Ramon Zarazua B.

Reputation: 7415

Building ranges using python set-builder notation

Hey, I am trying to build a set of ranges in python like so:

Given (0.1, 0.2, 0.7)

I want to build [(0, 0.1), (0.1, 0.3), (0.3, 1)]

While this could be achieved easily through a regular for-loop, as a learning exercise I wanted to see if this could be achieved via a set-builder expression.

My first thought was to do [(i, i+t) for i = 0, i+=t, t in (0.1, 0.2, 0.7)], however that is not valid syntax, I tried a few other expressions, however I noticed that it is not possible to assign values to variables inside the expression. Looking for information, it seems that in list-builder expressions you can iterate through various other iterable objects at the same time, but not keep a state.

So I want to know if it is at all possible to do something like this in a "pythonic" way.

Upvotes: 0

Views: 2735

Answers (2)

minhee
minhee

Reputation: 5828

It seems that just looping is a way more Pythonic. Write a generator function:

def build_ranges(steps):
    val = 0
    for step in steps:
        yield val, val + step
        val += step

Then:

>>> input = (0.1, 0.2, 0.7)
>>> list(build_ranges(input))
[(0, 0.10000000000000001), (0.10000000000000001, 0.30000000000000004), (0.30000000000000004, 1.0)]

Upvotes: 2

Jim Brissom
Jim Brissom

Reputation: 32969

A possible solution is:

a = (0.1, 0.2, 0.7)
l = [(sum(a[:ii]), sum(a[:ii+1])) for ii, v in enumerate(a)]

Yet being pythonic does not mean being the most concise, or using comprehensions at any place possible - if a simple loop is more readable, go for it (if there are no other factors hinting to a list comprehension, for example).

Upvotes: 3

Related Questions