-1
def factors(numer):    
    return set(reduce(list.__add__, ([i, numer//i] for i in range(1, int(numer**0.5) + 1) if numer % i == 0)))

I'm trying to find the different sets of factors for the value "numer" but it gives me an error saying:

NameError: name 'reduce' is not defined

What could I replace reduce with to make my code work?

dirtydan
  • 36
  • 1
  • 5

1 Answers1

1

You need to import it in python3:

from functools import reduce

once you do it will work:

In [5]: from functools import reduce

In [6]: factors(10)
Out[6]: {1, 2, 5, 10}

You could also just flatten with itertools.chain:

from itertools import chain
def factors(numer):
    return set(chain.from_iterable((i, numer//i) for i in range(1, int(numer**0.5) + 1) if numer % i == 0))

Or flatten by adding another loop over the elements in each tuple:

def factors(numer):
    return set((j for i in range(1, int(numer**0.5) + 1) if numer % i == 0 for j in (i, numer//i)))
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321