Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Sunday, 6 October 2024

Python Practical book for First Year B.Sc. Computer Science

Python Practical Book for Mathematics

Python Practical Book for Mathematics

First Year B.Sc Computer Science

Index

  • Assignment 1: Introduction to Python
  • Assignment 2: Python Strings
  • Assignment 3: Python List and Tuple
  • Assignment 4: Python Set
  • Assignment 5: Python Dictionary
  • Assignment 6: Decision Making Statements
  • Assignment 7: SymPy for Basic Matrix Operations
  • Assignment 8: SymPy for Advanced Matrix Operations
  • Assignment 9: Determinants and Rank of Matrix using SymPy
  • Assignment 10: Matrix Inversion using SymPy
  • Assignment 11: Triangular Matrix and LU Decomposition using SymPy
  • Assignment 12: Solving Systems of Linear Equations using SymPy

Assignment 1: Introduction to Python

1.1 Installation of Python

Python is a popular programming language known for its simplicity and readability. You can download and install Python from the official website: python.org. Follow these steps to install Python on your machine:

  • For Windows: Download the installer and follow the instructions.
  • For Linux/MacOS: Use your package manager to install Python, e.g., sudo apt-get install python3 for Ubuntu.
# Check Python version in the terminal:
python --version

1.2 Values and Types: int, float, str, etc.

In Python, every value has a type. Some basic types include:

  • int: Integer values, e.g., 5, 10, -3
  • float: Floating-point numbers, e.g., 3.14, 0.1
  • str: Strings of characters, e.g., "Hello", "Python"
age = 20         # Integer
pi = 3.14        # Float
name = "Alice"   # String

print(type(age))    # 
print(type(pi))     # 
print(type(name))   # 

1.3 Variables: Assignment, Printing Variable Values, Types of Variables

Variables in Python are dynamically typed, which means you don't need to declare their type explicitly. You assign a value to a variable using the = operator.

x = 5
y = "Hello"
z = 3.14

print(x)    # Outputs: 5
print(y)    # Outputs: Hello
print(z)    # Outputs: 3.14

1.4 Boolean and Logical Operators

Boolean values in Python can be True or False. Logical operators include and, or, and not.

a = True
b = False

print(a and b)  # False
print(a or b)   # True
print(not a)    # False

1.5 Mathematical Functions from math and cmath Modules

Python has built-in mathematical functions through the math module (for real numbers) and cmath (for complex numbers).

import math
import cmath

# Basic math functions
print(math.sqrt(16))  # Outputs: 4.0
print(math.factorial(5))  # Outputs: 120

z = 1 + 2j
print(cmath.sqrt(z))  # Complex square root of z

Assignment 2: Python Strings

2.1 Accessing Values in Strings

Strings are sequences of characters. You can access individual characters using indexing, starting from 0.

name = "Python"
print(name[0])  # Outputs: P
print(name[1])  # Outputs: y

2.2 Updating Strings

Strings in Python are immutable, but you can create a new string by concatenating strings.

greeting = "Hello"
greeting += " World"  # Concatenation
print(greeting)       # Outputs: Hello World

2.3 String Special Operators

Strings support several operators like concatenation (+) and repetition (*).

# Concatenation
s1 = "Hello"
s2 = "Python"
result = s1 + " " + s2
print(result)  # Outputs: Hello Python

# Repetition
print(s1 * 3)  # Outputs: HelloHelloHello

2.4 Concatenation and 2.5 Repetition

We can concatenate strings with the + operator and repeat them with the * operator.

# Concatenation example
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)  # Outputs: John Doe

# Repetition example
echo = "echo " * 3
print(echo)  # Outputs: echo echo echo 

Assignment 3: Python List and Tuple

3.1 Accessing Values in Lists and Tuples

Lists and tuples are collections that hold multiple items. You can access elements using indexing.

fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # Outputs: apple

days = ("Mon", "Tue", "Wed")
print(days[1])  # Outputs: Tue

3.2 Updating Lists

Lists are mutable, which means you can change their elements after they are created. Tuples, however, are immutable and cannot be changed.

numbers = [1, 2, 3]
numbers[0] = 10
print(numbers)  # Outputs: [10, 2, 3]

3.3 Deleting Elements

Lists allow you to delete elements using del, remove(), or pop().

numbers = [1, 2, 3, 4]
del numbers[0]  # Deletes the first element
print(numbers)  # Outputs: [2, 3, 4]

Assignment 4: Python Set

4.1 Creating a Set

A set is an unordered collection of unique elements. You can create a set using curly braces {} or the set() function.

numbers = {1, 2, 3, 4}
print(numbers)

letters = set("abcde")
print(letters)

4.2 Changing a Set

Sets are mutable, so you can add or remove elements using methods like add() or discard().

numbers.add(5)
print(numbers)  # Outputs: {1, 2, 3, 4, 5}

4.3 Removing Elements from a Set

Sets in Python allow for the removal of elements using methods like remove(),
discard(), and pop(). The difference is that remove() raises an error
if the element doesn't exist, while discard() does not.

my_set = {1, 2, 3, 4, 5}
my_set.remove(3)   # Removes the element 3
print(my_set)      # Outputs: {1, 2, 4, 5}

my_set.discard(5)  # Discards the element 5
print(my_set)      # Outputs: {1, 2, 4}

# Using pop to remove a random element
removed_element = my_set.pop()
print(f"Removed: {removed_element}")   # Outputs: Removed: 1 (or another element)
print(my_set)      # Remaining elements

4.4 Python Set Operations

Python sets support common mathematical operations like union,
intersection, difference, and symmetric difference. These can be performed using
operators or set methods:

  • Union (|): Combines two sets, removing duplicates.
  • Intersection (&): Finds common elements between two sets.
  • Difference (-): Finds elements present in the first set but not the second.
  • Symmetric Difference (^): Finds elements present in either set but not both.
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

# Union
print(A | B)    # Outputs: {1, 2, 3, 4, 5, 6}

# Intersection
print(A & B)    # Outputs: {3, 4}

# Difference
print(A - B)    # Outputs: {1, 2}
# Symmetric Difference
print(A ^ B)    # Outputs: {1, 2, 5, 6}

4.5 Built-in Functions with Set

Python provides various built-in functions that work with sets:

  • len(): Returns the number of elements in a set.
  • max() and min(): Returns the largest and smallest elements, respectively.
  • sum(): Returns the sum of elements in a set (for numeric sets).
  • sorted(): Returns a sorted list of the set’s elements.
my_set = {7, 2, 10, 4}
print(len(my_set))  # Outputs: 4
print(max(my_set))  # Outputs: 10
print(min(my_set))  # Outputs: 2
print(sum(my_set))  # Outputs: 23
print(sorted(my_set))  # Outputs: [2, 4, 7, 10]

Assignment 5: Python Dictionary

5.1 Creating a Dictionary

Dictionaries store key-value pairs in Python. You can create a dictionary using
curly braces {} and colons to separate keys from values.

my_dict = {"name": "Alice", "age": 25, "city": "New York"}
print(my_dict)  # Outputs: {'name': 'Alice', 'age': 25, 'city': 'New York'}

5.2 Changing a Dictionary in Python

Dictionaries are mutable, meaning you can add, modify, or remove key-value pairs after the dictionary has been created.

# Adding or updating a key-value pair
my_dict["age"] = 30
my_dict["country"] = "USA"
print(my_dict)  # Outputs: {'name': 'Alice', 'age': 30, 'city': 'New York', 'country': 'USA'}

5.3 Removing Elements from a Dictionary

You can remove elements from a dictionary using methods like del, pop(), and clear():

my_dict = {"name": "Alice", "age": 25, "city": "New York"}

# Removing a specific key-value pair
del my_dict["age"]
print(my_dict)  # Outputs: {'name': 'Alice', 'city': 'New York'}

# Using pop to remove a key and return its value
city = my_dict.pop("city")
print(city)      # Outputs: New York
print(my_dict)   # Outputs: {'name': 'Alice'}

5.4 Python Dictionary Operations

  • keys(): Returns a view object of all the keys in the dictionary.
  • values(): Returns a view object of all the values.
  • items(): Returns a view object of all key-value pairs.
my_dict = {"name": "Alice", "age": 25, "city": "New York"}

# Getting keys, values, and items
print(my_dict.keys())   # Outputs: dict_keys(['name', 'age', 'city'])
print(my_dict.values()) # Outputs: dict_values(['Alice', 25, 'New York'])
print(my_dict.items())  # Outputs: dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])

5.5 Built-in Functions with Dictionary

Some useful built-in functions that work with dictionaries include:

  • len(): Returns the number of key-value pairs in the dictionary.
  • dict(): Creates a dictionary from another mapping type.
  • zip(): Combines two sequences into a dictionary.
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
people = dict(zip(names, ages))
print(people)  # Outputs: {'Alice': 25, 'Bob': 30, 'Charlie': 35}

Assignment 6: Decision Making Statements

6.1 IF statement

The if statement is used to execute a block of code only if a certain condition is true.

x = 10
if x > 5:
    print("x is greater than 5")  # This will be executed

6.2 IF...ELIF...ELSE Statements

If you want to test multiple conditions, you can use elif (else if) and else blocks.

x = 10
if x > 15:
    print("x is greater than 15")
elif x > 5:
    print("x is greater than 5 but less than or equal to 15")  # This will be executed
else:
    print("x is less than or equal to 5")

6.3 Nested IF Statements

It's possible to nest if statements inside one another to check multiple conditions.

x = 10
y = 20

if x > 5:
    if y > 15:
        print("x is greater than 5 and y is greater than 15")  # This will be executed

6.4 While Loop

A while loop repeatedly executes a block of code as long as a condition is true.

i = 1
while i <= 5:
    print(i)
    i += 1   # Increment i

6.5 For Loop

A for loop is used to iterate over a sequence (like a list, tuple, or string).

for i in range(5):
    print(i)

Assignment 7: Using SymPy for Basic Operations on Matrices

7.1 Addition, Subtraction, Multiplication, Power

SymPy allows for basic matrix operations like addition, subtraction, multiplication, and exponentiation.

from sympy import Matrix

# Creating matrices
A = Matrix([[1, 2], [3, 4]])
B = Matrix([[5, 6], [7, 8]])

# Addition
C = A + B
print(C)  # Outputs the matrix result of A + B

# Subtraction
D = A - B
print(D)  # Outputs the matrix result of A - B

# Multiplication
E = A * B
print(E)  # Outputs the matrix result of A * B

# Power
F = A ** 2
print(F)  # Outputs the matrix result of A squared

7.2 Accessing Elements, Rows, Columns of a Matrix

Individual elements, rows, and columns of a matrix can be accessed using SymPy’s indexing methods.

element = A[0, 1]   # Access element at row 0, column 1
print(element)        # Outputs: 2

row = A.row(1)        # Access row 1
print(row)            # Outputs: [3, 4]

column = A.col(0)     # Access column 0
print(column)         # Outputs: [1, 3]

7.3 Creating Some Standard Matrices

SymPy provides functions for creating standard matrices such as
zero matrices, identity matrices, and diagonal matrices.

from sympy import zeros, eye, diag

zero_matrix = zeros(2, 3)   # 2x3 zero matrix
identity_matrix = eye(3)    # 3x3 identity matrix
diagonal_matrix = diag(1, 2, 3)   # Diagonal matrix

print(zero_matrix)
print(identity_matrix)
print(diagonal_matrix)

Assignment 8: Using SymPy for Operations on Matrices

8.1 Inserting an Element into a Matrix

In SymPy, although matrices are immutable, you can create a new matrix by
replacing elements or inserting them. To insert a new element into a row or
column, you may have to rebuild the matrix using concatenation or element
replacement methods.

from sympy import Matrix

# Create a matrix
A = Matrix([[1, 2], [3, 4]])

# Rebuilding the matrix by inserting an element at position (1, 1)
A_new = A.row_insert(1, Matrix([[5, 6]]))
print(A_new)  # Outputs the new matrix with inserted row

8.2 Inserting a Matrix into Another Matrix

You can insert a submatrix into another matrix by using methods
like row_insert or col_insert for adding rows or columns.

from sympy import Matrix

A = Matrix([[1, 2], [3, 4]])
B = Matrix([[5, 6]])

# Insert matrix B as a new row in matrix A
A_new = A.row_insert(1, B)
print(A_new)  # Outputs the new matrix

8.3 Deleting a Row or Column from a Matrix

You can delete a row or column from a matrix by creating a new matrix without that row or column.

from sympy import Matrix

A = Matrix([[1, 2], [3, 4], [5, 6]])

# Delete the second row
A_new = A.row_del(1)
print(A_new)  # Outputs the matrix after deleting row 1

8.4 Elementary Row Operations

Elementary row operations include row swapping, row multiplication,
and row addition. These operations are useful for manipulating matrices,
especially in solving systems of equations.

from sympy import Matrix

A = Matrix([[1, 2], [3, 4]])

# Swap row 0 and row 1
A_new = A.elementary_row_op('n<->m', n=0, m=1)
print(A_new)  # Outputs: Matrix([[3, 4], [1, 2]])

# Multiply row 0 by 2
A_new = A.elementary_row_op('n->kn', n=0, k=2)
print(A_new)  # Outputs: Matrix([[2, 4], [3, 4]])

# Add row 0 to row 1
A_new = A.elementary_row_op('n->n+km', n=1, m=0, k=1)
print(A_new)  # Outputs: Matrix([[1, 2], [4, 6]])

Assignment 9: Using SymPy to Obtain Matrix Properties

9.1 Determinant of a Matrix

The determinant of a matrix is a scalar value that can be computed using
the det() method. It is crucial in solving linear systems,
finding the inverse of matrices, and understanding matrix properties.

from sympy import Matrix

A = Matrix([[1, 2], [3, 4]])

# Calculate determinant
det_A = A.det()
print(det_A)  # Outputs: -2

9.2 Rank of a Matrix

The rank of a matrix is the maximum number of linearly independent row
or column vectors. You can compute it using the rank() method in SymPy.

rank_A = A.rank()
print(rank_A)  # Outputs: 2

9.3 Transpose of a Matrix

The transpose of a matrix is achieved by swapping its rows and columns.
This operation is useful in many mathematical contexts.

transpose_A = A.T
print(transpose_A)  # Outputs the transpose of matrix A

9.4 Reduced Row Echelon Form of a Matrix

The reduced row echelon form (RREF) of a matrix is used in solving systems of
linear equations. It transforms the matrix into a form where back substitution
can be applied easily.

rref_A, pivots = A.rref()
print(rref_A)  # Outputs the RREF of matrix A

Assignment 10: Using SymPy for Matrix Inverses and Related Operations

10.1 The Inverse of a Matrix

You can calculate the inverse of a matrix using the inv() method.
The matrix must be square and have a non-zero determinant to be invertible.

inverse_A = A.inv()
print(inverse_A)  # Outputs the inverse of matrix A

10.2 Inverse of a Matrix by Row Reduction

The inverse of a matrix can also be computed using row reduction techniques,
where elementary row operations are applied until the matrix is reduced to the identity matrix.

# SymPy allows you to apply row reduction techniques to find the inverse
inverse_A = A.inv(method="GE")
print(inverse_A)

10.3 Minor and Cofactors of a Matrix

The minor of an element is the determinant of the matrix obtained by deleting
the element's row and column. The cofactor includes the minor along with a sign.

# Minor of element at (0, 0)
minor_A = A.minor_submatrix(0, 0).det()
print(minor_A)  # Outputs the minor of element A[0, 0]

10.4 Inverse of a Matrix by Adjoint Method

The adjoint method is another way to compute the inverse of a matrix.
It involves computing the cofactor matrix, transposing it, and dividing
by the determinant.

adjoint_A = A.adjugate()
inverse_A = adjoint_A / A.det()
print(inverse_A)  # Outputs the inverse using the adjoint method

Assignment 11: Using SymPy for LU Decomposition

11.1 Lower Triangular Matrix

A lower triangular matrix is a matrix where all the entries above the
diagonal are zero. SymPy can compute this using LU decomposition.

L, U, _ = A.LUdecomposition()
print(L)  # Outputs the lower triangular matrix L

11.2 Upper Triangular Matrix

An upper triangular matrix is one where all the entries below the diagonal
are zero. SymPy provides this using LU decomposition as well.

print(U)  # Outputs the upper triangular matrix U

11.3 LU Decomposition of a Matrix

LU decomposition expresses a matrix as the product of a lower triangular matrix
and an upper triangular matrix. This is useful in solving linear systems and computing matrix inverses.

# The matrices L and U are already computed in the LUdecomposition step
print(L * U)  # Rebuilds the original matrix A

Assignment 12: Using SymPy to Solve Systems of Linear Equations

12.1 Cramer's Rule

Cramer’s rule is used to solve a system of linear equations using determinants.
It works for systems where the number of equations equals the number of unknowns.

from sympy import symbols

x, y = symbols('x y')
eq1 = 2*x + y - 1
eq2 = x - 2*y - 3

sol = A.solve((x, y))
print(sol)  # Outputs the solution using Cramer's rule

12.2 Gauss Elimination Method

Gauss elimination transforms a system of linear equations into an
upper triangular matrix, which is then solved using back substitution.

# Use row reduction (RREF) to solve the system
rref_A, pivots = A.rref()
print(rref_A)

12.3 Gauss-Jordan Method

Gauss-Jordan elimination extends the Gauss method by reducing the matrix to its
reduced row echelon form (RREF), allowing direct solutions without back substitution.

rref_A, pivots = A.rref()
print(rref_A)  # Outputs the RREF, which can be directly solved

12.4 LU Decomposition Method for Solving Systems

LU decomposition can also be used to solve systems of linear equations
by solving two triangular systems: one for the lower

Featured Post

Mathematics Exams in India for various level.

Mathematics Exams for Indian Students Mathematics Exams for Indian Students School Level Nation...