9

I'm writing a small function to check if all elements in a list are less than or equal to a limit. This is just for practice, and should be done without using any loops.

def small_enough(a, limit): 
    return all(x <= limit for x in a)
small_enough([66, 101], 200)

Been on this for a while but I can not find any substituting code to replace the for loop.This code works perfectly fine as it is - however, I am trying to get the results without using loops. Trying to write something a bit more 'pythonic'.

4 Answers4

4

If using numpy is ok, you can do

import numpy as np

x = np.asarray([66,101])
print(all(x <= 200))
user2653663
  • 2,818
  • 1
  • 18
  • 22
2

In general,

f(x) for x in xs == map(f, xs) 

so

def small_enough(a, limit): 
    return all(map(lambda x: x <= limit, a))
molbdnilo
  • 64,751
  • 3
  • 43
  • 82
1

There's always a loop somewhere, even if you can't see it, and here's just one solution without a for loop:

def small_enough(a, limit): 
    return not sum(map(lambda x : x > limit, a))

print(small_enough([66, 101], 200))  #  True
print(small_enough([66, 201], 200))  #  False
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • 1
    Calling dundermethods directly is not a good idea. Here's just one example that doesn't work: `(3).__gt__(2.0)` -> `NotImplemented`. – Aran-Fey Aug 29 '19 at 11:07
  • @Aran-Fey I just rolled-back my edit, I was using a lambda before, and thanks for your comment, it is really helpful. – DjaouadNM Aug 29 '19 at 14:28
1

Of course you can use recursion here:

def small_enough(a, limit):
    if a:
        return a[0] <= limit and small_enough(a[1:], limit)
    else:
        return True

or even

def small_enough(a, limit):
    return not a or (a[0] <= limit and small_enough(a[1:], limit))

But your solution is really much more readable than this. Besides, recursion doesn't actually avoid looping, it just looks different.

kojiro
  • 74,557
  • 19
  • 143
  • 201
  • The recursion is also horrendously inefficient (and, for large enough `a`, will probably produce an exception). – chepner Aug 27 '19 at 14:17
  • @chepner that said, recursion does force you to give some thought to the construction of the code. In this case, I had to ask myself "does OP really want the answer to be `True` when the input list is empty?" I stuck with what `all` does, but I think it's nevertheless useful to have to think about stuff in more than one way. – kojiro Aug 27 '19 at 14:19
  • And worth pointing out Python doesn't have tail call optimization, so rewriting loops as tail recursion is an anti-pattern in Python – wrschneider Aug 27 '19 at 14:55