We have considered lists in the previous lectures. It is extremely convenient to use these data structures BUT ... Python's list data structures are not real arrays.
"The implementation uses a contiguous array of references to other objects, and keeps a pointer to this array and the array’s length in a list head structure."
This is exactly why NumPy came to be in 2005. NumPy implements real one-dimensional (as well as multi-dimensional) arrays that is up to 50x faster that traditional Python lists.
In the last chapter, we will learn about NumPy arrays.
Cheers!
====================================================
#5 Python Programming Exercise
a.)
The aim is to filter an exiting list of integers with the list comprehension approach. So here is a function that determines whether an input is prime or not:
def is_prime(x):
if x < 0:
return False
if x == 1:
return False
if x == 2:
return True
for num in range(2, x):
if x % num == 0:
return False
return True
Then we have a data structure (list) storing integers.
numbers = [1, 5, 43, 55, 76, 100, 123, 11, 2, -5, 87, 99]
Write an algorithm that filters this list of integers and constructs a new list with the prime numbers. Of course you can use the is_prime() function to decide whether an integer is prime or not.
b.)
Create a list of squared values in the range [5, 10] - 5 and 10 are part of the interval. So the result should be [25, 36, 49, 64, 81, 100]. Use list comprehension!
Good luck!
=======================================================
#5 Python Programming Solution
a.)
def is_prime(x):
if x < 0:
return False
if x == 1:
return False
if x == 2:
return True
for num in range(2, x):
if x % num == 0:
return False
return True
numbers = [1, 5, 43, 55, 76, 100, 123, 11, 2, -5, 87, 99]
primes = [num for num in numbers if is_prime(num)]
print(primes)