4

How do i remove the repetitions

 if a < 2 or b < 2 or c < 2 or d < 2: 
       pass #logic

I want to remove the repetitions. Something like this:

if (a,b,c,d) < 2:
   pass #logic 
JayPeerachai
  • 3,499
  • 3
  • 14
  • 29
  • You might want to use a list or dictionary instead of a sequence of variables. This will allow you to use loop and comprehensions. – Klaus D. Dec 21 '21 at 09:24

6 Answers6

2

I wouldn't import numpy just for this as other answers suggest. It's probably overkill.

I would do something like:

condition = lambda x: x < 2
if any(condition(x) for x in (a, b, c, d)):
    # whatever you want

Or more compact (but less reusable):

if any(x < 2 for x in (a, b, c, d)):
    # whatever you want
asmartin
  • 459
  • 1
  • 3
  • 12
2

Another slightly different way is to check if the smallest variable is less than the target value. In other words, if the smallest variable is not less than the target - then surely none of them is:

if min(a, b, c, d) < 2:
    # do something

This however needs to actually find the minimal value behind the scenes and loses the short-circuiting advantage of using any with a generator expression.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
1

When using numpy this can be done with .all() and .any():

import numpy as np

array = np.asarray([1,2,3])

if (array < 2).any():
    print('True')
else:
    print('False')

#output: True

if (array < 2).all():
    print('True')
else:
    print('False')

#output: False

d8411BT
  • 11
  • 2
1

In addition to other answers, use generator expression to reduce computing time

if True in (i < 2 for i in [a,b,c,d]):
   pass #logic
JayPeerachai
  • 3,499
  • 3
  • 14
  • 29
1

I would have used combination of Numpy and any here.

For example:

a, b, c, d = 10, 10, 10, 10

Convert it into a numpy array:

import numpy as np

arr = np.array([a, b, c, d])

And now you can do this:

if any(arr < 2):
    pass #logic
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Amit Amola
  • 2,301
  • 2
  • 22
  • 37
-1

Use built-in any function:

if any(map(lambda x: x < 2, (a, b, c, d))):
    pass  # whatever here
Ratery
  • 2,863
  • 1
  • 5
  • 26
  • you can also use `filter`. `len(filter(lambda x: x>=2, (a, b, c, d))) == 0` – cup11 Dec 21 '21 at 10:36
  • @cup11 This way checks that ***all*** numbers are less 2. The question asks for ***any***. Maybe `len(filter(lambda x: x<2, (a, b, c, d))) != 0` would work but seems like an unnecessary complication – Tomerikoo Dec 21 '21 at 12:02
  • @Tomerikoo You're right. I didn't notice that. – cup11 Dec 21 '21 at 13:55