alvas
alvas

Reputation: 122112

Is there a simpler way to allocate value to a variable given a if condition - Python?

Other than the following brute force method, is there a simpler way to allocate value to a variable given a if condition?

Method 1:

a, b, c, d = 0.03,0.4,0.055,0.7
x = 0.2

if a < x:
  a = x
if b < x:
  b = x
if c < x:
  c = x
if d < x:
  d = x

Upvotes: 0

Views: 198

Answers (4)

Developer
Developer

Reputation: 8400

Absolutely consider using numpy.where which is the most efficient way to do what you want dealing with any size of array and dimension:

#your example:
a,b,c,d = 0.03,0.4,0.055,0.7
x = 0.2

#solution
values = numpy.asarray([a, b, c, d])
a,b,c,d = numpy.where(values<x, x, values)

#efficiency becomes clear when
values = numpy.random.rand(1000,100,10)     #any size and number of dimensions
values = numpy.where(values<x, x, values)   #just works fine and efficient

#further developments would be possible, e.g., multiple conditions
values = numpy.where((values>=0.3)&(values<0.7), 0.5, values)

Upvotes: 2

p7k
p7k

Reputation: 161

Perhaps, a bit more Haskell-like (zipWith)

from itertools import izip, starmap, repeat

a, b, c, d = starmap(max, izip(repeat(0.2), (0.03, 0.4, 0.055, 0.7)))

Some basic timeits (darwin 12.2.0, py 2.7.3):

In [0]: %timeit a,b,c,d = starmap(max, izip(repeat(0.2), (0.03, 0.4, 0.055, 0.7)))
1000000 loops, best of 3: 1.87 us per loop

In [1]: %timeit a,b,c,d = map(max, izip(repeat(0.2), (0.03, 0.4, 0.055, 0.7)))
100000 loops, best of 3: 3.99 us per loop

In [2]: %timeit a,b,c,d = [max(0.2, v) for v in [0.03,0.4,0.055,0.7]]
100000 loops, best of 3: 1.95 us per loop

In [3]: %timeit a,b,c,d = [max(0.2, v) for v in (0.03,0.4,0.055,0.7)]
1000000 loops, best of 3: 1.62 us per loop

Conclusions:

  • Tuples are faster to iterate over than lists ?!?

  • starmap beats map, even though max(values) is faster than max(*values) ?!?

Upvotes: 0

Viren Rajput
Viren Rajput

Reputation: 5736

try:

a = x if a < x else a

b = x if b < x else b

c = x if c < x else c

d = x if d < x else d

Upvotes: -3

Duncan
Duncan

Reputation: 95682

Perhaps:

a, b, c, d = max(a, x), max(b, x), max(c, x), max(d, x)

but if you have a lot of variables being handled in exactly the same way a list might be better.

values = [0.03,0.4,0.055,0.7]
x = 0.2

values = [max(v, x) for v in values]

Upvotes: 20

Related Questions