0% found this document useful (0 votes)
3 views22 pages

Python For Exam Sem 1

The document outlines various elementary programming concepts and algorithms, including calculating the area of a triangle using Heron's formula, checking if a number is odd or even, finding the factorial of a number, and determining if a number is a perfect square. It also covers more advanced topics such as the Fibonacci series, prime numbers, leap years, and methods for finding roots of equations like the Bisection method and Newton-Raphson method. Each section includes a theory explanation, algorithm steps, and corresponding Python code examples.

Uploaded by

swarajitdhar6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views22 pages

Python For Exam Sem 1

The document outlines various elementary programming concepts and algorithms, including calculating the area of a triangle using Heron's formula, checking if a number is odd or even, finding the factorial of a number, and determining if a number is a perfect square. It also covers more advanced topics such as the Fibonacci series, prime numbers, leap years, and methods for finding roots of equations like the Bisection method and Newton-Raphson method. Each section includes a theory explanation, algorithm steps, and corresponding Python code examples.

Uploaded by

swarajitdhar6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Elementary Programs

1) Area of a Triangle by Heron’s Formula:

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

2) To find if a number is Odd or Even :


Theory :
To find a given number is odd or even. Check the modulus with 2 is zero
or not.
Algorithm :
a) Input a number
b) Find modulus with 2
c) Check if modulus is zero then print even number
d) Otherwise print odd number

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)

4) Perfect square number :


Theory :
This is to check if a given number is a perfect square, for example, . So
we take a number and calculate its square root, the result will be an
integer when perfect square, else a real number. If the result is a real
number (and not an integer), the integer part squared again, will not
match with the original number. In case of perfect square number, this
matches.
Algorithm :
a) Import math
b) Input a number
c) Take square root and keep its integer part
d) Square the integer part
e)Check the square number is same as input
number or not
Page 3 of 22
Elementary Programs
Program :
import math
n = int(input("enter a integer : "))
a = math.sqrt(n)
b = int(a)
if b**2 == n:
print(n,"is a perfect square number and
its square root is",a)
else:
print(n,"is not a perfect square number
and is square root is",a)

5)Mean and variance of a given data :


Theory :
̅ ∑ and
∑ ( ∑ )
Algorithm :
a) Import math
b) First input how many number user want
to give. That is n (here)
c) Initialize the sum as 0.0
d) Initialize the square of the sum ( ) as
0.0
e)Using for loop collect the inputs from user

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")

num = int(input('enter a number '))


print(reverse(num))

8) To check leap year :


Theory :

Earth takes 365 days, 5 hours, 48 minutes, and 45 seconds – to


revolve once around the Sun. But our Gregorian calendar

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 ")

9) Stirling’s Approximation Formula:


Theory :

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)

10) Fibonacci series :


Theory :
Fibonacci numbers are the series of numbers where each number is the
sum of two previous
numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89….
The rule:

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)

num = int(input("enter nth value of fibonacci


series ;"))
if num < 0:
print("error")
else:
print(fib(num))

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)

13) Newton-Raphson Method:


Theory :This is method is an improved version of the other two
methods we discussed so far. If is the approximate root of the
equation: f(x) =0

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)

15) Sin(x) series :


Theory :

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)

16) Maxima /Minima for a second degree equation


Theory :
If f(x) is polynomial of 2nd degree then we first find 1st
order derivative of f(x) and equate it with 0
Net we find 2nd order derivative at the solution point of
1st order derivative.
If 2nd order derivative is positive then function is minima
at this point and if negative then the function is maxima
otherwise undetermined.

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]

print("sorted list will be ", list1)

Same for descending order just replace ‘>’ to ‘<’

18) Selection sorting:

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

You might also like