Python - Check if numbers in list are factors of a number

Zach picture Zach · Mar 14, 2010 · Viewed 9.9k times · Source

I have a list of numbers (integers) (say, from 1 to 10).

They're not necessarily consecutive, but they are in ascending order.

I've prompted the user multiple times to enter a choice of the available numbers. When that number is entered, it is removed from the list along with any of its factors that may be there.

I've prevented the user from selecting prime numbers. However, at some point in time, there may be non-prime numbers there, which have no factors remaining.

I'm relatively new to Python, so I'm having trouble implementing:

  • Checking if the number selected has no factors remaining (even if it is not prime).

  • Checking if only prime numbers remain, or numbers without factors.

I'm thinking of using for statements, but I'm not sure exactly how to implement them. Can anyone offer advice, or code? Thanks in advance...

Answer

sth picture sth · Mar 14, 2010

To check if there are any factors of the number guess remaining you can use any():

hasfactors = any(guess % n == 0 for n in numbers)

To check if all the remaining numbers are prime, all() can be used. (Since you say you already prevented the user from inputting prime numbers I assume you have some kind of isprime() function):

onlyprimes = all(isprime(n) for n in numbers)