Showing posts with label lab. Show all posts
Showing posts with label lab. Show all posts

Pandas - dataframe

 # Pandas - dataframe


import pandas as pd


data = {

  "Countries": ["India","China","Spain","Italy","USA", "UK", "France","Australia"],

  "Capital": ["New Delhi", "Beijing", "Madrid", "Rome", "Washington DC", "London", "Paris", "Canberra"],

  "Population (Million)":[1380,1439,46,60,331,67,65,25]

}


#load data into a DataFrame object:

df = pd.DataFrame(data)

print("Unsorted  data")

print(df) 


# Sorting data by column

sorted_df = df.sort_values(by='Population (Million)')

print("Data sorted by population")

print(sorted_df)



# Printing selected columns

df_SelectedCols = pd.DataFrame(data, columns=["Countries","Population (Million)"])

print("Printing selected columns")

print(df_SelectedCols)


"""

Sample output


>python Pandas1.py


Unsorted  data

   Countries        Capital  Population (Million)

0      India      New Delhi                  1380

1      China        Beijing                  1439

2      Spain         Madrid                    46

3      Italy           Rome                    60

4        USA  Washington DC                   331

5         UK         London                    67

6     France          Paris                    65

7  Australia       Canberra                    25


Data sorted by population

   Countries        Capital  Population (Million)

7  Australia       Canberra                    25

2      Spain         Madrid                    46

3      Italy           Rome                    60

6     France          Paris                    65

5         UK         London                    67

4        USA  Washington DC                   331

0      India      New Delhi                  1380

1      China        Beijing                  1439


Printing selected columns

   Countries  Population (Million)

0      India                  1380

1      China                  1439

2      Spain                    46

3      Italy                    60

4        USA                   331

5         UK                    67

6     France                    65

7  Australia                    25


"""

Scipy - Square matrix - Determinant, Eigen values and Eigen vectors

 # Scipy - Determinant of a square array

# Scipy - Eigen values and Eigen vectors


#importing the scipy and numpy packages


from scipy import linalg

import numpy as np

import random


# Creating a random 2d array object of size 3 x 3

A = np.random.randint(10, size=(2,2))


# Calculating the determinant of a square matrix

DA = linalg.det(A)


#printing the result array

print("Given square array")

print(A)


print("Determinant of the square array")

print(int(DA))


# Calling the eigen function

eig_val, eig_vect = linalg.eig(A)


# Printing the eigen values

print("Eigen values : ")

print(eig_val)


# Printing the eigen vectors

print("Eigen vectors : ")

print(eig_vect)



"""


Sample output


>python 8_6_scipy2.py

Given square array

[[0 5]

 [2 5]]

 

Determinant of the square array

-10


Eigen values :

[-1.53112887+0.j  6.53112887+0.j]


Eigen vectors :

[[-0.9561723  -0.60788018]

 [ 0.2928046  -0.79402877]]

 

"""


Scipy - Solving linear equations

 # Scipy - solving linear equations 



#importing the scipy and numpy packages


from scipy import linalg

import numpy as np


#Declaring the numpy arrays

a = np.array([[3, 2, 0], [1, -1, 0], [0, 5, 1]])

b = np.array([2, 4, -1])


#Passing the values to the solve function

x = linalg.solve(a, b)


#printing the result array

print(x)


"""


Given input

3x + 2y = 2

x - y = 4

5y + z = -1


Sample output

>python scipy1.py

[ 2. -2.  9.]


"""


Algorithm - Bouncing ball - pygame

Algorithm - Bouncing ball 
  1.     Start the program
  2.     Set screen size and background color.
  3.    Set speed of moving ball.
  4.    Create a graphical window using set_mode()
  5.    Set caption
  6.     Load the ball image and create a rectangle area covering the image
  7.    Use blit() method to copy the pixel color of the ball to the screen
  8.     Set background color of screen and use flip() method to make all images visible.
  9.     Move the ball in specified speed.
  10.    If ball hits the edges of the screen reverse the direction. 
  11.    Create an infinite loop and Repeat steps 9 and 10 until user quits the program
  12.     Stop the program


Algorithm - Simulation of Elliptical Orbit

Algorithm - Simulation of Elliptical orbit
  1.     Start the program
  2.     Set screen size and caption
  3.     Create clock variable
  4.     Set x and y radius of ellipse.
  5.     Starting from degree 0 ending with 360 degrees in increments of 10 degrees  calculate the (x1, y1) coordinates to find a point in the elliptical orbit.
  6.     Convert degree to radians (degree * 2 * math.pi / 360)
  7.     Set background color, draw center circle, ellipse and another smaller circle on the ellipse
  8.     Refresh the screen every 5 clock ticks
  9.     Repeat steps 4 to 8 until user quits the program
  10.     Stop the program


Functions - Selection Sort

# Functions - Selection sort

# Function - Read list of elements
def fn_read(nterms):
    L = []
    for idx in range(0, nterms, 1):
        ele = int(input("Enter element : "))
        L.append(ele)
    return L

# Function - Selection sort
def fn_Selection_Sort(L):
    for idx in range(0, len(L)-1, 1):
        min_ele = min(L[idx:len(L)])
        pos = L.index(min_ele)
        if(pos != idx):   
            L[pos], L[idx]  = L[idx], L[pos]
    return L
   
# Main Program
# Read elements and create list
no_of_terms = int(input("Enter number of terms : "))
L1 = fn_read(no_of_terms)

print("Original list :", L1)
L1 = fn_Selection_Sort(L1)
print("Sorted List :", L1)

Functions - Insertion sort

# Functions - Insertion sort

# Function - Read list of elements
def fn_read(nterms):
    L = []
    for idx in range(0, nterms, 1):
        ele = int(input("Enter element : "))
        L.append(ele)
    return L

# Function - Insertion sort
def fn_Ins_Sort(L):
    for idx in range(1, len(L), 1):
        while( idx>0 and L[idx-1]>L[idx] ):
            L[idx],L[idx-1] = L[idx-1],L[idx]
            idx = idx-1

    return L
   
# Main Program
# Read elements and create list
no_of_terms = int(input("Enter number of terms : "))
L1 = fn_read(no_of_terms)

print("Original list :", L1)
L1 = fn_Ins_Sort(L1)
print("Sorted List :", L1)

Functions - Fibonacci series - Number of terms

# Functions - Fibonacci series - Number of terms

def fn_fib(nterms):
    n1 = -1
    n2 = 1
    for counter in range(0,nterms,1):
        fib = n1 + n2
        print(fib, end = " ")
        n1, n2 = n2, fib

# Main Program

no_of_terms = int(input("Enter number of terms :"))
print("Fibonacci series : ")
fn_fib(no_of_terms)

Functions - Fibonacci series upto limit

# Functions - Fibonacci series upto limit

def fn_fib(el):
    n1 = -1
    n2 = 1
    while(True):
        fib = n1 + n2
       
        if(fib > el):
            return
           
        print(fib, end = " ")

        n1, n2 = n2, fib

# Main Program

end_limit = int(input("Enter ending limit :"))
print("Fibonacci series upto", end_limit)
fn_fib(end_limit)

Functions - Matrix - Transpose of a Matrix

# Functions and Matrix
# Transpose of a Matrix

# Function - Read Matrix
def fn_read(r, c):
    M = []
    print("Enter values of Matrix : ")
    for i in range(0,r,1):
        tmp = []
        for j in range(0,c,1):
            ele = int(input())
            tmp.append(ele)
        M.append(tmp)
    return M

# Function - Display Matrix
def fn_display(M):
    for row in M:
        for ele in row:
            print(ele, end=" ")
        print()

# Function - Transpose
def fn_transpose(MA, r, c):
    M = []
    for i in range(0,c,1):
        tmp = []
        for j in range(0,r,1):
            ele = MA[j][i]
            tmp.append(ele)
        M.append(tmp)
    return M

# Main Program

import sys

Mat_A = []
Mat_Transpose = []

print("Enter number of rows and columns :")
r1 = int(input("Matrix 1 - Row : "))
c1 = int(input("Matrix 1 - Column : "))

# Transpose
Mat_A = fn_read(r1, c1)
       
print("Given Matrix : ")   
fn_display(Mat_A)
   
Mat_Transpose = fn_transpose(Mat_A, r1, c1)
print("Transpose of given matrices : ")
fn_display(Mat_Transpose)   
   

Functions - Matrix - Sum of diagonal elements

# Functions and Matrix
# Matrix Sum of diagonal elements

# Function - Read Matrix
def fn_read(r, c):
    M = []
    print("Enter values of Matrix : ")
    for i in range(0,r,1):
        tmp = []
        for j in range(0,c,1):
            ele = int(input())
            tmp.append(ele)
        M.append(tmp)
    return M

# Function - Display Matrix
def fn_display(M):
    for row in M:
        for ele in row:
            print(ele, end=" ")
        print()

# Function - Sum of diagonal elements
def fn_add(MA, r):
    s = 0
    for i in range(0,r,1):
        s += MA[i][i]
    return s

# Main Program

import sys

Mat_A = []

print("Enter number of rows and columns :")
r1 = int(input("Matrix 1 - Row : "))
c1 = int(input("Matrix 1 - Column : "))

# Addition and Subtraction
if (r1 != c1):
    print("Not a square matrix.")
    print("Cannot Add the diagonal elements.")
else:
    Mat_A = fn_read(r1, c1)
       
    print("Given Matrix : ")   
    fn_display(Mat_A)
   
    dsum = fn_add(Mat_A, r1)
    print("Sum of diagonal elements of given matrices :", dsum)   
   

Functions - Matrix - Multiplication

# Functions and Matrix
# Matrix Multiplication

# Function - Read Matrix
def fn_read(r, c):
    M = []
    print("Enter values of Matrix : ")
    for i in range(0,r,1):
        tmp = []
        for j in range(0,c,1):
            ele = int(input())
            tmp.append(ele)
        M.append(tmp)
    return M

# Function - Display Matrix
def fn_display(M):
    for row in M:
        for ele in row:
            print(ele, end=" ")
        print()

# Function - Matrix Multiplication
def fn_mul(MA, MB, ra, ca, cb):
    M = []
    for i in range(0,ra,1):
        tmp = []
        for j in range(0,cb,1):
            ele = 0
            for k in range(0,ca,1):
                ele = ele + (Mat_A[i][k] * Mat_B[k][j])
            tmp.append(ele)
        M.append(tmp)
    return M


# Main Program

import sys

Mat_A = []
Mat_B = []
Mat_Mul = []

print("Enter number of rows and columns :")
r1 = int(input("Matrix 1 - Row : "))
c1 = int(input("Matrix 1 - Column : "))
r2 = int(input("Matrix 2 - Row : "))
c2 = int(input("Matrix 2 - Column : "))

# Multiplication
if (c1 != r2):
    print("Rows and columns do not match.")
    print("Cannot multiply.")
else:
    Mat_A = fn_read(r1, c1)
    Mat_B = fn_read(r2, c2)
   
    print("Given matrix 1 : ")   
    fn_display(Mat_A)
    print("Given matrix 2 : ")   
    fn_display(Mat_B)
       
    Mat_Mul = fn_mul(Mat_A, Mat_B, ra = r1, ca = c1, cb = c2)
    print("Product of given matrices : ")
    fn_display(Mat_Mul)

Functions - Matrix - Subtraction

# Functions and Matrix
# Matrix Subtraction

# Function - Read Matrix
def fn_read(r, c):
    M = []
    print("Enter values of Matrix : ")
    for i in range(0,r,1):
        tmp = []
        for j in range(0,c,1):
            ele = int(input())
            tmp.append(ele)
        M.append(tmp)
    return M

# Function - Display Matrix
def fn_display(M):
    for row in M:
        for ele in row:
            print(ele, end=" ")
        print()

# Function - Matrix Subtraction
def fn_sub(MA, MB, r, c):
    M = []
    for i in range(0,r,1):
        tmp = []
        for j in range(0,c,1):
            ele = MA[i][j] - MB[i][j]
            tmp.append(ele)
        M.append(tmp)
    return M
   
# Main Program

import sys

Mat_A = []
Mat_B = []
Mat_Sub = []

print("Enter number of rows and columns :")
r1 = int(input("Matrix 1 - Row : "))
c1 = int(input("Matrix 1 - Column : "))
r2 = int(input("Matrix 2 - Row : "))
c2 = int(input("Matrix 2 - Column : "))

# Subtraction
if ( (r1 != r2) or (c1 != c2) ):
    print("Rows and columns of given matrices do not match.")
    print("Cannot Subtract the matrices.")
else:
    Mat_A = fn_read(r1, c1)
    Mat_B = fn_read(r2, c2)
   
    print("Given matrix 1 : ")   
    fn_display(Mat_A)
    print("Given matrix 2 : ")   
    fn_display(Mat_B)
   
    Mat_Sub = fn_sub(Mat_A, Mat_B, r1, c1)
    print("Difference of given matrices : ")
    fn_display(Mat_Sub)
   

Functions - Matrix - Addition

# Functions and Matrix
# Matrix Addition

# Function - Read Matrix
def fn_read(r, c):
    M = []
    print("Enter values of Matrix : ")
    for i in range(0,r,1):
        tmp = []
        for j in range(0,c,1):
            ele = int(input())
            tmp.append(ele)
        M.append(tmp)
    return M

# Function - Display Matrix
def fn_display(M):
    for row in M:
        for ele in row:
            print(ele, end=" ")
        print()

# Function - Matrix Addition
def fn_add(MA, MB, r, c):
    M = []
    for i in range(0,r,1):
        tmp = []
        for j in range(0,c,1):
            ele = MA[i][j] + MB[i][j]
            tmp.append(ele)
        M.append(tmp)
    return M

# Main Program

import sys

Mat_A = []
Mat_B = []
Mat_Add = []

print("Enter number of rows and columns :")
r1 = int(input("Matrix 1 - Row : "))
c1 = int(input("Matrix 1 - Column : "))
r2 = int(input("Matrix 2 - Row : "))
c2 = int(input("Matrix 2 - Column : "))

# Addition
if ( (r1 != r2) or (c1 != c2) ):
    print("Rows and columns of given matrices do not match.")
    print("Cannot Add the matrices.")
else:
    Mat_A = fn_read(r1, c1)
    Mat_B = fn_read(r2, c2)
   
    print("Given matrix 1 : ")   
    fn_display(Mat_A)
    print("Given matrix 2 : ")   
    fn_display(Mat_B)
   
    Mat_Add = fn_add(Mat_A, Mat_B, r1, c1)
    print("Sum of given matrices : ")   
    fn_display(Mat_Add)
   

Function, biggest of three numbers

# Function - biggest of three numbers

def fn_big(x,y,z):
    if (x >= y and x >= z):
        return x
    elif (y >= x and y >= z):
        return y
    else:
        return z
    return max(x,y,z)

num1 = int(input("Enter number :"))
num2 = int(input("Enter number :"))
num3 = int(input("Enter number :"))

big = fn_big(num1, num2, num3)
print("biggest of three numbers is :", big)

# Function - biggest of three numbers

def fn_big(x,y,z):
    return max(x,y,z)

num1 = int(input("Enter number :"))
num2 = int(input("Enter number :"))
num3 = int(input("Enter number :"))

big = fn_big(num1, num2, num3)
print("biggest of three numbers is :", big)

Functions - swap two numbers

# Functions - swap two numbers

def fn_swap(x, y):
    x, y = y, x
    return x, y

# Main program

num1 = int(input("Enter numbre :"))
num2 = int(input("Enter numbre :"))

print("Numbers before swap :", num1, num2)
num1, num2 = fn_swap(num1, num2)
print("Numbers after swap :", num1, num2)

Functions - recursion - Factorial of a number

# Functions - recursion, Factorial of a number

def fnfact(n):
    if (n==0):
        return 1
    else:
        fact = n * fnfact(n-1)
   
    return fact

num = int(input("Enter number :"))
f = fnfact(num)
print("Factorial of", num, "is", f)

List - Matrix Multiplication

# MatrixMultiplication

Mat_A = []
Mat_B = []
Mat_Mul = []

print("Enter number of rows and columns :")
r1 = int(input("Matrix 1 - Row : "))
c1 = int(input("Matrix 1 - Column : "))
r2 = int(input("Matrix 2 - Row : "))
c2 = int(input("Matrix 2 - Column : "))

# Multiplication
if (c1 != r2):
    print("Rows and columns do not match.")
    print("Cannot multiply.")
else:
    print("Matrix A - Enter values : ")
    for i in range(0,r1,1):
        tmp = []
        for j in range(0,c1,1):
            ele = int(input())
            tmp.append(ele)
        Mat_A.append(tmp)
           
    print("Matrix B - Enter values : ")
    for i in range(0,r2,1):
        tmp = []
        for j in range(0,c2,1):
            ele = int(input())
            tmp.append(ele)
        Mat_B.append(tmp)
       
    for i in range(0,r1,1):
        tmp = []
        for j in range(0,c2,1):
            ele = 0
            for k in range(0,c1,1):
                ele = ele + (Mat_A[i][k] * Mat_B[k][j])
            tmp.append(ele)
        Mat_Mul.append(tmp)
       
    print("Product of given matrices : ")
   
    for row in Mat_Mul:
        for ele in row:
            print(ele, end=" ")
        print()

List - Matrix Subtraction

# Matrix Subtraction

Mat_A = []
Mat_B = []

Mat_Sub = []

print("Enter number of rows and columns :")
r1 = int(input("Matrix 1 - Row : "))
c1 = int(input("Matrix 1 - Column : "))
r2 = int(input("Matrix 2 - Row : "))
c2 = int(input("Matrix 2 - Column : "))
 
# Subtraction
if ( (r1 != r2) or (c1 != c2) ):
    print("Rows and columns of given matrices do not match.")
    print("Cannot Subtract the matrices.")
else:
    print("Matrix A - Enter values : ")
    for i in range(0,r1,1):
        tmp = []
        for j in range(0,c1,1):
            ele = int(input())
            tmp.append(ele)
        Mat_A.append(tmp)
           
    print("Matrix B - Enter values : ")
    for i in range(0,r2,1):
        tmp = []
        for j in range(0,c2,1):
            ele = int(input())
            tmp.append(ele)
        Mat_B.append(tmp)

    for i in range(0,r1,1):
        tmp = []
        for j in range(0,c1,1):
            ele = Mat_A[i][j] - Mat_B[i][j]
            tmp.append(ele)
        Mat_Sub.append(tmp)
   
    print("Difference of given matrices : ")
   
    for row in Mat_Sub:
        for ele in row:
            print(ele, end=" ")
        print()
  

List - Matrix Addition

# Matrix Addition

Mat_A = []
Mat_B = []
Mat_Add = []

print("Enter number of rows and columns :")
r1 = int(input("Matrix 1 - Row : "))
c1 = int(input("Matrix 1 - Column : "))
r2 = int(input("Matrix 2 - Row : "))
c2 = int(input("Matrix 2 - Column : "))

# Addition
if ( (r1 != r2) or (c1 != c2) ):
    print("Rows and columns of given matrices do not match.")
    print("Cannot Add the matrices.")
else:
    print("Matrix A - Enter values : ")
    for i in range(0,r1,1):
        tmp = []
        for j in range(0,c1,1):
            ele = int(input())
            tmp.append(ele)
        Mat_A.append(tmp)
           
    print("Matrix B - Enter values : ")
    for i in range(0,r2,1):
        tmp = []
        for j in range(0,c2,1):
            ele = int(input())
            tmp.append(ele)
        Mat_B.append(tmp)
   
    for i in range(0,r1,1):
        tmp = []
        for j in range(0,c1,1):
            ele = Mat_A[i][j] + Mat_B[i][j]
            tmp.append(ele)
        Mat_Add.append(tmp)

    print("Sum of given matrices : ")
   
    for row in Mat_Add:
        for ele in row:
            print(ele, end=" ")
        print()