1

I was going through a code which have the following function. I was wondering if it possible to write the for loops in multiple lines and return the same exact value as the following.

def RecordsLists(self, a, q):
   return set([a1.union(a2) for a1 in a for a2 in a if len(a1.union(a2)) == q])
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Damien Rice
  • 111
  • 5

2 Answers2

0

Yes, you can use itertools.product(). Nested for loops are okay, but in my opinion they add an unnecessary amount of indentation.

from itertools import product
def RecordsLists(self, a, q):
    result = []
    for a1, a2 in product(a, repeat=2):
        union = a1.union(a2)
        if len(union) == q:
            result.append(union)
    return set(union)
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
  • 1
    "Don't use nested for loops; it's poor style." that is not true. It is perfectly reasonable and pythonic to use nested loops. `itertools.product` is usually helpful when the nesting is arbitrary, but if it is a fixed amount it doesn't give you any advantages. In any case, the OP is probably asking for a *transliteration* of their specific code. Not for how to improve it – juanpa.arrivillaga Mar 31 '22 at 02:23
  • I have revised to post to make it clear that this is my opinion and not a guideline. – BrokenBenchmark Mar 31 '22 at 02:45
0

Why not? All list comprehension are equal to loops.

def RecordsLists(self, terms, q):
    lst = []
    for term1 in terms:
        for term2 in terms:
            unioned = term1.union(term2)
            if len(unioned) == q:
                lst.append(unioned)
    return set(lst)

The only concern is the order of the two loops, but I think it won't affect result of this algorithm.

Lei Yang
  • 3,970
  • 6
  • 38
  • 59
  • 1
    "Why not? All list comprehension are equal to loops." *Yes they are*. Every list comprehension can be directly translated into regular for loops. Indeed, that is essentially how it works underneath the hood. – juanpa.arrivillaga Mar 31 '22 at 02:24
  • 1
    Side-note: In both this code and the OP's code, it's kinda silly to build a `list` just to `set`ify it at the end. You could just as easily use a `set` from the get-go and call `.add` on it instead of `.append` (and in the OP's code, they could write a raw `set` comprehension instead of `set`ifying the result of a listcomp). – ShadowRanger Mar 31 '22 at 02:39