bahaaz - 1 year ago 66

Python Question

I have to create a function that calculates how much factors an integer has. For example, when I call

`factor(10)`

`1`

`2`

`5`

`10`

Answer Source

The `%`

(modulus) operator gives you the remainder of a division. If that remainder is 0, then the second multiple is a factor of the second. So just loop through all the numbers from `1`

to `n`

and check if they're factors; if so, add them to the list with `append`

:

```
def factors(n):
result = []
for i in range(1, n + 1):
if n % i == 0:
result.append(i)
return result
```

Or, more concisely using lambdas:

```
def factors(n):
return filter(lambda i: n % i == 0, range(1, n + 1))
```