Showing posts with label PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY. Show all posts
Showing posts with label PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY. Show all posts

Set operations

 # Set manipulation


"""

The second year of engineering offers the following subjects in two departments. 

CSE = ["PQT", "ADC", "SE", "DPSD", "DS", "OOP"]

IT = ["OS", "PQT", "DS", "SE", "OOP", "SS"]


Write a program to create set of subjects for the two departments.  

Use set operations to find 

1. Number and names of subjects in CSE

2. Number and names of subjects in IT

3. Names of subjects in CSE only

4. Names of subjects in IT only

5. Number and names of subjects in both CSE and IT

6. Number and names of subjects for either CSE or IT, but not in both

7. Number and names of all subjects.

"""


# Converting Given List to set

CSE = set(["PQT", "ADC", "SE", "DPSD", "DS", "OOP"])

IT = set(["OS", "PQT", "DS", "SE", "OOP", "SS"])


print("CSE =",CSE)

print("IT =",IT)



# 1. Number and names of subjects in CSE

print("Number of subjects in CSE = ", len(CSE))

print("Subjects in CSE : ")

for sub in CSE:

print(sub, end=", ")

print()


# 2. Number and names of subjects in IT

print("Number of subjects in IT = ", len(IT))

print("Subjects in IT : ")

print(", ".join(IT))


# 3. Names of subjects in CSE only

print("Names of subjects in CSE only : ", CSE.difference(IT))


# 4. Names of subjects in IT only

print("Names of subjects in IT only : ", IT.difference(CSE))


# 5. Number and names of subjects in both CSE and IT

CommonSubjects = CSE.intersection(IT)

print("Number of common subjects in CSE and IT =",len(CommonSubjects))

print("Names of common subjects in CSE and IT :",CommonSubjects)


# 6. Number and names of subjects for either CSE or IT, but not in both

UniqueSubjects = CSE.symmetric_difference(IT)

print("Number of subjects for either CSE or IT, but not in both = ", len(UniqueSubjects))

print("Names of subjects for either CSE or IT, but not in both = ", UniqueSubjects)


# 7. Number and names of all subjects.

Allsub=CSE.union(IT)

print("Number of subjects : ", len(Allsub))

print("Names of all subjects : ", Allsub)


"""

Sampleoutput

>python Set.py

CSE = {'PQT', 'SE', 'DPSD', 'ADC', 'DS', 'OOP'}

IT = {'PQT', 'SS', 'SE', 'OS', 'DS', 'OOP'}

Number of subjects in CSE =  6

Subjects in CSE :

PQT, SE, DPSD, ADC, DS, OOP,

Number of subjects in IT =  6

Subjects in IT :

PQT, SS, SE, OS, DS, OOP

Names of subjects in CSE only :  {'ADC', 'DPSD'}

Names of subjects in IT only :  {'SS', 'OS'}

Number of common subjects in CSE and IT = 4

Names of common subjects in CSE and IT : {'OOP', 'PQT', 'DS', 'SE'}

Number of subjects for either CSE or IT, but not in both =  4

Names of subjects for either CSE or IT, but not in both =  {'SS', 'ADC', 'DPSD', 'OS'}

Number of subjects :  8

Names of all subjects :  {'PQT', 'SS', 'SE', 'DPSD', 'OS', 'ADC', 'DS', 'OOP'}

"""

Pygame - car racing - python

 # Car Racing based on keypress


import sys,pygame


pygame.init()

screen = pygame.display.set_mode((500, 500))

pygame.display.set_caption("Car Racing")

  

# Car starting co-ordinates and size

x = 200

y = 200


width = 20

height = 20

  

# Moving speed

step = 5


# Loading image

car = pygame.image.load("car.png")

car = pygame.transform.scale(car, (35, 65))

carrect = car.get_rect()


# Changing direction 

car_rotated_Left = pygame.transform.rotate(car, 90)

car_rotated_Right = pygame.transform.rotate(car, 270)

car_rotated_Up = pygame.transform.rotate(car, 0)

car_rotated_Down = pygame.transform.rotate(car, 180)


# infinite loop 

while 1:

pygame.time.delay(10)

angle = 0

for event in pygame.event.get():

if event.type == pygame.QUIT:

sys.exit()


# Get the keys pressed 

keys = pygame.key.get_pressed()

      

    # Left arrow key - decrement in x axis

if keys[pygame.K_LEFT]and x>0:

x-=step

car=car_rotated_Left

    # Right arrow key - increment in x axis

if keys[pygame.K_RIGHT] and x<500-width:

x += step

car=car_rotated_Right

         

    # Up arrow key - decrement in y axis

if keys[pygame.K_UP] and y>0:

y -= step

car=car_rotated_Up

          

    # Down arrow key - increment in y axis

if keys[pygame.K_DOWN] and y<500-height:

y += step

car=car_rotated_Down


    # Set screen background and Place moving object on screen 

screen.fill((255, 255, 255))

screen.blit(car, (x, y))

pygame.display.flip()

      

    # Display movement

pygame.display.update() 

  

pygame.quit()


Nested List Sorting

# Nested List sort


L = [['IT', 56], ['CSE', 53], ['EEE', 52], ['ECE', 55]]


# Sorting a nested List using bubble sort

# default - sorts by first element of nested list


for i in range(0,len(L)):

for j in range(0,len(L)-1):

if(L[j]>L[j+1]):

L[j],L[j+1]=L[j+1],L[j]


print("Sort by first element (default)")

print(L)


# Sorting a nested List using bubble sort

# Sort by second element of nested list


for i in range(0,len(L)):

for j in range(0,len(L)-1):

if(L[j][1]>L[j+1][1]):

L[j],L[j+1]=L[j+1],L[j]

print("Sort by Second element")

print(L)


"""

Sample output

 >python NestedListSort.py


Sort by first element (default)


[['CSE', 53], ['ECE', 55], ['EEE', 52], ['IT', 56]]


Sort by Second element


[['EEE', 52], ['CSE', 53], ['ECE', 55], ['IT', 56]]


"""

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.]


"""


Dictionary - Histogram - character frequency of a string

 # Dictionary - Histograms

# Create a histogram based on the frequency of characters in given string

# Histogram - String - Word Frequency


import operator


string1 = "An algorithm is a step-by-step procedure to solve a given problem. It is a well-defined computational procedure that takes some values as input, manipulates them using a set of instructions and produces some values as output and terminates in a finite amount of time. An algorithm, when formally written in a programming language is called a program, or code. Derivation of an algorithm that solves the problem and conversion of the algorithm into code, together,  is known as Algorithmic Problem Solving."


string1 = string1.lower()


ch = set(string1)


D = {c:string1.count(c) for c in ch if c.isalpha()}  


print("Histogram")

print("Length of dictionary = ", len(D))

print(D)


DSorted = sorted(D.items(), key=operator.itemgetter(1), reverse=True)


D_max3 = dict(DSorted[:3])

print("Most frequently used 3 characters:")

print(D_max3)


"""

Sample output

>python Dict_Hist.py

Histogram

Length of dictionary =  22

{'t': 37, 'a': 39, 'w': 4, 'l': 22, 'g': 14, 'h': 12, 'o': 38, 'u': 14, 's': 26, 'i': 32, 'm': 20, 'e': 40, 'd': 12, 'c': 10, 'r': 25, 'v': 8, 'n': 30, 'b': 4, 'y': 2, 'p': 14, 'k': 2, 'f': 7}

Most frequently used 3 characters:

{'e': 40, 'a': 39, 'o': 38}

"""

Dictionary methods

 # Dictionary Manipulation 


"""

Create a dictionary containing employee name and id (name:id). 

Display

1. Employee names, sorted in alphabetical order

2. Employee name and id, sorted alphabetically by name

3. Inverse the dictionary (id : name)

"""


# Program


# Creating dictionary

Emp_ID = {'Alice':283, 'Larry':185, 'Cathy':307, 'Gary':585, 'Dan':427, 'Bob':734, 'Ed':564, 'Helen':370, 'Jack':609, 'Irene':921, 'Frank':478, 'Kelly':154}


print(Emp_ID)


# 1. Employee names, sorted in alphabetical order

print("Employee names - sorted alphabetically")

Emp_Names = sorted(Emp_ID.keys())

print("\n".join(Emp_Names))


# 2. Employee name and id, sorted alphabetically by name

print("Employee name and id - sorted alphabetically")

SD = {k:Emp_ID[k] for k in sorted(Emp_ID.keys())}

for k in SD:

print(k.ljust(10), SD[k])

# 3. Inverse the dictionary (id : name)

print("Inverse Dictionary")

InvD = {v:k for k,v in Emp_ID.items()}

for k in InvD:

print(k,"\t",InvD[k])


Number series - sine series

 # Sine series 


import math


def fn_x(x, term):

return (math.pow(x,term))


def fn_fact(term):

if(term==0):

return 1

else:

return term*fn_fact(term-1)


x = int(input("Enter value of x : "))

n = int(input("Enter number of terms : "))


Sine_series = 0

i = 1

p = 1


for count in range(0,n+1):

Sine_series = Sine_series+(i * (fn_x(x,p) / fn_fact(p)))

p = p+2

i = i*(-1)


print("Sine series = ", round(Sine_series,4))



"""

Sample output

>python sine_series.py

Enter value of x : 2

Enter number of terms : 5

Sine series =  0.9093

"""




Functions - Area of a Shape

 # Functions 

# Area of a shape


def fnSquare(s):

return (s*s)


def fnRectangle(l,b):

return (l*b)


def fnCircle(r):

return 3.142*r*r

def fnTriangle(base,ht):

return 0.5*base*ht


# square


s = eval(input("Enter side of square : "))

l,b = map(int,(input("Enter length and breath of rectangle : ").split()))

r = eval(input("Enter circle radius : "))

base,ht = map(int,(input("Enter base and height of triangle : ").split()))


print("Area of square =",fnSquare(s))

print("Area of rectangle =",fnRectangle(l,b))

print("Area of circle =",fnCircle(r))

print("Area of triangle =",fnTriangle(base,ht))


"""

Sample output

>python 6_Area.py

Enter side of square : 5

Enter length and breath of rectangle : 4 6

Enter circle radius : 3

Enter base and height of triangle : 5 6

Area of square = 25

Area of rectangle = 24

Area of circle = 28.278

Area of triangle = 15.0

"""

List Comprehension - Squares

 # List comprehension

# Squares of numbers 


L = eval(input("Enter List : "))


Squares = [x**2 for x in L]

print("Squares of the given list is : ")

print(Squares)


"""

>python LC_Squares.py

Enter List : [1,2,3,4,5]

Squares of the given list is :

[1, 4, 9, 16, 25]

"""

List Comprehension - count set bits

 # List Comprehension 


"""

Given a list of n integers, count the number of set bits (1’s) in the binary representation of each number present in the list

"""


# Read List

L = eval(input("Enter list of numbers : "))


# Convert each number in List to its binary equivalent and type cast to string

Lbinstr = [str(bin(N)) for N in L]


# Join the binary string and count number of 1's

print("Number of 1's = ",("".join(Lbinstr)).count("1"))


"""

Sample output

>python Listcomprehenstion.py

Enter list of numbers : [1,2,3,4,5]

Number of 1's =  7

"""


List manipulation - membership operator

# List manipulation


"""

The second year of engineering offers the following subjects in two departments. 

CSE = ["PQT", "ADC", "SE", "DPSD", "DS", "OOP"]

IT = ["OS", "PQT", "DS", "SE", "OOP", "SS"]


Write a program to create subject list for the two departments.  

Also find 

1. Number and names of subjects in CSE

2. Number and names of subjects in IT

3. Names of subjects in CSE only

4. Names of subjects in IT only

5. Number and names of subjects in both CSE and IT

6. Number and names of subjects for either CSE or IT, but not in both

7. Number and names of all subjects.

"""


# Create List

# CSE = ["PQT", "ADC", "SE", "DPSD", "DS", "OOP"]

# IT = ["OS", "PQT", "DS", "SE", "OOP", "SS"]


CSE = []

print("Enter subjects for CSE : ")

for count in range(0,6):

sub = input()

CSE.append(sub)

IT = eval(input("Enter subjects for IT : "))


# 1. Number and names of subjects in CSE

print("Number of subjects in CSE = ", len(CSE))

print("Subjects in CSE : ")

for sub in CSE:

print(sub, end=" ")

print()


# 2. Number and names of subjects in IT

print("Number of subjects in IT = ", len(IT))

print("Subjects in IT : ")

print(", ".join(IT))


# 3. Names of subjects in CSE only

print("Names of subjects in CSE only")

for sub in CSE:

if sub not in IT:

print(sub)


# 4. Names of subjects in IT only

print("Names of subjects in IT only")

for sub in IT:

if sub not in CSE:

print(sub)


# 5. Number and names of subjects in both CSE and IT

print("Number and names of subjects in both CSE and IT")

for sub in CSE:

if sub in IT:

print(sub)


# 6. Number and names of subjects for either CSE or IT, but not in both

List1=[]


for sub in IT:

if sub not in CSE:

List1.append(sub)

for sub in CSE:

if sub not in IT:

List1.append(sub)

print("Number of subjects for either CSE or IT, but not in both = ", len(List1))

print(List1)


# 7. Number and names of all subjects.

Allsub=CSE

for sub in IT:

if sub not in Allsub:

Allsub.append(sub)

print("Number and names of all subjects : ", len(Allsub))

string1 = ", ".join(Allsub)

print(string1)



"""

Sample output

>python 4_List.py

Enter subjects for CSE :

PQT

ADC

SE

DPSD

DS

OOP

Enter subjects for IT : ['OS','PQT','DS','SE','OOP','SS']

Number of subjects in CSE =  6

Subjects in CSE :

PQT ADC SE DPSD DS OOP

Number of subjects in IT =  6

Subjects in IT :

OS, PQT, DS, SE, OOP, SS

Names of subjects in CSE only

ADC

DPSD

Names of subjects in IT only

OS

SS

Number and names of subjects in both CSE and IT

PQT

SE

DS

OOP

Number of subjects for either CSE or IT, but not in both =  4

['OS', 'SS', 'ADC', 'DPSD']

Number and names of all subjects :  8

PQT, ADC, SE, DPSD, DS, OOP, OS, SS

""" 

Weight of Steel bar

 # Weight of Steel bar


"""

unit weight of steel bars is D²/162 kg/m. D is the Diameter Of steel bars, 162 is a constant value. 

"""


D = eval(input("Enter diameter of steel bar (in meter) : "))

wt = D*D/162

print("Weight of steel bar = ",round(wt,2),"kg/m")


"""

Sample output

>python wtofsteelbar.py

Enter diameter of steel bar (in meter) : 20

Weight of steel bar =  2.47 kg/m

"""

Electrical Current in Three Phase AC Circuit

 # Electrical Current in Three Phase AC Circuit


import math


P = eval(input("Enter power (in Watts) : "))

pf = eval(input("Enter power factor (pf<1): "))

VL = eval(input("Enter Line Voltage (in Volts) : "))


CL = P/(math.sqrt(3)*VL*pf)

print("Line Current =", round(CL,2),"A")


"""

Sample output

>python current.py

Enter power (in Watts) : 5000

Enter power factor (pf<1): 0.839

Enter Line Voltage (in Volts) : 400

Line Current = 8.6 A

"""

Weight of a motor bike

 # Weight of a motor bike


Bike = {"Chopper":315, "Adventure bike":250, "Dirtbike":100, "Touring bike":400, "Sport bikes":180, "Bagger":340, "Cruiser":250, "Cafe racer":200, "Scooter":115, "Moped":80 }


B = input("Enter bike : ")

print("Weight of", B, "is", Bike[B],"kg.")


"""

Sample output

>python wtofbike.py

Enter bike : Scooter

Weight of Scooter is 115 kg.

"""

String manipulation

 # String manipulation


"""

Implementing programs using Strings. (reverse, palindrome, character count, replacing characters,

remove characters)

"""


def fnReverse(s):

return s[::-1]


def fnPalindrome(s):

if(s==s[::-1]):

return "String is a palindrome"

else:

return "String is not a palindrome"


def fnCharcount(s):

charcount = 0

for ch in s:

if(ch.isalpha()):

charcount+=1

return charcount


def fnWordCount(s):

L=s.split()

return len(L)

def fnReplace(s,ss,rs):

if(ss in s):

return s.replace(ss,rs)

else:

return "Search string not found. Cannot replace"


def fnRemove(s, rs):

if(rs in s):

return s.replace(rs,"")

else:

return "String not found. Cannot remove" 



S = input("Enter string : ")

print("Reverse of the string : ",fnReverse(S))

print("Palindrome check : ")

print(fnPalindrome(S))

print("Character count =",fnCharcount(S))

print("Word count =",fnWordCount(S))

searchstr = input("Enter search string : ")

replacestr = input("Enter string to replace : ")


print("Replaced string :")

print(fnReplace(S,searchstr,replacestr))



removestr = input("Enter string to remove : ")


print("Remove string :")

print(fnRemove(S,removestr))


"""

Sample output

>python 7_stringmanip.py

Enter string : HELLO IT

Reverse of the string :  TI OLLEH

Palindrome check :

String is not a palindrome

Character count = 7

Word count = 2

Enter search string : IT

Enter string to replace : CSE

Replaced string :

HELLO CSE

Enter string to remove : IT

Remove string :

HELLO

"""

Electricity bill calculation

 

# Electricity bill calculation

"""

Tariff rates in TN

Scheme

Unit

Per unit(₹)

0 to 100

0-100

0

0 to 200

0-100

0

101-200

1.5

0 to 500

0-100

0

101-200

2

201-500

3

> 500

0-100

0

101-200

3.5

201-500

4.6

>500

6.6

 

"""

 

Unit = int(input("Enter number of units : "))

L = [[0],[0,1.5],[0,2,3],[0,3.5,4.6,6.6]]

Bill = 0

 

if(Unit>=0 and Unit<=100):

          Bill = 0

elif(Unit<=200):

          Bill = (Unit-100)*L[1][1]

elif(Unit<=500):

          Bill = 100*L[2][1]+(Unit-200)*L[2][2]

else:

          Bill = 100*L[3][1]+300*L[3][2]+(Unit-500)*L[3][3]

 

print("Unit :", Unit)

print("Bill : Rs.", Bill)

 

"""

Sample output

>python EBBill.py

Enter number of units : 510

Unit : 510

Bill : Rs. 1796.0

"""

 

Largest number in a List

 # Function - largest number in a list


def fnMax(L):

return max(L)


L1 = eval(input("Enter a List of numbers : "))

print("Largest number in given List = ", fnMax(L1))


Function overloading in Python - Area of a shape

# Functions - Area of a shape

# Function overloading 


"""

install multipledispatch as below from command prompt


pip install multipledispatch


"""


from multipledispatch import dispatch


@dispatch(int)

def fnShape(x):

print("Area of square = ",(x*x))

@dispatch(float)

def fnShape(x):

print("Area of circle = ",(3.142*x*x))


@dispatch(int,int)

def fnShape(x,y):

print("Area of rectangle = ",(x*y))


# The three function calls differ by number and datatype


fnShape(5) # int

fnShape(2.1)         # float

fnShape(5,6)         # int,int