Fiery Phoenix Fiery Phoenix - 2 years ago 114
Python Question

Getting First Prime in a List of Random Numbers

I was playing around with the Python shell and I have what I believe is an extremely naive implementation of a function that simply returns the first prime number in a list of 100 randomly generated numbers (whose values are between 0 and 99, inclusive). Code below:

>>> def is_prime(n):
if n < 2:
return False
elif n == 2:
return True
for i in range(2, n):
if n % i == 0:
return False
return True

>>> from random import randint
>>> numbers = []
>>> for i in range(0, 100):
numbers.append(randint(0, 99))

>>> def get_first_prime(values):
temp = []
for i in values:
if is_prime(i):
return temp[0]

>>> get_first_prime(numbers)

I want this function to strictly return only the first prime number. My implementation uses a helper list to cache all primes and then simply return the element at the first index. It works, but I'm not convinced it's a good one. I'm sure there is a more efficient way of doing this that does not require scanning through the entire list, but I can't seem to think of one yet.

What are some better alternatives?

Answer Source
def get_first_prime(values):
    for i in values:
        if is_prime(i):
            return i

This way you don't keep searching once you find a prime. The function implicitly returns None if no prime is found.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download