Lesson 01 - Array - Student
Lesson 01 - Array - Student
Learning Objectives
Lesson Content
1. Introduction to Arrays
In Python, arrays can be represented using lists. An array is a data structure that contains elements of the
same type, accessible via indices.
Example:
# Declare an array
arr = [1, 2, 3, 4, 5]
Example:
arr = [1, 2, 3, 4, 5]
arr.append(6) # [1, 2, 3, 4, 5, 6]
arr.insert(2, 2.5) # [1, 2, 2.5, 3, 4, 5, 6]
arr.pop(3) # [1, 2, 2.5, 4, 5, 6]
arr.remove(2.5) # [1, 2, 4, 5, 6]
b. Traversing an Array
Example:
c. Searching in an Array
Example:
Phạm Văn Tú 1|
Olympiad Programming 2
if 3 in arr:
print("3 is in the array")
print(arr.index(3)) # Returns the index of element 3
a. Sorting
Example:
arr = [3, 1, 4, 1, 5, 9, 2]
arr.sort() # [1, 1, 2, 3, 4, 5, 9]
sorted_arr = sorted(arr, reverse=True) # [9, 5, 4, 3, 2, 1, 1]
b. Searching
Linear search
Example:
index = linear_search(arr, 4)
print(index) # Returns the index of element 4
4. Example Problems
Problem Statement: Given an array of integers, find the second largest number in the array.
Solution:
def second_largest(arr):
if len(arr) < 2:
return None
5. Practice Problems
Phạm Văn Tú 2|
Olympiad Programming 3
Hints:
# Reverse array
def reverse_array(arr):
start, end = 0, len(arr) - 1
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
return arr
# Find duplicates
def find_duplicates(arr):
count = {}
duplicates = []
for num in arr:
if num in count:
count[num] += 1
else:
count[num] = 1
return duplicates
Conclusion
In this lesson, we covered arrays in Python, basic and advanced operations on arrays, and how to use
arrays to solve real-world problems. Mastering arrays and their related operations is a crucial step in
solving programming problems in Olympiad contests.
Phạm Văn Tú 3|