Uploaded by Akhyiar

Arrays in Computer Science: 1D Arrays & Examples

advertisement
Paper-2 /4 Arrays
Computer Science
Arrays
An array is group of consecutive memory locations with same name and type. Simple
variable is single memory locations with a unique name and type. But an array is a
collection of different adjacent memory locations. All these memory locations have one
collective name and type.
One dimensional array:
Characteristics of 1D array:
An array is an ordered, static set of elements in a fixed-size memory location
An array can only store 1 data type
A 1D array is a linear array
Indexes start at generally start at 0, known as zero-indexed
MR. FAZLE MALIK
PHNO:03334732544
1
Paper-2 /4 Arrays
Computer Science
We can also create arrays as follows:
// Creating a one-dimensional array
array scores [5]
scores [0] = 12
scores [1] = 10
scores [2] = 30
scores [3] = 40
scores [4] = 50
OR
scores ← [12, 10,20,30,40,50]
Using arrays:
MR. FAZLE MALIK
PHNO:03334732544
2
Paper-2 /4 Arrays
Computer Science
Arrays are used to store a large amount of similar kind of data. For example, if we want
to store the marks of 100 students, we have to declare 100 variables. It is time consuming
process to use these variables individually. We can save this time by using arrays. Instead
of using 100 variables, we can declare only one arrays of 100 elements.
Array declaration in python:
marks = [0] * 5 # Creating a list of length 5 to store marks
or
marks = []
Python code example-1:
How to declare, input and print values in an array
marks = [0] * 5 # Creating a list of length 5 to store marks
for a in range(5):
marks[a] = int(input("Enter marks: ")) # Convert input to integer
for a in range(5):
print("Value at index", a, "is", marks[a])
MR. FAZLE MALIK
PHNO:03334732544
3
Paper-2 /4 Arrays
Computer Science
pseudocode example of the above program code:
DECLARE Marks : ARRAY[0 : 4] OF INTEGER
FOR a ← 0 TO 4
OUTPUT "Enter marks: "
INPUT Marks[a]
ENDFOR
FOR a ← 0 TO 4
OUTPUT "Value at index ", a, " is ", Marks[a]
ENDFOR
Example-2
How to find sum and average of number in arrays?
Python code:
num = [0] * 5
sum = 0
# Initialize an array of size 5 with zeros
# Fill the array with user input numbers
for i in range(5):
num[i] = int(input("Enter number: "))
sum += num[i]
# Calculate the average
average = sum / 5
# Print the sum and average
print("The sum is", sum)
print("The average is", average)
Write pseudocode of the above program code:
MR. FAZLE MALIK
PHNO:03334732544
4
Paper-2 /4 Arrays
Computer Science
Example-3
Python code Searching in arrays:
attendance =["saad", "sanan", "kamran", "zia","fayyaz", "shan"]
print("Who are you searching for: ")
search = input()
found = False
for x in range(len(attendance)):
if attendance[x] == search:
print(search + " found at position:", x)
found = True
MR. FAZLE MALIK
PHNO:03334732544
5
Paper-2 /4 Arrays
Computer Science
if not found:
print(search + " NOT found in the array")
Note: Pseudocode declaration of arrays with fixed elements
// Declare an array to store student names
DECLARE students: ARRAY[6] OF STRING
// Initialize the array with student names
students[1] = "ali"
students[2] = "ahmed"
students[3] = "hassan"
Write pseudocode of the above program code:
MR. FAZLE MALIK
PHNO:03334732544
6
Paper-2 /4 Arrays
Computer Science
Example-4
Python code Searching in arrays using Input statement
Student = [""] * 5
strings
# Initialize an array of size 5 with empty
found = False
# Fill the array with user input names
for b in range(5):
print("Enter name to fill this array: ")
Student[b] = input()
name = input("Who are you searching for: ")
# Search for the name in the array
for c in range(5):
if name == Student[c]:
print("Name is found at position", c)
found = True
if not found:
MR. FAZLE MALIK
PHNO:03334732544
7
Paper-2 /4 Arrays
Computer Science
print("Name is not found in the array list")
Write pseudocode of the above program code:
MR. FAZLE MALIK
PHNO:03334732544
8
Paper-2 /4 Arrays
Computer Science
Sorting arrays using In-efficient:
Bubble Sort Algorithm
Bubble Sort is an elementary sorting algorithm, which works by
repeatedly exchanging adjacent elements, if necessary. When no
exchanges are required, the file is sorted.
We assume list is an array of n elements. We further assume
that swap function swaps the values of the given array elements.
Step 1 − Check if the first element in the input array is greater than
the next element in the array.
Step 2 − If it is greater, swap the two elements; otherwise move the
pointer forward in the array.
Step 3 − Repeat Step 2 until we reach the end of the array.
Step 4 − Check if the elements are sorted; if not, repeat the same
process (Step 1 to Step 3) from the last element of the array to the
first.
Step 5 − The final output achieved is the sorted array.
We observe in algorithm that Bubble Sort compares each pair of array
element unless the whole array is completely sorted in an ascending
order. This may cause a few complexity issues like what if the array
needs no more swapping as all the elements are already ascending.
To ease-out the issue, we use one flag variable swapped which will
help us see if any swap has happened or not. If no swap has occurred,
i.e. the array requires no more processing to be sorted, it will come
out of the loop.
Example
We take an unsorted array for our example. Bubble sort takes Ο(n2)
time so we're keeping it short and precise.
Bubble sort starts with very first two elements, comparing them to
check which one is greater.
In this case, value 33 is greater than 14, so it is already in sorted
locations. Next, we compare 33 with 27.
MR. FAZLE MALIK
PHNO:03334732544
9
Paper-2 /4 Arrays
Computer Science
We find that 27 is smaller than 33 and these two values must be
swapped.
Next we compare 33 and 35. We find that both are in already sorted
positions.
Then we move to the next two values, 35 and 10.
We know then that 10 is smaller 35. Hence they are not sorted. We swap
these values. We find that we have reached the end of the array. After
one iteration, the array should look like this −
To be precise, we are now showing how an array should look like after
each iteration. After the second iteration, it should look like this −
MR. FAZLE MALIK
PHNO:03334732544
10
Paper-2 /4 Arrays
Computer Science
Notice that after each iteration, at least one value moves at the end.
And when there's no swap required, bubble sort learns that an array is
completely sorted.
MR. FAZLE MALIK
PHNO:03334732544
11
Paper-2 /4 Arrays
Computer Science
Now we should look into some practical aspects of bubble sort.
Implementation
One more issue we did not address in our original algorithm and its
improvised pseudocode, is that, after every iteration the highest
values settles down at the end of the array. Hence, the next iteration
need not include already sorted elements. For this purpose, in our
implementation, we restrict the inner loop to avoid already sorted
values.
Python code:
arr = [0] * 5 # Creating a list of length 5 to store marks
# Taking input for marks
for i in range(5):
arr[i] = int(input("Enter marks: "))
# Bubble sort algorithm to sort the array
for i in range(5):
for j in range(i + 1, 5):
if arr[i] > arr[j]:
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
print("Sorted values:")
for i in range(5):
print(arr[i])
Write pseudocode of the above program code:
DECLARE arr:ARRAY[0:4] AS INTEGER
DECLARE i, j, temp AS INTEGER
# Input marks
FOR i ← 0 TO 4 DO
MR. FAZLE MALIK
PHNO:03334732544
12
Paper-2 /4 Arrays
Computer Science
OUTPUT "Enter marks: "
INPUT arr[i]
ENDFOR
# Bubble sort algorithm to sort the array
FOR i ← 0 TO 4
FOR j ← i + 1 TO 4
IF arr[i] > arr[j] THEN
temp ← arr[i]
arr[i] ← arr[j]
arr[j] ← temp
ENDIF
ENDFOR
ENDFOR
# Output sorted values
OUTPUT "Sorted values:"
FOR i ← 0 TO 4
OUTPUT arr[i]
ENDFOR
MR. FAZLE MALIK
PHNO:03334732544
13
Paper-2 /4 Arrays
Computer Science
Efficient bubble sorting:
Python code:
MyList = [0] * 8
# Input numbers into the list
for Index in range(8):
MyList[Index] = int(input("Enter a number: "))
MaxIndex = 7
n = MaxIndex - 1
while True:
NoMoreSwaps = True
for j in range(n + 1):
if MyList[j] > MyList[j + 1]:
Temp = MyList[j]
MyList[j] = MyList[j + 1]
MyList[j + 1] = Temp
NoMoreSwaps = False
n -= 1
if NoMoreSwaps:
break
# Print the sorted list
for index in range(8):
print(MyList[index], end=" ")
MR. FAZLE MALIK
PHNO:03334732544
14
Paper-2 /4 Arrays
Computer Science
MyList = [0] * 8
# Input numbers into the list
for Index in range(8):
MyList[Index] = int(input("Enter a number: "))
MaxIndex = 7
n = MaxIndex - 1
while True:
NoMoreSwaps = True
for j in range(n + 1):
if MyList[j] > MyList[j + 1]:
Temp = MyList[j]
MyList[j] = MyList[j + 1]
MyList[j + 1] = Temp
NoMoreSwaps = False
#ENDIF
#END FOR
n -= 1
# END While below
if NoMoreSwaps == True:
break
# Print the sorted list
for index in range(8):
print(MyList[index], end=" ")
MR. FAZLE MALIK
PHNO:03334732544
15
Paper-2 /4 Arrays
Computer Science
Pseudocode:
// Declare the variables
DECLARE MyList : ARRAY[7] OF INTEGER
DECLARE Index, MaxIndex, n, j, Temp AS INTEGER
DECLARE NoMoreSwaps AS BOOLEAN
// Input numbers into MyList
FOR Index ← 0 TO 6
OUTPUT "Enter a number: "
INPUT MyList[Index]
ENDFOR
// Set initial values for sorting
MaxIndex ← 7
n ← MaxIndex - 1
// Bubble sort algorithm
REPEAT
NoMoreSwaps ← TRUE
FOR j ← 0 TO n - 1
IF MyList[j] > MyList[j + 1] THEN
Temp ← MyList[j]
MyList[j] ← MyList[j + 1]
MyList[j + 1] ← Temp
NoMoreSwaps ← FALSE
ENDIF
ENDFOR
n←n-1
UNTIL NoMoreSwaps = TRUE
// Output sorted list
MR. FAZLE MALIK
PHNO:03334732544
16
Paper-2 /4 Arrays
Computer Science
FOR Index ← 0 TO 6
OUTPUT MyList[Index]
ENDFOR
Write pseudocode of the above program code:
def bubble_sort_version_2(items):
"""A quite efficient bubble sort that stops if the items are sorted"""
# Initialise the variables
num_items = len(items)
swapped = True
# Repeat while one or more swaps have been made
while swapped == True:
swapped = False
MR. FAZLE MALIK
PHNO:03334732544
17
Paper-2 /4 Arrays
Computer Science
# Perform a pass
for index in range(0, num_items - 1):
# Compare items to check if they are out of order
if items[index] > items[index + 1]:
# Swap the items
temp = items[index]
items[index] = items[index + 1]
items[index + 1] = temp
swapped = True
print(items) # Testing
"""Perform a bubble sort on the test data"""
test_items = [80,64,50,43,35,21,7,3,2] # Least sorted
print("### Bubble sort version 2 (while and for loops) ###")
print(test_items)
bubble_sort_version_2(test_items)
MR. FAZLE MALIK
PHNO:03334732544
18
Paper-2 /4 Arrays
Computer Science
2D Arrays:
Two dimensional arrays can be considered as a table that consist of rows and column.
Each element in Two-dimensional array is referred with two indexes. One index is used to
indicate the row and the second index indicates the column of the element. The syntax
for declaring two-dimensional array is as follows:
Dim <arrays Name> <Rows, Columns > As <type>
MR. FAZLE MALIK
PHNO:03334732544
19
Paper-2 /4 Arrays
MR. FAZLE MALIK
Computer Science
PHNO:03334732544
20
Paper-2 /4 Arrays
Computer Science
Python declaration of 2D arrays:
# Method 1: Initialising an empty 2D array
rows = 3
cols = 4
array_2d = [[0 for _ in range(cols)] for _ in range(rows)]
# The above code creates a 2D array with 3 rows and 4 columns, filled
with zero
# Method 2: Initialising a 2D array with values
array_2d = [[1, 2, 3],[4, 5, 6], [7, 8, 9]]
# The above code creates a 2D array with 3 rows and 3 columns, with
the specified value
# Accessing elements in the 2D array
print(array_2d[0][0])
# Output: 1
print(array_2d[1][2])
# Output: 6
MR. FAZLE MALIK
PHNO:03334732544
21
Paper-2 /4 Arrays
Computer Science
For example, the following statement will declare a two-dimensional with three rows and
five columns.
Python code:
# Initialize a 2D array with dimensions 3x2
array = [[0 for j in range(2)] for i in range(3)]
# Loop through each element of the array to input data
for i in range(3):
for j in range(2):
print("Enter data:")
array[i][j] = int(input())
# Loop through each element of the array to print the values along
with their indices
for i in range(3):
for j in range(2):
print(array[i][j], "at", i, ",", j)
Write pseudocode of the above program code:
MR. FAZLE MALIK
PHNO:03334732544
22
Paper-2 /4 Arrays
Computer Science
Example-2
Python code:
# Initialize variables
MaxRows = int(input("Enter no of Rows: "))
MaxColumns = int(input("Enter no of Columns: "))
# Initialize a 2D array with dimensions MaxRows x MaxColumns
ThisTable = [[0 for j in range(MaxColumns)] for i in range(MaxRows)]
for Row in range(MaxRows):
for Column in range(MaxColumns):
print(ThisTable[Row][Column], end=" ")
print()
#When you specify end=" ", you're telling Python to use a space
character (" ") instead of the default newline character ("\n") at
#the end of each print statement
# Fill the array with user input
for Row in range(MaxRows):
for Column in range(MaxColumns):
print("Fill this array:")
ThisTable[Row][Column] = int(input())
# Print the filled array
MR. FAZLE MALIK
PHNO:03334732544
23
Paper-2 /4 Arrays
Computer Science
for Row in range(MaxRows):
for Column in range(MaxColumns):
print(ThisTable[Row][Column], end=" ")
print()
OR
# Initialize variables
MaxRows = int(input("Enter no of Rows: "))
MaxColumns = int(input("Enter no of Columns: "))
# Initialize a 2D array with dimensions MaxRows x MaxColumns
ThisTable = [[0 for j in range(MaxColumns)] for i in range(MaxRows)]
# Fill the array with user input
for Row in range(MaxRows):
for Column in range(MaxColumns):
print("Fill this array:")
ThisTable[Row][Column] = int(input())
# Print the filled array
for Row in range(MaxRows):
for Column in range(MaxColumns):
print(ThisTable[Row][Column], end=" ")
print()
input()
MR. FAZLE MALIK
PHNO:03334732544
24
Paper-2 /4 Arrays
Computer Science
Write pseudocode of the above program code:
MR. FAZLE MALIK
PHNO:03334732544
25
Paper-2 /4 Arrays
Computer Science
Arrays Practice questions
1. Write a program to input price of 10 items in a one-dimensional array
and display them in a row on the screen. Also, display the average
price of all the items.
price = [0] * 11 # Creating an array of size 11
total = 0 # Variable to store the total price
print("Enter the price of 10 items:")
for counter in range(1, 11):
price[counter] = float(input())
print()
print("Prices of items:")
for counter in range(1, 11):
print(price[counter], end=" ")
total += price[counter]
average = total / 10
print("\n\nThe average price of all the items is =", average)
2. Make changes in program (1) such that it also displays number of
items that cost more than average, equal to average and less than
average
MR. FAZLE MALIK
PHNO:03334732544
26
Paper-2 /4 Arrays
Computer Science
price = [0] * 11 # Creating an array of size 11 to match the VB.NET 1based indexing
total = 0 # Variable to store the total price
greater = 0 # Variable to store the count of prices greater than average
lesser = 0 # Variable to store the count of prices lesser than average
equal = 0 # Variable to store the count of prices equal to average
print("Enter the price of 10 items:")
for counter in range(1, 11):
price[counter] = float(input())
print()
print("Prices of items:")
for counter in range(1, 11):
print(price[counter], end=" ")
total += price[counter]
average = total / 10
print("\n\nThe average price of the given items is =", average)
for counter in range(1, 11):
if price[counter] > average:
greater += 1
elif price[counter] < average:
lesser += 1
else:
equal += 1
print("The number of prices greater than average =", greater)
print("The number of prices lesser than average =", lesser)
print("The number of prices equal to average =", equal)
3. Write a program to input age of 10 people in a one-dimensional array.
Display the age the oldest and the youngest person with appropriate
message
MR. FAZLE MALIK
PHNO:03334732544
27
Paper-2 /4 Arrays
Computer Science
# Input the ages of 10 people
ages = []
# Collecting the ages
for i in range(10):
age = int(input(f"Enter the age of person {i+1}: "))
ages.append(age)
# Initialize variables for the oldest and youngest ages
oldest_age = ages[0]
youngest_age = ages[0]
# Loop through the list to find the oldest and youngest ages
for age in ages:
if age > oldest_age:
oldest_age = age
if age < youngest_age:
youngest_age = age
# Displaying the results
print(f"The oldest person is {oldest_age} years old.")
print(f"The youngest person is {youngest_age} years old.")
OR
age = [0] * 11 # Creating an array of size 11
young = None # Variable to store the youngest age
old = None # Variable to store the oldest age
print("Enter the age of 10 people:")
for counter in range(1, 11):
age[counter] = int(input())
store = age[1]
for counter in range(1, 11):
if store > age[counter]:
store = age[counter]
MR. FAZLE MALIK
PHNO:03334732544
28
Paper-2 /4 Arrays
Computer Science
young = store
store = age[1]
for counter in range(1, 11):
if store < age[counter]:
store = age[counter]
old = store
print("\nThe youngest age is =", young)
print("The oldest age is =", old)
4. Write a program to input total income of 10 people in array. Display
the values stored in an array and also print how many of them are
taxpayers. If the total income is greater than or equal to Rs 200000
then the person has to pay the tax.
income = [0] * 11 # Creating an array of size 11 to match the VB.NET 1based indexing
taxP = 0 # Variable to store the number of taxpayers
print("Enter total income of ten peoples:")
for counter in range(1, 11):
income[counter] = int(input())
for counter in range(1, 11):
if income[counter] >= 200000:
taxP += 1
print("income({}) = {}".format(counter, income[counter]))
print("The number of taxpayers =", taxP)
5. Write a program that asks a user to type 5 integers and print the largest
value.
# Initialize an empty list to store the integers
numbers = []
# Collect 5 integers from the user
for i in range(5):
MR. FAZLE MALIK
PHNO:03334732544
29
Paper-2 /4 Arrays
Computer Science
number = int(input(f"Enter integer {i+1}: "))
numbers.append(number)
# Initialize the variable to hold the largest value
largest = numbers[0]
# Loop through the list to find the largest value
for number in numbers:
if number > largest:
largest = number
# Print the largest value
print(f"The largest value is: {largest}")
OR
# Ask the user to input 5 integers
print("Please enter 5 integers:")
# Initialize an empty list to store the integers
numbers = []
# Use a loop to get 5 integers from the user
for i in range(5):
num = int(input(f"Enter integer {i+1}: "))
numbers.append(num)
# Find the largest number in the list
largest_number = max(numbers)
# Print the largest number
print(f"The largest number is: {largest_number}")
6. Write a program that askes the user to type 10 integers and writes the
smallest value.
# Initialize an empty list to store the integers
MR. FAZLE MALIK
PHNO:03334732544
30
Paper-2 /4 Arrays
Computer Science
numbers = []
# Collect 5 integers from the user
for i in range(5):
number = int(input(f"Enter integer {i+1}: "))
numbers.append(number)
# Initialize the variable to hold the largest value
largest = numbers[0]
# Loop through the list to find the largest value
for number in numbers:
if number < largest:
largest = number
# Print the largest value
print(f"The largest value is: {largest}")
OR
# Ask the user to input 10 integers
print("Please enter 10 integers:")
# Initialize an empty list to store the integers
numbers = []
# Use a loop to get 10 integers from the user
for i in range(10):
num = int(input(f"Enter integer {i+1}: "))
numbers.append(num)
# Initialize the smallest number with the first number in the list
smallest_number = numbers[0]
# Iterate through the list to find the smallest number
for num in numbers:
if num < smallest_number:
MR. FAZLE MALIK
PHNO:03334732544
31
Paper-2 /4 Arrays
Computer Science
smallest_number = num
# Print the smallest number
print(f"The smallest number is: {smallest_number}")
Further Example:
Example 1
Python program to find the largest number in an array −
Open Compiler
import array as arr
a = arr.array('i', [10,5,15,4,6,20,9])
print (a)
largest = a[0]
for i in range(1, len(a)):
if a[i]>largest:
largest=a[i]
print ("Largest number:", largest)
It will produce the following output −
array('i', [10, 5, 15, 4, 6, 20, 9])
Largest number: 20
Pseudocode:
DECLARE a : ARRAY[1:7] OF INTEGER
a ← [10, 5, 15, 4, 6, 20, 9]
OUTPUT a
DECLARE largest : INTEGER
largest ← a[1]
FOR i ← 2 TO LEN(a)
IF a[i] > largest THEN
MR. FAZLE MALIK
PHNO:03334732544
32
Paper-2 /4 Arrays
Computer Science
largest ← a[i]
ENDIF
NEXT i
OUTPUT "Largest number:", largest
Example 2
Python program to store all even numbers from an array in another array −
Open Compiler
import array as arr
a = arr.array('i', [10,5,15,4,6,20,9])
print (a)
b = arr.array('i')
for i in range(len(a)):
if a[i]%2 == 0:
b.append(a[i])
print ("Even numbers:", b)
It will produce the following output −
array('i', [10, 5, 15, 4, 6, 20, 9])
Even numbers: array('i', [10, 4, 6, 20])
Pseudocode:
DECLARE a : ARRAY[1:7] OF INTEGER
a ← [10, 5, 15, 4, 6, 20, 9]
OUTPUT a
DECLARE b : ARRAY OF INTEGER
b ← []
FOR i ← 1 TO LEN(a)
IF a[i] MOD 2 = 0 THEN b.APPEND(a[i])
ENDIF
NEXT i
OUTPUT "Even numbers:", b
MR. FAZLE MALIK
PHNO:03334732544
33
Paper-2 /4 Arrays
Computer Science
Example 3
Python program to find the average of all numbers in a Python array −
Open Compiler
import array as arr
a = arr.array('i', [10,5,15,4,6,20,9])
print (a)
s=0
for i in range(len(a)):
s+=a[i]
avg = s/len(a)
print ("Average:", avg)
# Using sum() function
avg = sum(a)/len(a)
print ("Average:", avg)
It will produce the following output −
array('i', [10, 5, 15, 4, 6, 20, 9])
Average: 9.857142857142858
Average: 9.857142857142858
AD
Pseudocode:
DECLARE a : ARRAY[1:7] OF INTEGER
a ← [10, 5, 15, 4, 6, 20, 9]
OUTPUT a
DECLARE s : INTEGER
s←0
FOR i ← 1 TO LEN(a)
s ← s + a[i]
NEXT i
MR. FAZLE MALIK
PHNO:03334732544
34
Paper-2 /4 Arrays
Computer Science
DECLARE avg : REAL
avg ← s / LEN(a)
OUTPUT "Average:", avg
// Using SUM function
avg ← SUM(a) / LEN(a)
OUTPUT "Average:", avg
Python: Array Exercises, Practice, Solution
Python Array [24 exercises with solution]
Python array module defines an object type which can compactly represent an
array of basic values: characters, integers, floating point numbers. Arrays are
sequence types and behave very much like lists, except that the type of objects
stored in them is constrained.
1. Write a Python program to create an array of 5 integers and display the array
items. Access individual elements through indexes.
Sample Output:
1
3
5
7
9
Access first three items individually
1
3
5
2. Write a Python program to append a new item to the end of the array.
Sample Output:
Original array: array('i', [1, 3, 5, 7, 9])
Append 11 at the end of the array:
New array: array('i', [1, 3, 5, 7, 9, 11])
MR. FAZLE MALIK
PHNO:03334732544
35
Paper-2 /4 Arrays
Computer Science
3. Write a Python program to reverse the order of the items in the array.
Sample Output
Original array: array('i', [1, 3, 5, 3, 7, 1, 9, 3])
Reverse the order of the items:
array('i', [3, 9, 1, 7, 3, 5, 3, 1])
4. Write a Python program to get the length in bytes of one array item in the
internal representation.
Sample Output:
Original array: array('i', [1, 3, 5, 7, 9])
Length in bytes of one array item: 4
5. Write a Python program to get the current memory address and the length in
elements of the buffer used to hold an array's contents. Also, find the size of the
memory buffer in bytes.
Sample Output:
Original array: array('i', [1, 3, 5, 7, 9])
Current memory address and the length in elements of the buffer:
(139741883429512, 5)
The size of the memory buffer in bytes: 20
6. Write a Python program to get the number of occurrences of a specified
element in an array.
Sample Output:
Original array: array('i', [1, 3, 5, 3, 7, 9, 3])
Number of occurrences of the number 3 in the said array: 3
7. Write a Python program to append items from inerrable to the end of the array.
Sample Output:
Original array: array('i', [1, 3, 5, 7, 9])
Extended array: array('i', [1, 3, 5, 7, 9, 1, 3, 5, 7, 9])
MR. FAZLE MALIK
PHNO:03334732544
36
Paper-2 /4 Arrays
Computer Science
8. Write a Python program to convert an array to an array of machine values and
return the bytes representation.
Sample Output:
Bytes to String:
b'w3resource'
9. Write a Python program to append items to a specified list.
Sample Output:
Items in the list: [1, 2, 6, -8]
Append items from the list:
Items in the array: array('i', [1, 2, 6, -8])
10. Write a Python program to insert a newly created item before the second
element in an existing array.
Sample Output:
Original array: array('i', [1, 3, 5, 7, 9])
Insert new value 4 before 3:
New array: array('i', [1, 4, 3, 5, 7, 9])
11. Write a Python program to remove a specified item using the index of an
array.
Sample Output:
Original array: array('i', [1, 3, 5, 7, 9])
Remove the third item form the array:
New array: array('i', [1, 3, 7, 9])
12. Write a Python program to remove the first occurrence of a specified element
from an array.
Sample Output:
Original array: array('i', [1, 3, 5, 3, 7, 1, 9, 3])
Remove the first occurrence of 3 from the said array:
MR. FAZLE MALIK
PHNO:03334732544
37
Paper-2 /4 Arrays
Computer Science
New array: array('i', [1, 5, 3, 7, 1, 9, 3])
13. Write a Python program to convert an array to an ordinary list with the same
items.
Original array: array('i', [1, 3, 5, 3, 7, 1, 9, 3])
Convert the said array to an ordinary list with the same items:
[1, 3, 5, 3, 7, 1, 9, 3]
14. Write a Python program to find out if a given array of integers contains any
duplicate elements. Return true if any value appears at least twice in the array,
and return false if every element is distinct.
Sample Output:
False
True
True
15. Write a Python program to find the first duplicate element in a given array of
integers. Return -1 if there are no such elements.
Sample Output:
4
-1
1
16. Write a Python program to check whether it follows the sequence given in the
patterns array.
Pattern example:
For color1 = ["red", "green", "green"] and patterns = ["a", "b", "b"]
the output should be samePatterns(color1, patterns) = true;
For color2 = ["red", "green", "greenn"] and patterns = ["a", "b", "b"]
the output should be samePatterns (strings, color2) = false.
MR. FAZLE MALIK
PHNO:03334732544
38
Paper-2 /4 Arrays
Computer Science
17. Write a Python program to find a pair with the highest product from a given
array of integers.
Original array: [1, 2, 3, 4, 7, 0, 8, 4]
Maximum product pair is: (7, 8)
Original array: [0, -1, -2, -4, 5, 0, -6]
Maximum product pair is: (-4, -6)
18. Write a Python program to create an array of six integers. Print all members
of the array.
Sample Output:
10
20
30
40
50
60
19. Write a Python program to get array buffer information.
Sample Output:
Array buffer start address in memory and number of elements.
(140023105054240, 2)
20. Write a Python program to get the length of an array.
Sample Output:
Length of the array is:
5
21. Write a Python program to get the array size of types unsigned integer and
float.
Sample Output:
4
MR. FAZLE MALIK
PHNO:03334732544
39
Paper-2 /4 Arrays
Computer Science
4
22. Write a Python program that reads a string and interprets it as an array of
machine values.
Sample Output:
array1: array('i', [7, 8, 9, 10])
Bytes: b'0700000008000000090000000a000000'
array2: array('i', [7, 8, 9, 10])
23. Write a Python program that removes all duplicate elements from an array
and returns a new array.
Sample Output:
Original array: 1 3 5 1 3 7 9
After removing duplicate elements from the said array: 1 3 5 7 9
Original array: 2 4 2 6 4 8
After removing duplicate elements from the said array: 2 4 6 8
24. Write a Python program to find the missing number in a given array of
numbers between 10 and 20.
Sample Output:
Original array: 10 11 12 13 14 16 17 18 19 20
Missing number in the said array (10-20): 15
Original array: 10 11 12 13 14 15 16 17 18 19
Missing number in the said array (10-20): 20
Exercise Programs



Python program find difference between each number in the array and the
average of all numbers
Python program to convert a string in an array
Python program to split an array in two and store even numbers in one
array and odd numbers in the other.
MR. FAZLE MALIK
PHNO:03334732544
40
Paper-2 /4 Arrays


Computer Science
Python program to perform insertion sort on an array.
Python program to store the Unicode value of each character in the given
array.
MR. FAZLE MALIK
PHNO:03334732544
41
Download