Python For Exam Sem 1
Python For Exam Sem 1
Theory :
For a triangle we need 2 sides and the angle between them
C =√
Area = √ ( ) ( ) ( )
Where s = (a+b+c)/2
Algorithm:
a) Input a ,b,
b) Convert angle to radian
c) Calculate c
d) Calculate s
e) Calculate area
Program
import math
a = int(input("enter value of a : "))
b = int(input("enter value of b : "))
alpha = int(input("enter value of α : "))
alpha = alpha*math.pi/180
c = math.sqrt(a**2 + b**2 -
2*a*b*math.cos(alpha))
s = (a+b+c)/2
area = math.sqrt(s*(s-a)*(s-b)*(s-c))
print("third side of the triangle is ",c)
print("area of given triangle is ",area)
Page 1 of 22
Elementary Programs
Program :
n = int(input("enter a integer : "))
if n%2 ==0:
print(n,"is an even number ")
else:
print(n,"is an odd number ")
3) Factorial of a number:
Theory :
n! = 1*2*3*…..*n
Algorithm :
a) Input a number
b) Initialize the product ( take 1 as initialize)
c) Check input as if input is 0 then print 1
d) Otherwise make a for loop from 2,n+1
Page 2 of 22
Elementary Programs
e) Take the product
f) Print the product outside the loop
Program :
n = int(input("enter a integer : "))
nfac =1
if n ==0:
print("factorial of ",n, "is ",nfac)
else:
for i in range(2,n+1):
nfac = nfac*i
print("factorial of ",n, "is",nfac)
Page 4 of 22
Elementary Programs
f) Take the sum of numbers when loop is
running and take also the square sum in
same loop.
g) Calculate mean and variance ‘
h) Print mean and variance
Program :
import math
n = int(input("enter the number of
observation : "))
sum_x = 0.0
sum_sqx = 0.0
for i in range(n):
x = float(input("enter value of x : "))
sum_x = sum_x + x
sum_sqx = sum_sqx + x**2
mean = sum_x/n
variance = sum_sqx/n - mean**2
print("mean of the given data is ",mean)
print("variance of the given data is
",variance)
6)Prime number :
Theory :
Prime numbers are those which are not divisible by any
number except 1 and the same number. For example, 3, 5, 7….
Here we check if a number is prime.
Algorithm :
a) input a number
Page 5 of 22
Elementary Programs
b) Make a for loop in range 2,n
c) Inside the loop check the number is divisible by any
number or not
d) If yes then print prime number
e) If no print non prime number
Program :
n = int(input("enter a integer : "))
if n>0:
for i in range(2,n):
if n % i == 0:
print(n, "is not a prime number
")
break # important
else:
print(n, "is a prime number ")
else:
print("error")
7) Palindrome Number:
Theory :
A Palindrome is some word or number or a phrase which when read
from the opposite end,
appears the same (reflection symmetry, example, 34543, symmetry
around 5 in the middle).
We here read a decimal number and find out its digits at different
places. After finding the
digits we construct the number taking the digits in the reverse order. For
example, given the
number 456, we construct the new number (this is not
palindrome number).
Page 6 of 22
Elementary Programs
Algorithm :
a) Input a number and store it
b) Reverse the number
c) If the main number is equal with reverse number
then print Palindrome number
d) Otherwise print not a palindrome number
Program :
def reverse(n):
rev = 0
a = n + 0
while a > 0:
rev = rev * 10 + a % 10
a = a // 10
print("reverse of", n, "is", rev)
if n == rev:
print(n, "is palindromic number")
else:
print(n, "is not a palindromic
number")
Page 7 of 22
Elementary Programs
considers 365 days in a year. So a leap day is regularly added
(to the shortest month February) in every 4 years to bring it in
sync with the Solar year. After 100 years our calendar does
have a round off by around 24 days.
In the Gregorian calendar three criteria must be taken into account to
identify leap years:
The year can be evenly divided by 4;
If the year can be evenly divided by 100, it is NOT a leap year, unless;
The year is also evenly divisible by 400. Then it is a leap year. This
means that in the Gregorian calendar, the years 2000 and 2400 are leap
years, while 1800,1900, 2100, 2200, 2300 and 2500 are NOT leap years.
Algorithm :
a) Input a year
b) Check if it is not divisible by 100 but divisible by 4
c) Check if it is divisible by 100 and 400
d) If true print leap year
e) Otherwise print not a leap year
Program :
year = int(input("enter the year : "))
if year % 100 != 0 and year % 4 ==0:
print(year, "is a leap year ")
elif year % 100 == 0 and year % 400 == 0:
print(year, "is a leap year ")
else :
print(year, "is not a leap year ")
Page 8 of 22
Elementary Programs
Stirling’s formula to find out logarithm of factorial of a large number: We
shall verify this. But since usually would be a very large number for a big
number, and so the computer would not be able to handle it and store
beyond some limit. Thus we use ∑ . *Here we avoid computing factorial!+
Algorithm :
a) Import math
b) Input a number
c) Start a do-loop to sum the logarithm of the integers
from 1 up to the given number.
d) Calculate the value from Stirling’s formula.
e) . Compare the results from (1) and (2)
Program :
import math
n = int(input("enter any positive integer :\t
"))
sum = 0
for i in range(1,n+1):
sum += math.log(i, 10)
print(sum)
acc = n*math.log(n, 10)- n
print(acc)
diff = abs(acc - sum)
print(n, diff, diff/sum)
Page 9 of 22
Elementary Programs
Algorithm :
a) Initialize first 2 terms of series as 0,1
b) Input the value of n of the n-th series
c) Check if n = 1 or 2 then print 0,1 respectively
d) If n > 2 start a for loop from 2,n
e) Make nth term as sum of last 2 terms
f) Print the hole series
Program :
def fib(n):
a = 0
b = 1
if n == 1:
print(a)
elif n == 2:
print(a)
print(b)
elif n > 2:
print(a)
print(b)
for i in range(2, n):
c = a + b
a = b
b = c
print(c)
gr = float(b/a)
print("golden ratio is ", gr)
Page 10 of 22
Elementary Programs
11) Combination formula :
Theory :
( )
( )
Algorithm:
a) Input n ,k
b) Make a factorial function
c) Make combination function
d) Print combination
Program :
def fac(x):
fac = 1
for i in range(2, x+1):
fac = fac*i
return fac
def combination(n,k):
if (n-k)< 0:
print("error ")
else:
nck = fac(n)/(fac(k)*fac(n-k))
print("combination ",nck)
n = int(input("enter n : "))
k = int(input("enter k : "))
combination(n, k)
Page 11 of 22
Elementary Programs
12) Bisection method for finding root
Page 12 of 22
Elementary Programs
Theory :
If a function is continuous between two limits and , and and
are of opposite
signs, then there exists a root between the and . The root is
between and if the following condition holds:
( ) ( )
The root can be approximated by the mid-point, That means
we bisect the interval.
Now in case, , then that is the root. If not, we search the root
in either of the intervals: [ or [ . In case, ,the root lies in this
half, otherwise the root lies in the other half. Then as before,
we bisect the new interval and repeat the process until the
root is found according to the desired accuracy.
Algorithm :
a) Input f(x) , a, b, error or accuracy level
b) Check if f(a)*f(b) >= 0 then no root exist
c) Else c = (a+b)/2
d) If f(x) = 0 then break the loop and print the root as x
e) If f(a)*f(c) < 0 then set b = c else a = c
f) The loop will stop when b-a < error
Program :
Page 13 of 22
Elementary Programs
def function(x):
f = x**3 - 2*x -5
return f
def bisection(a, b, error):
if function(a)*function(b)>=0.0:
print("error ")
else:
while abs(b-a)>=error:
c = (a+b)/2
if function(c) == 0:
print("root of the function
is ",c)
elif function(a)*function(c)<0.0:
b =c
else:
a=c
print("root of the function is ",c)
print(callable(c))
a = float(input("enter lower limit : "))
b = float(input("enter upper limit :"))
error = float(input("enter error or acuracy :
"))
bisection(a, b, error)
Page 14 of 22
Elementary Programs
, we can expand the function in Taylor’s series
around the point . Suppose, be the correct root, so that (
. Taylor Series expansion:
( ) ( ) (́ ) ( )
Neglecting higher order derivatives
( )
( )
So, a better approximation of the root can be written as
( )
( )
Algorithm :
a) Input f(x), f’(x), a, error
( )
b) Calculate and update x until | ( )|
( )
Program :
def function(x):
f = x**3 -2*x -5
return f
def derivative(x):
return 3*x**2 -2
def newton_method(x, error):
h = function(x)/derivative(x)
while abs(h)>= error:
h = function(x)/derivative(x)
x = x - h
print("value of root is ",x)
print(function(x))
x = float(input("enter value of x : "))
error = float(input("enter error : "))
newton_method(x, error)
Page 15 of 22
Elementary Programs
14) Exponential series :
Theory :
Algorithm :
a) Input number of terms or limit
b) Input x (float)
c) Initialize the power ,factorial , sum
d) Print value
Program :
limit = int(input("enter limit : "))
x = float(input("enter x : "))
power = 1
frac = 1
s = 1
for i in range(1,limit+1):
power = power*x
frac = frac*i
s = s + power/frac
print("value of exponential",x,"is", s)
Algorithm :
a) Input number of terms or limit
b) Input limit, x (in degree)
c) Change x from degree to radian
Page 16 of 22
Elementary Programs
d) Initialize power , sign, factorial and sum as x
e) Calculate sum by for loop
f) Print value
Program :
import math
limit = int(input("enter limit : "))
x = float(input("enter x in degree : "))
x = x*math.pi/180
p = 1
fac = 1
sign = -1
s = x
for i in range(3,limit+1,2):
x =x*sign
p = pow(x,i)
frac = fac*i*(i-1)
s =s + p/fac
print(s)
Page 17 of 22
Elementary Programs
Algorithm :
a) Input the function
b) Find 1st order derivative
c) Solve x
d) Calculate 2nd order derivative
e) If 2nd order derivative at x is >0 then print minima
f) If 2nd order derivative at x <0 then print maxima
g) If 2nd order derivative is = 0 then undetermined
Program :
def function(x):
f = x**2 - 3*x
return f
def first_derivative(x):
f =2*x -3
return f
def x_val(f):
x = f/2+ 1.5
return x
def double_dervative(x):
f = 2
return f
m = x_val(0)
if double_dervative(m)<0:
print("maxima at ", m,'and maximum value
of function is', function(m))
elif double_dervative(m)>0:
print("minima at ", m,"and minimum value
of function is", function(m))
else:
print("undetermined ")
Page 18 of 22
Elementary Programs
17) Bubble sorting(ascending order):
Theory :
Bubble Sort is the simplest sorting algorithm that works
by repeatedly swapping the adjacent elements if they
are in wrong order.
Algorithm :
a) Started with the 1st element of list(index 0) compare
the current element with next element.
b) If the current element is greater than next element
then swap.
c) Otherwise move to next element and do step 1
Page 19 of 22
Elementary Programs
Program :
list1 = []
n = int(input("enter number of terms of your
list : "))
for k in range(n):
num = int(input("enter numbers of your
list : "))
list1.append(num)
print("unsorted list is :", list1)
for j in range(len(list1)-1):
for i in range(len(list1) - 1):
if list1[i] > list1[i + 1]:
list1[i], list1[i + 1] = list1[i
+ 1], list1[i]
Theory :
The selection sort algorithm sorts an array by
repeatedly finding the minimum element (considering
ascending order) from unsorted part and putting it at
the beginning. The algorithm maintains two subarrays
in a given array.
1) The sub array which is already sorted.
2) Remaining sub array which is unsorted.
Page 20 of 22
Elementary Programs
In every iteration of selection sort, the minimum
element (considering ascending order) from the
unsorted sub array is picked and moved to the sorted
sub array
Algorithm :
a) Starting from the 1st element search for smallest(or
biggest) element in list of numbers.
b) Swap minimum (or maximum) number with 1st
element of list.
c) Take the sub list (ignore sorted part) and repeat
part 1 untill all the elements are sorted.
Page 21 of 22
Elementary Programs
Program :
list1 = []
n = int(input("enter number od terms of your
list : "))
for j in range(n):
num = int(input("enter number :"))
list1.append(num)
print("unsorted list : ", list1)
print(list1)
for i in range(len(list1)):
min_val = min(list1[i:])
min_index = list1.index(min_val)
list1[i], list1[min_index] =
list1[min_index], list1[i]
print("sorted list :", list1)
Page 22 of 22