[Tutor] Usefulness of BIFs all() and any()?

Richard D. Moores rdmoores at gmail.com
Tue Sep 25 18:03:01 CEST 2012

```Thanks for the great instruction, Tutors.

I'd been working over a script of mine that factors integers. I noticed
that if all the prime factors of n are the same, then if f is one of the
factors and p is the number of factors, n = f ^ p. I thought of using all()
or any(), but couldn't see how to do so. The only code I could think of for
this was:

n = 64
factors = [2, 2, 2, 2, 2, 2]
first_factor = factors
power = len(factors)
all_equal = True
for factor in factors:
if factor != first_factor:
all_equal = False
break
if all_equal == True:
power = len(factors)
print(n, "=", first_factor, "^", power)

But after asking my question I've changed it to:

n = 64
factors = [2, 2, 2, 2, 2, 2]
first_factor = factors
power = len(factors)
if all(factor == first_factor for factor in factors):
print(n, "=", first_factor, "^", power)

which prints,
64 = 2 ^ 6

Dick
-------------- next part --------------
An HTML attachment was scrubbed...