Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Phython

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

1. Write a function that returns the maximum of two numbers.

Sol : a = 2

b=4

maximum = max(a, b)

print(maximum)

2. Write a Python Program to detect if Two Strings are Anagrams

s1=input("Enter first string:")

s2=input("Enter second string:")

if(sorted(s1)==sorted(s2)):

print("The strings are anagrams.")

else:

print("The strings aren't anagrams.")

3. Write a Python Program to Convert Binary to Gray Code

def binary_to_gray(n):

"""Convert Binary to Gray codeword and return it."""

n = int(n, 2) # convert to int

n ^= (n >> 1)

return bin(n)[2:]

g = input('Enter binary number: ')

b = binary_to_gray(g)

print('Gray codeword:', b)

4. Use Bisection Method to find roots of a given function f(x)


def func(x):

return x*x*x - x*x + 2

# Prints root of func(x)

# with error of EPSILON

def bisection(a,b):

if (func(a) * func(b) >= 0):

print("You have not assumed right a and b\n")

return

c=a

while ((b-a) >= 0.01):

# Find middle point

c = (a+b)/2

# Check if middle point is root

if (func(c) == 0.0):

break

# Decide the side to repeat the steps

if (func(c)*func(a) < 0):


b=c

else:

a=c

print("The value of root is : ","%.4f"%c)

# Driver code

# Initial values assumed

a =-200

b = 300

bisection(a, b)

5.Design a simple calculator to perform addition, subtraction, multiplication


and division.
# Function to add two numbers
def add(num1, num2):
return num1 + num2

# Function to subtract two numbers


def subtract(num1, num2):
return num1 - num2

# Function to multiply two numbers


def multiply(num1, num2):
return num1 * num2

# Function to divide two numbers


def divide(num1, num2):
return num1 / num2

print("Please select operation -\n" \


"1. Add\n" \
"2. Subtract\n" \
"3. Multiply\n" \
"4. Divide\n")
# Take input from the user
select = int(input("Select operations form 1, 2, 3, 4 :"))

number_1 = int(input("Enter first number: "))


number_2 = int(input("Enter second number: "))

if select == 1:
print(number_1, "+", number_2, "=",
add(number_1, number_2))

elif select == 2:
print(number_1, "-", number_2, "=",
subtract(number_1, number_2))

elif select == 3:
print(number_1, "*", number_2, "=",
multiply(number_1, number_2))

elif select == 4:
print(number_1, "/", number_2, "=",
divide(number_1, number_2))
else:
print("Invalid input")

6. Write a python program that accepts students names separated with


comma as an input and prints the names in sorted form (alphanumerically).
Ans :items = input("Input comma separated sequence of words")
words = [word for word in items.split(",")]
print(",".join(sorted(list(set(words)))))

7. Use Cramer’s rule to solve minimum 3 linear equations


def determinantOfMatrix(mat):

ans = (mat[0][0] * (mat[1][1] * mat[2][2] -


mat[2][1] * mat[1][2]) -
mat[0][1] * (mat[1][0] * mat[2][2] -
mat[1][2] * mat[2][0]) +
mat[0][2] * (mat[1][0] * mat[2][1] -
mat[1][1] * mat[2][0]))
return ans

# This function finds the solution of system of


# linear equations using cramer's rule
def findSolution(coeff):

# Matrix d using coeff as given in


# cramer's rule
d = [[coeff[0][0], coeff[0][1], coeff[0][2]],
[coeff[1][0], coeff[1][1], coeff[1][2]],
[coeff[2][0], coeff[2][1], coeff[2][2]]]

# Matrix d1 using coeff as given in


# cramer's rule
d1 = [[coeff[0][3], coeff[0][1], coeff[0][2]],
[coeff[1][3], coeff[1][1], coeff[1][2]],
[coeff[2][3], coeff[2][1], coeff[2][2]]]

# Matrix d2 using coeff as given in


# cramer's rule
d2 = [[coeff[0][0], coeff[0][3], coeff[0][2]],
[coeff[1][0], coeff[1][3], coeff[1][2]],
[coeff[2][0], coeff[2][3], coeff[2][2]]]

# Matrix d3 using coeff as given in


# cramer's rule
d3 = [[coeff[0][0], coeff[0][1], coeff[0][3]],
[coeff[1][0], coeff[1][1], coeff[1][3]],
[coeff[2][0], coeff[2][1], coeff[2][3]]]

# Calculating Determinant of Matrices


# d, d1, d2, d3
D = determinantOfMatrix(d)
D1 = determinantOfMatrix(d1)
D2 = determinantOfMatrix(d2)
D3 = determinantOfMatrix(d3)

print("D is : ", D)
print("D1 is : ", D1)
print("D2 is : ", D2)
print("D3 is : ", D3)

# Case 1
if (D != 0):

# Coeff have a unique solution.


# Apply Cramer's Rule
x = D1 / D
y = D2 / D

# calculating z using cramer's rule


z = D3 / D

print("Value of x is : ", x)
print("Value of y is : ", y)
print("Value of z is : ", z)

# Case 2
else:
if (D1 == 0 and D2 == 0 and
D3 == 0):
print("Infinite solutions")
elif (D1 != 0 or D2 != 0 or
D3 != 0):
print("No solutions")

# Driver Code
if __name__ == "__main__":

# storing coefficients of linear


# equations in coeff matrix
coeff = [[2, -1, 3, 9],
[1, 1, 1, 6],
[1, -1, 1, 2]]

findSolution(coeff)

8.Write a Python Program to Count the Frequency of Words Appearing in a


String Using a Dictionary

# initializing lists
test_list = ["Gfg", 3, "is", 8, "Best", 10, "for", 18, "Geeks", 33]

# printing original list


print("The original list : " + str(test_list))

# initializing key list


key_list = ["name", "number"]

# loop to iterate through elements


# using dictionary comprehension
# for dictionary construction
n = len(test_list)
res = []
for idx in range(0, n, 2):
res.append({key_list[0]: test_list[idx], key_list[1] : test_list[idx + 1]})

# printing result
print("The constructed dictionary list : " + str(res))

9.Write a Python Program to Generate a Dictionary that Contains Numbers


(between 1 and n) in the Form (x,x*x).

:n=int(input("Input a number "))


d = dict()

for x in range(1,n+1):
d[x]=x*x

print(d)

10. Write program to read 2X2 matrix and find its covariance matrix. Eigen
values and Eigen vectors of covariance matrix. Discuss what do you mean by
eigen values and covariance matrix

import numpy as np
m = np.mat("3 -2;1 0")
print("Original matrix:")
print("a\n", m)
w, v = np.linalg.eig(m)
print( "Eigenvalues of the said matrix",w)
print( "Eigenvectors of the said matrix",v)

11.Write a Python Program to Compute the Value of Euler's Number e. Use the
Formula:
e = 1 + 1/1! + 1/2! + …… 1/n!

import math
n=int(input("Enter the number of terms: "))
sum1=1
for i in range(1,n+1):
sum1=sum1+(1/math.factorial(i))
print("The sum of series is",round(sum1,2))

11.Write a function called fizz_buzz that takes a number.


1. If the number is divisible by 7, it should return “Fizz”.
2. If it is divisible by 9, it should return “Buzz”.
3. If it is divisible by both 7 and 9, it should return “FizzBuzz”.

for fizzbuzz in range(51):


if fizzbuzz % 7 == 0 and fizzbuzz % 9 == 0:
print("fizzbuzz")
continue
elif fizzbuzz % 7 == 0:
print("fizz")
continue
elif fizzbuzz % 9 == 0:
print("buzz")
continue
print(fizzbuzz)

11. Write a Python Program to Count the Frequency of Words Appearing in a


String Using a Dictionary

test_string=input("Enter string:")
l=[]
l=test_string.split()
wordfreq=[l.count(p) for p in l]
print(dict(zip(l,wordfreq)))

12.Write a python program to find the H.C.F of two input number using loops

def calculate_hcf(x, y):


# selecting the smaller number
if x > y:
smaller = y
else:
smaller = x
for i in range(1,smaller + 1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf

# taking input from users


num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
# printing the result for the users
print("The H.C.F. of", num1,"and", num2,"is", calculate_hcf(num1, num2))
15. Write a Python Program to Implement Stack using One Queue
class Stack:
def __init__(self):
self.q = Queue()

def is_empty(self):
return self.q.is_empty()

def push(self, data):


self.q.enqueue(data)

def pop(self):
for _ in range(self.q.get_size() - 1):
dequeued = self.q.dequeue()
self.q.enqueue(dequeued)
return self.q.dequeue()

class Queue:
def __init__(self):
self.items = []
self.size = 0

def is_empty(self):
return self.items == []

def enqueue(self, data):


self.size += 1
self.items.append(data)

def dequeue(self):
self.size -= 1
return self.items.pop(0)

def get_size(self):
return self.size

s = Stack()

print('Menu')
print('push <value>')
print('pop')
print('quit')

while True:
do = input('What would you like to do? ').split()

operation = do[0].strip().lower()
if operation == 'push':
s.push(int(do[1]))
elif operation == 'pop':
if s.is_empty():
print('Stack is empty.')
else:
print('Popped value: ', s.pop())
elif operation == 'quit':
break

16. Write a python program to check leap year

def CheckLeap(Year):
# Checking if the given year is leap year
if((Year % 400 == 0) or
(Year % 100 != 0) and
(Year % 4 == 0)):
print("Given Year is a leap Year");
# Else it is not a leap year
else:
print ("Given Year is not a leap Year")
# Taking an input year from user
Year = int(input("Enter the number: "))
# Printing result
CheckLeap(Year)

17.Write a Python Program to Read a List of Words and Return the Length of
the Longest One
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=input("Enter element" + str(x+1) + ":")
a.append(element)
max1=len(a[0])
temp=a[0]
for i in a:
if(len(i)>max1):
max1=len(i)
temp=i
print("The word with the longest length is:")
print(temp)

18.Perform following matrix operations:


o Writing a data into given size matrix
o Reading a matrix to either row vector or column vector
o Addition, subtraction, multiplication of matrices
o Find the rank of a given matrix

import numpy as np

matrix1 = []
print("Enter the entries of first matrix rowwise:")

for i in range(2): # A for loop for row entries


a =[]
for j in range(2): # A for loop for column entries
a.append(int(input()))
matrix1.append(a)
arr1 = np.array(matrix1)

matrix2 = []

print("Enter the entries of second matrix rowwise:")

for i in range(2): # A for loop for row entries


a =[]
for j in range(2): # A for loop for column entries
a.append(int(input()))
matrix2.append(a)

arr2 = np.array(matrix2)
print('----------First Matrix---------------')

# For printing the matrix


for i in range(2):
for j in range(2):
print(matrix1[i][j], end = " ")
print()
print('----------Second Matrix---------------')
for i in range(2):
for j in range(2):
print(matrix2[i][j], end = " ")
print()

print("Addition of two matrix is ", arr1+arr2)


print("Substraction of two matrix is ", arr1-arr2)
print("Dot product of two matrix is ", arr1.dot(arr2))
print("Multiplication of two matrix is ", arr1*arr2)

# Python 3 program to find rank of a matrix


class rankMatrix(object):
def __init__(self, Matrix):
self.R = len(Matrix)
self.C = len(Matrix[0])

# Function for exchanging two rows of a matrix


def swap(self, Matrix, row1, row2, col):
for i in range(col):
temp = Matrix[row1][i]
Matrix[row1][i] = Matrix[row2][i]
Matrix[row2][i] = temp

# Function to Display a matrix


def Display(self, Matrix, row, col):
for i in range(row):
for j in range(col):
print (" " + str(Matrix[i][j]))
print ('\n')

# Find rank of a matrix


def rankOfMatrix(self, Matrix):
rank = self.C
for row in range(0, rank, 1):

# Before we visit current row


# 'row', we make sure that
# mat[row][0],....mat[row][row-1]
# are 0.

# Diagonal element is not zero


if Matrix[row][row] != 0:
for col in range(0, self.R, 1):
if col != row:

# This makes all entries of current


# column as 0 except entry 'mat[row][row]'
multiplier = (Matrix[col][row] /
Matrix[row][row])
for i in range(rank):
Matrix[col][i] -= (multiplier *
Matrix[row][i])

else:
reduce = True

# Find the non-zero element


# in current column
for i in range(row + 1, self.R, 1):

# Swap the row with non-zero


# element with this row.
if Matrix[i][row] != 0:
self.swap(Matrix, row, i, rank)
reduce = False
break

if reduce:

# Reduce number of columns


rank -= 1

# copy the last column here


for i in range(0, self.R, 1):
Matrix[i][row] = Matrix[i][rank]

# process this row again


row -= 1

# self.Display(Matrix, self.R,self.C)
return (rank)

# Driver Code

Matrix = matrix1
RankMatrix = rankMatrix(Matrix)
print ("Rank of the Matrix is:",
(RankMatrix.rankOfMatrix(Matrix)))
Matrix = matrix2
RankMatrix = rankMatrix(Matrix)
print ("Rank of the Matrix is:",
(RankMatrix.rankOfMatrix(Matrix)))

19. Write a function that returns the maximum of two numbers.

a=2
b=4

maximum = max(a, b)
print(maximum)

20. Write a python program for Matrix Multiplication Using Nested List
Comprehension and using Using Nested Loop

def Multiply(X,Y):

result=[ [0,0,0],[0,0,0],[0,0,0] ]
#list comprehension
result= [[sum(a*b for a,b in zip(X_row,Y_col)) for Y_col in zip(*Y)] for
X_row in X]

for k in result:
print(k)

return 0

A = [ [6, 7, 2],[3, 5, 4], [1, 2, 3] ]

B = [[1, 5],[2, 5],[6, 3]]

print("Result: ")
Multiply(A,B)

21. Write a Python Program that Reads a Text File and Counts the Number of
Times a Certain Letter Appears in the Text File

fname = input("Enter file name: ")

num_words = 0

with open(fname, 'r') as f:


for line in f:
words = line.split()
num_words += len(words)
print("Number of words:")
print(num_words)
22. Write a Python Program to Check String is Palindrome using Stack
class Stack:
def __init__(self):
self.items = []

def is_empty(self):
return self.items == []

def push(self, data):


self.items.append(data)

def pop(self):
return self.items.pop()

s = Stack()
text = input('Please enter the string: ')

for character in text:


s.push(character)

reversed_text = ''
while not s.is_empty():
reversed_text = reversed_text + s.pop()

if text == reversed_text:
print('The string is a palindrome.')
else:
print('The string is not a palindrome.')

23.Write a program to compute polynomial equation


import math
print("Enter the coefficients of the form ax^3 + bx^2 + cx + d")
lst=[]
for i in range(0,4):
a=int(input("Enter coefficient:"))
lst.append(a)
x=int(input("Enter the value of x:"))
sum1=0
j=3
for i in range(0,3):
while(j>0):
sum1=sum1+(lst[i]*math.pow(x,j))
break
j=j-1
sum1=sum1+lst[3]
print("The value of the polynomial is:",sum1)

24. Write a Python program to check if a number is positive or


negative

num = float(input("Enter a number: "))


if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

25.Write a code to check whether a given number is prime or not,

If not prime, whether it is divisible by 3,7,9,11

num =10

# If given number is greater than 1


if num > 1:

# Iterate from 2 to n / 2
for i in range(2, int(num/2)+1):

# If num is divisible by any number between


# 2 and n / 2, it is not prime
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
26.Write a function for checking the speed of drivers. This function should
have one parameter: speed.
8. If speed is less than 60, it should print “Ok”.
9. Otherwise, for every 5km above the speed limit (60), it should give the
driver one demerit point and print the total number of demerit points. For
example, if the speed is 80, it should print: “Points: 4”.
10.If the driver gets more than 12 points, the function should print: “License
suspended”

def speed_check(speed):
if speed <= 60:
return "OK"

else:
speed1 = (speed-60)/5

if speed1 <= 12:


return (f"Point: {speed1}")

else:
return ("License suspended")

enter = speed_check(int(input("Enter speed: ")))


print(enter)

27.Write a function called showNumbers that takes a parameter


called limit. It should print all the numbers between 0 and limit (limit should
be greater than 6 with a label to identify the square numbers. For example, if
the limit is 7, it should print:
o 0 NA
o 1 Sq No
o 2 NOT a Sq No
o 3 NOT a Sq No
o 4 Sq No
o 5 NOT a Sq No
o 6 NOT a Sq No
o 7 NOT a Sq No

def even_odd_recognize(limit):
for i in range(0,limit+1):
if(i%2==0):
print(i,' EVEN')
else:
print(i,' ODD')

27..Write a function called show_stars(rows). If rows is 5, it should print the


following:

n = int(input("Enter the number of rows"))

for i in range(0, n):

for j in range(0, i + 1):


# printing stars
print("* ", end="")
print()

28. Write a function that returns the sum of multiples of 3 and 5 between 0
and limit (parameter). For example, if limit is 20, it should return the sum of 3,
5, 6, 9, 10, 12, 15, 18, 20.

total_sum = 0
for i in range(21):
if (i%3 == 0 or i%5 == 0):
total_sum = total_sum+i
print (total_sum)

29. Write a Python Program to Read a Number n And Print the Series "1+2+
…..+n= "

n = input("Enter Number to calculate sum & average")

n = int (n)

sum = 0

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

sum = sum+num

average = sum / n

print("SUM of", n, "numbers is: ", sum )


print("Average of", n, "natural number is: ", average)

You might also like