Uploaded by Zaid Iftikhar

CV Lab 2

advertisement
Department of Electrical Engineering
Faculty Member:
Dated: 22/09/2023
Course/Section:
Semester: 7
CS-477 Computer Vision
Lab#2: Data Structures and NumPy
Name
Reg No.
PLO4CLO4
Investigati
on
PLO5-CLO5
PLO8-CLO6
PLO9-CLO7
Modern Tool
Usage
Ethics
Individual and
Team Work
(5 marks)
(5 marks)
(5 marks)
(5 marks)
Lab#2: Data structures and NumPy
Objectives: The following are the main objectives of this lab:
Implement data structures such as lists and dictionaries in python
Create, alter and loop through lists
Use slicing to access range of items in a list
Utilize various list methods such as append, insert, extend, remove, pop
etc
• Implement 2-D lists.
• Create and implement a dictionary.
• Introduction to numpy
•
•
•
•
Lab Instructions
 This lab activity comprises of following parts: Lab Exercises, and Post-Lab
Viva/Quiz session.
 The lab report shall be uploaded on LMS.
 Only those tasks that are completed during the allocated lab time will be credited to
the students. Students are however encouraged to practice on their own in spare time
for enhancing their skills.
Lab Report Instructions
All questions should be answered precisely to get maximum credit. Lab report must ensure
following items:
 Lab objectives
 Python codes
 Results (graphs/tables) duly commented and discussed
 Conclusion
Theory
Data structures are an important part of python. The 4 main data structures are
lists, tuples, sets and dictionaries. Lists are most commonly used so they will be
the major part of the lab tasks. Dictionaries are also used at times. Tuples and
sets are very similar to lists and are not very commonly used in robotics. In this
lab, mainly lists will be considered. To write python scripts (.py files), the
SublimeText application will be used which is a text editor with syntax
highlighting. Once the code is written, the script is saved and then executed by
using the Linux terminal.
The terminal commands are given as:
cd <directory>
cd..
pwd
ls
python <script.py>
change directory
go back to previous directory
print the current directory
list the contents of the current directory
execute python script
A brief summary of the list functions in python is provided below. (For more
details, check the slides for this lab)
append(I)
insert(i, I)
extend(L)
remove(I)
pop(i)
count(I)
index(I)
reverse
append item I to the end of the list
insert item I at i position of the list
extend/concatenate a second list L
remove a specified item I from a list
remove item at specific index i in the list
return total number of a specific item I from a list
return index of first occurrence of a specific item I
reverse the items of the list
Lab Objectives
The objectives of this lab are to familiarize students with the basics and
fundamental commands and syntax of python. This will allow students to build
their basics for the future lab assignments related to computer vision. In the last
task of the lab, students will also be introduced to the basics of numpy and its array
structures which will be used later in the computer vision related lab assignments.
Lab Task 1
[1]
Create a simple list containing the characters of the word: MANIPULATOR.
Loop through the list and display each character on a new line.
Code
L = ["M","A","N","I", "P","U","L","A","T","O","R"]
for i in L:
print(i)
Results
Lab Task 2
[1]
Write a program which first prompts the user for an integer which will be
the size of a list. Then, the program must repeatedly prompt the user to
input the items of the list. Each item is to be added with the append
function. The inputs continue until the number of items reach the size of
the list. The final list is then printed. The syntax for making an empty list
and appending function are given below:
my_list = [ ]
my_list.append(item)
Code
n =
n =
L =
for
input("Please enter the size of the list: ")
int(n)
[]
i in range(0,n):
L.append(input("Please enter something to add to list: "))
for item in L:
print(item)
Results
Lab Task 3
[1]
Write a function that takes in a list input and returns true if the items of the
list make a palindrome. A palindrome is a word/number that is written the
same way forward and backward. Examples of palindromes include
“radar”, “level”, “5445”, “8395938”, “racecar”. To use a list in a function, use
the following syntax:
def my_function(my_list):
statement1
statement2
Code
def palindrome_check(list): #function to check palindromes
flag = True #by default returns true
for i in range(0,int(len(list)/2)):
if list[i] != list[len(list)-i-1]:
flag = False
return flag
def main():
list = ["Z","A","I","D","D","I","A","Z"]
print("Palindrome Check for Z A I D D I A Z")
print(palindrome_check(list))
list = ["Z","A","I","D","U","I","A","Z"]
print("Palindrome Check for Z A I D U I A Z")
print(palindrome_check(list))
Results
Lab Task 4
[1]
Write a program that repeatedly prompts the user for input. The user will
keep entering numbers which are added to a list. Each time a number is
added to the list, it must be placed in such a way that the list items are
always in ascending order. Each time a number is input, the list is to be
printed showing the newly added number. This continues until the word
“done” is input at which point the prompts will stop. The final list is then
displayed. Do NOT use any inbuilt sorting function for this task.
Code
numbers = []
num = input("Please enter a number or write done to exit: ")
while (num != "done"):
num = int(num)
index = 0
while index < len(numbers) and num>numbers[index]:
index = index +1
numbers.insert(index,num)
print("Updated list is: ", numbers)
num = input("Please enter a number or write done to exit: ")
print("The final list is: ", numbers)
Results
Lab Task 5
[1]
In this task, you will implement the Selection Sort algorithm using lists. A
selection sort searches a list looking for the smallest element. Then, the
smallest element is swapped with the first element of the list. The process
is repeated for the sub-list beginning with the second element of the list.
Each pass of the list results in one element being placed in its proper
location. When the sub-list being processed contains one element, the list
is sorted. Create a function which takes a list as input and then implements
the selection sort on it. You need to print the list each time a swap is made.
Code
def selection_sort(list): #function to sort the list
start_pos = 0
for i in range(start_pos,int(len(list))):#outer loop
smallest_index = i
for j in range(start_pos+1, int(len(list))):#inner loop that begins from the
next item after each iteration
if list[j] <= list[smallest_index]:
smallest_index = j
list.insert(start_pos,list[smallest_index])#inserts the smallest number in
its right place
list.pop(smallest_index+1)#deletes the smallest number from its previous
place
start_pos = start_pos + 1#increments starting position
print(list)
return list
def main():
list = ["D","A","C","K","L","M","Q","E"]
print("List is DACKLMQE")
sorted_list = []
sorted_list = selection_sort(list)
print("The sorted list after completion is: ", sorted_list)
Results
Lab Task 6 ________________________________________________________________________________
Use the np.array function to define two matrices of size 3x3. Place numerical
elements of your choice in the matrices. Write code to perform the following:






Print the arrays
Compute the sum of the matrices
Compute the difference of the matrices
Compute the element-wise product of the matrices
Compute the element-wise division of the matrices
Compute the matrix multiplication of the matrices
Code
import numpy as np
def main():
array1 = np.array([1,2,3,4,5,6,7,8,9])
array1 = array1.reshape(3,3)
array2 = np.array([10, 12, 31, 2, 7, 1, 4, 8, 3])
array2 = array2.reshape(3, 3)
print("array 1: \n", array1)
print("array 2: \n", array2)
print("Sum of the two arrays: \n", array1+array2)
print("Difference of the two arrays: \n", np.subtract(array1, array2))
print("Element wise product of the two arrays: \n", np.multiply(array1, array2))
print("element wise division of the two arrays: \n", np.divide(array1, array2))
print("Matrix multiplication of the two matrices: \n", np.dot(array1, array2))
Results
Conclusion:
This lab was very important in teaching the python key concepts to students.
Students were given different problems to solve while using the basic syntax of
python. This lab provided us with the fundamental concepts that are to be used
later in the lab assignments.
Download