Fiery Phoenix - 9 months ago 50

Python Question

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):

temp.append(i)

return temp[0]

>>> get_first_prime(numbers)

I want this function to strictly return

What are some better alternatives?

Answer

```
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.