0% found this document useful (0 votes)
20 views21 pages

Module 3.2.5

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

Module 3.2.5

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

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

ALGORITHMIC THINKING WITH PYTHON

Prof. Sarju S
21 November 2024
Module 3

Page 2
Module 3

► SELECTION AND ITERATION USING PYTHON:- if-else, elif, for loop, range, while loop.

► SEQUENCE DATA TYPES IN PYTHON - list, tuple, set, strings, dictionary, Creating and
using Arrays in Python (using Numpy library).

► DECOMPOSITION AND MODULARIZATION* :- Problem decomposition as a strategy for


solving complex problems, Modularization, Motivation for modularization, Defining and
using functions in Python, Functions with multiple return values

Page 3 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
The numpy package and arrays

Page 4
Introduction to NumPy

► NumPy (Numerical Python) is an open-source Python library.


► It is mainly used for:
► Performing mathematical operations on large datasets.
► Working with multi-dimensional arrays and matrices.
► Every element of an array must be the same type.

► Importing NumPy
import numpy as np

► Typing numpy repeatedly can be inconvenient, especially in large programs.


► The alias np is shorter and makes the code cleaner and easier to read.

Page 5 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
What is an “array”?

► An array is a structure for storing and retrieving data.


► We often talk about an array as if it were a grid in space, with each cell storing one element
of the data.
► If each element of the data were a number, we might visualize a “one-dimensional” array
like a list:

► A two-dimensional array would be like a table:

Page 6 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
What is an “array”?

► Most NumPy arrays have some restrictions.


► All elements of the array must be of the same type of data.
► Once created, the total size of the array can’t change.
► The shape must be “rectangular”, not “jagged”; e.g., each row of a two-dimensional array must have
the same number of columns.

Page 7 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Creating arrays

► To create an array, you use the array() method of numpy package as shown below:

>>> import numpy as np


>>> arr = np.array([1, 2, 3, 4, 5, 6])
>>> print(arr)
[1 2 3 4 5 6]

► You can also create matrices (two-dimensional arrays) with array() method:

>>> mat = np.array([[1, 2, 3], [4, 5, 6]])


>>> print(mat)
[[1 2 3]
[4 5 6]]

Page 8 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Creating arrays

► To know the dimensions of an array, you use the ndim attribute in NumPy. See below:

>>> arr = np.array([1, 2, 3, 4, 5])


>>> print(arr.ndim)
1
>>> mat = np.array([[1, 2, 3], [4, 5, 6]])
>>> print(mat.ndim)
2

► To know the size across each dimension, you use the shape attribute:
>>> arr = np.array([1, 2, 3, 4, 5])
>>> mat = np.array([[1, 2, 3], [4, 5, 6]])
>>> print(mat.shape)
(2, 3)
>>> print(arr.shape)
(6,)

Page 9 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Accessing array elements

► Indexing and slicing work the same way with arrays as with other sequences like lists, and
tuples.
>>> arr = np.array([1,2,3,4,5,6])
>>> mat = np.array([[1, 2, 3], [4, 5, 6]])
>>> print(arr[3])
4 >>> print(mat[-1,2])
>>> print(arr[2:5]) 6
[3 4 5] >>> print(mat[-2,-3])
>>> print(mat[1]) 1
[4 5 6] >>> print(arr[-2:])
>>> print(mat[0,2]) [5 6]
3 >>> print(arr[1:5:2])
>>> print(mat[0][2]) [2 4]
3 >>> print(arr[:5:2])
>>> print(arr[-2]) [1 3 5]
5 >>> print(mat[:2:2])
[[1 2 3]]

Page 10 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Traversing through the array

► A 1D array is similar to a list in structure. You can use a for loop to iterate over its elements.

import numpy as np

# Create a 1D array
arr = np.array([10, 20, 30, 40, 50])

print("Traversing a 1D array:")
for element in arr:
print(element)

Page 11 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Traversing through the array

► Traversing a 2D Array: Traverse row by row (outer loop for rows, inner loop for elements in
the row).

# Create a 2D array
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print("Traversing a 2D array row by row:")


for row in arr:
for element in row:
print(element, end=" ")
print() # Newline after each row #Output
Traversing a 2D array row by row:
1 2 3
4 5 6
7 8 9

Page 12 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Changing Array Dimensions in NumPy

► The reshape() function is used to change the shape (dimensions) of an array.


► Rules:
► The total number of elements must remain the same.
► Dimensions should be compatible with the number of elements.

import numpy as np
# Original 1D array
arr = np.array([1, 2, 3, 4, 5, 6])
#output
# Reshape to 2D (2 rows, 3 columns) Reshaped to 2D (2x3):
reshaped_arr = arr.reshape(2, 3) [[1 2 3]
print("Reshaped to 2D (2x3):") [4 5 6]]
print(reshaped_arr)

Page 13 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Changing Array Dimensions in NumPy

► Rules:
► The total number of elements must remain the same.
► Dimensions should be compatible with the number of elements.

import numpy as np
# Original 1D array
arr = np.array([1, 2, 3, 4, 5])

# Reshape to 2D (2 rows, 3 columns)


reshaped_arr = arr.reshape(2, 3)
print("Reshaped to 2D (2x3):")
print(reshaped_arr)

Page 14 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Changing Array Dimensions in NumPy

► Write a Python program to input the number of rows and columns from the user, then
create a rows × columns matrix using NumPy.

https://github.com/sarjus/Algorithemic-Thinking-with-Python-classroom-
exercises/blob/main/matrix-numpy.py

Page 15 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Matrix operations

► NumPy has excellent support for doing most of the matrix operations.

Page 16 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Matrix operations

► NumPy has excellent support for doing most of the matrix operations.

import numpy as np

# Define matrices
#output
matrix1 = np.array([[1, 2], [3, 4]])
Matrix Addition:
matrix2 = np.array([[5, 6], [7, 8]])
[[ 6 8]
[10 12]]
# Matrix addition
addition = np.add(matrix1, matrix2)
print("Matrix Addition:\n", addition)

Page 17 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Matrix operations

► NumPy has excellent support for doing most of the matrix operations.

import numpy as np

# Define matrices
matrix1 = np.array([[1, 2], [3, 4]]) #output
matrix2 = np.array([[5, 6], [7, 8]]) Matrix Subtraction:
[[-4 -4]
# Matrix subtraction [-4 -4]]
subtraction = np.subtract(matrix1, matrix2)
print("\nMatrix Subtraction:\n", subtraction)

Page 18 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Matrix operations

► NumPy has excellent support for doing most of the matrix operations.
import numpy as np

# Define matrices
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])

# Element-wise multiplication
elementwise_multiplication = np.multiply(matrix1, matrix2)
print("\nElement-wise Multiplication:\n", elementwise_multiplication)

#output
Element-wise Multiplication:
[[ 5 12]
[21 32]]

Page 19 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Matrix operations

► NumPy has excellent support for doing most of the matrix operations.

import numpy as np

# Define matrices
matrix1 = np.array([[1, 2], [3, 4]]) #output
matrix2 = np.array([[5, 6], [7, 8]]) Matrix Transpose:
[[1 3]
# Matrix transpose [2 4]]
transpose = np.transpose(matrix1)
print("\nMatrix Transpose:\n", transpose)

Page 20 Prof. Sarju S, Department of Computer Science and Engineering, SJCET Palai
Thank You

Prof. Sarju S
Department of Computer Science and Engineering
St. Joseph’s College of Engineering and Technology, Palai (Autonomous)
[email protected]

Page 21 Disclaimer - This document contains images/texts from various internet sources. Copyright belongs to the respective content creators.
Document is compiled exclusively for study purpose and shall not be used for commercial purpose.

You might also like