0% found this document useful (0 votes)
11 views22 pages

7 Chapter 7 - Array-Oriented Programming With NumPy - Sessions 23, 24, 25 and 26 - Exercises

Uploaded by

milo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views22 pages

7 Chapter 7 - Array-Oriented Programming With NumPy - Sessions 23, 24, 25 and 26 - Exercises

Uploaded by

milo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Array-Oriented

Programming With
NumPy
Exercises
Exercise 1: Find the Maximum Element in an Array

• Write a Python function to find the maximum element in an array.


Example: [3, 8, 2, 1, 7].
Exercise 1 solution: Find the Maximum
Element in an Array
import numpy as np

def find_max(arr):
# Find the maximum element in the array
max_element = arr.max()
return max_element

# Create the array using NumPy


arr = np.array([3, 8, 2, 1, 7])

# Call the function to find the maximum element


max_value = find_max(arr)
print("Maximum element in the array:", max_value)
Exercise 2: Reverse an Array
• Write a Python function to reverse an array. Example: [3, 8, 2, 1, 7]
Exercise 2 solution: Reverse an Array
import numpy as np

def reverse_array(arr):
return arr[::-1]

arr = np.array([3, 8, 2, 1, 7])


reversed_arr = reverse_array(arr)

print("Original array:", arr)


print("Reversed array:", reversed_arr)
Exercise 3: Remove Duplicates from Array
• Write a Python function to remove duplicates from an array. Example:
[1, 2, 2, 3, 4, 4, 5]
Exercise 3 solution 1: Remove Duplicates from Array

import numpy as np

def remove_duplicates(arr):
return np.unique(arr)

# Example usage
arr = np.array([1, 2, 2, 3, 4, 4, 5])
unique_arr = remove_duplicates(arr)

print("Original array:", arr)


print("Array with duplicates removed:", unique_arr)
Exercise 3 solution 2: Remove Duplicates from Array

import numpy as np

def remove_duplicates(arr):
return list(set(arr)) #converts it to a set then to a list
set(arr): Converts the input array
arr into a set. A set is an unordered
# Example usage collection of unique elements, so any
arr = np.array([1, 2, 2, 3, 4, 4, 5]) duplicate elements in arr will be
unique_arr = remove_duplicates(arr) automatically removed when
print("Original array:", arr) converting it to a set.
print("Array with duplicates removed:", unique_arr)
Exercise 4 : Find the Sum of Even Numbers in an Array

• Write a Python function to find the sum of all even numbers in an


array. Example: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Exercise 4 solution 1: Find the Sum of Even Numbers in an Array

import numpy as np

def sum_of_even(arr):
# Filter even numbers
even_numbers = arr[arr % 2 == 0]

# Sum the even numbers


sum_even = np.sum(even_numbers)

return sum_even

# Example usage
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
result = sum_of_even(arr)
print("Sum of even numbers:", result)
Exercise 4 solution 2: Find the Sum of Even Numbers in an Array

import numpy as np

def sum_of_even_numbers(arr):
return sum(x for x in arr if x % 2 == 0)

# Example usage
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
result = sum_of_even_numbers(arr)
print("Sum of even numbers:", result)
Exercise 5 : Find the Intersection of Two Arrays

• Write a Python function to find the intersection of two arrays.


Example
[1, 2, 3, 4, 5]
[3, 4, 5, 6, 7]

Ouput:
Intersection of arrays: [3, 4, 5]
Exercise 5 : Find the Intersection of Two Arrays

import numpy as np

def find_intersection(arr1, arr2):


#The & operator is used to find the common elements between the sets.
intersection = np.array(list(set(arr1) & set(arr2)))
return intersection

# Example usage
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([3, 4, 5, 6, 7])

intersection = find_intersection(arr1, arr2)


print("Intersection of arrays:", intersection)
Exercise 6 : Find the Second Largest Element in an Array

• Write a Python function to find the second-largest element in an


array.
Example:
[12, 5, 7, 3, 8, 10, 15]

Ouput:
Second largest element: 12
Exercise 6 solution 1 : Find the Second Largest Element in an
Array

import numpy as np

def find_second_largest(arr):
# Sort the array in descending order
sorted_arr = np.sort(arr)[::-1] // sort it in a reverse order
# Return the second element (index 1) in the sorted array
return sorted_arr[1]

# Example usage
arr = np.array([12, 5, 7, 3, 8, 10, 15])
second_largest = find_second_largest(arr)
print("Second largest element:", second_largest)
Exercise 6 solution 2 : Find the Second Largest Element in an
Array

import numpy as np

def find_second_largest(arr):
sorted_arr = sorted(set(arr), reverse=True)
return sorted_arr[1]

# Example usage
arr = np.array([12, 5, 7, 3, 8, 10, 15])
second_largest = find_second_largest(arr)
print("Second largest element:", second_largest)
Exercise 7: Check for Palindrome Array
• Write a Python function to check if an array is a palindrome (reads the
same forwards and backwards).

Example:
Palindrome array [1, 2, 3, 2, 1]
Non palindrome array [1, 2, 3, 4, 5]

Ouput:
Is palindrome_array a palindrome? True
Is non_palindrome_array a palindrome? False
Exercise 7 solution: Check for Palindrome Array

import numpy as np

def is_palindrome(arr):
return arr == arr[::-1] #check the elements of arr with its reverse

# Test the function


palindrome_array = np.array([1, 2, 3, 2, 1])
non_palindrome_array = np.array([1, 2, 3, 4, 5])

print("Palindrome array:", is_palindrome(palindrome_array))


print("Non-palindrome array:", is_palindrome(non_palindrome_array))
Exercise 8: Implement Binary Search in a Sorted Array

• Write a Python function to perform a binary search in a sorted array to find a specific
element. Binary search repeatedly dividing the search interval in half.
• The idea is to compare the target value to the middle element of the array. If the target is
equal to the middle element, the search is successful, and the index of the middle element
is returned.
• If the target is less than the middle element, the search continues in the lower half of the
array.
• If the target is greater than the middle element, the search continues in the upper half of
the array. This process is repeated until the target is found or the search space becomes
empty.

Example:
Sorted array [1, 2, 3, 4, 5, 6, 7, 8, 9]
Target element = 5
Ouput:
Index of 5: 4
Exercise 8 solution: Implement Binary Search in a Sorted Array
import numpy as np

def binary_search(arr, target):


low, high = 0, len(arr) – 1 # because array indices start from 0. The last index of the array is len(arr) - 1
while low <= high:
mid = (low + high) // 2 # returns the floor value. It discards the fractional part of the division.

if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1

# Example usage:
sorted_array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
target_element = 5
result = binary_search(sorted_array, target_element)
print(f"Index of {target_element}:", result)
Exercise 9: merge two sorted arrays

• Write a python program that implements a function to merge two


sorted arrays into a new single sorted array. Please consider the
following two input arrays:
arr1 = [1, 3, 5, 7]
arr2 = [2, 4, 6, 8]

Output:
[1, 2, 3, 4, 5, 6, 7, 8]
def merge_sorted_arrays(arr1, arr2):
merged_array = [] #the new empty array that will hold the two input arrays Exercise 9: merge
i, j = 0, 0 # used to traverse through the two input arrays (arr1 and arr2) two sorted arrays
while i < len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]: # to sort the new array
merged_array.append(arr1[i])
i += 1
else:
merged_array.append(arr2[j])
j += 1
# If there are remaining elements in arr1 or arr2, append them to the merged array
merged_array.extend(arr1[i:])
merged_array.extend(arr2[j:])

return np.array(merged_array)

# Example usage:
arr1 = np.array([1, 3, 5, 7])
arr2 = np.array([2, 4, 6, 8])
result = merge_sorted_arrays(arr1, arr2)
print(result)

You might also like