python programming BTech lab manual
python programming BTech lab manual
Output:
ERROR!
File "<string>", line 3
return x
^
IndentationError: expected an indented block after 'if' statement on line 2
Output:
Enter a number: 2
Enter another number: 23
Finding the Maximum out of a: 2 and b: 23
23 is maximum
Exercise 2 – Operations
a) Write a program to compute distance between two points taking input from the
user (Pythagorean Theorem)
import math
x1=int(input("Enter x1: "))
y1=int(input("Enter y1: "))
x2=int(input("Enter x2: "))
y2=int(input("Enter y2: "))
d1 = (x2 - x1) * (x2 - x1)
d2 = (y2 - y1) * (y2 - y1)
res = math.sqrt(d1+d2)
print ("Distance between two points:",res);
Output:
Enter x1: 2
Enter y1: -4
Enter x2: -2
Enter y2: 4
Distance between two points: 8.94427190999916
b) Write a program that takes 2 numbers as command line arguments and prints its
sum.
x = int(input("Enter x: "))
y = int(input("Enter y: "))
print(x+y)
Output:
Enter x: 2
Enter y: 4
6
Exercise - 3 Control Flow
a) Write a Program for checking whether the given number is a even number or not.
num = int(input("Enter a number: "))
if (num % 2) == 0:
print(num,"is even")
else:
print(num,"is odd")
Output:
Enter a number: 22
22 is even
b) Using a for loop, write a program that prints out the decimal equivalents of 1/2, 1/3,
1/4, . . . ,1/10
a=1
for b in range(2,11):
print(f'{a}/{b}:',a/b)
Output:
1/2: 0.5
1/3: 0.3333333333333333
1/4: 0.25
1/5: 0.2
1/6: 0.16666666666666666
1/7: 0.14285714285714285
1/8: 0.125
1/9: 0.1111111111111111
1/10: 0.1
Output:
I am a Python developer
d) Write a program using a while loop that asks the user for a number, and prints a
countdown from that number to zero.
n = int(input("Enter a no. "))
while n>=0:
print(n,end=' ')
n=n-1
Output:
Enter a no.
10
10 9 8 7 6 5 4 3 2 1 0
Exercise 4 - Control Flow – Continued
a) Find the sum of all the primes below two million. Adding the previous two terms, each
new term in the Fibonacci sequence is generated. By starting with 1 and 2, the first 10
terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
n = 2000000
num1 = 0
num2 = 1
next_number = num2
Total = 0
def prime(num):
if num > 1:
for i in range(2, int(num/2)+1):
if (num % i) == 0:
return 0
else:
return num
return 0
print(Total)
Output:
544828
b) By considering the terms in the Fibonacci sequence whose values do not exceed four
million, find the sum of the even valued terms.
nterms = 4000000
n1, n2 = 0, 1
nth = n2
total=0
while nth <= nterms:
if nth%2==0:
total+=nth
nth = n1 + n2
n1 = n2
n2 = nth
print(total)
Output:
4613732
Output:
Element found at index: 3
2. Binary search
def binarySearch(array, x, low, high):
while low <= high:
mid = low + (high - low)//2
if array[mid] == x:
return mid
elif array[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1
Output:
Element is found at index 7
Output:
Sorted Array in Ascending Order:
[-9, -2, 0, 11, 45]
2. Insertion sort
def insertionSort(array):
for step in range(1, len(array)):
key = array[step]
j = step - 1
data = [9, 5, 1, 4, 3]
insertionSort(data)
print('Sorted Array in Ascending Order:')
print(data)
Output:
Sorted Array in Ascending Order:
[1, 3, 4, 5, 9]
Exercise - 5 – DS
a) Write a program to count the numbers of characters in the string and store them in a
dictionary data structure
str=input("Enter a String:")
dict = {}
for n in str:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
print (dict)
Output:
Enter a String:I am a Programmer
{'I': 1, ' ': 3, 'a': 3, 'm': 3, 'P': 1, 'r': 3, 'o': 1, 'g': 1, 'e': 1}
b) Write a program to use split and join methods in the string and trace a birthday with
a dictionary data structure.
people = {}
for i in range(2):
s1 = input("Enter the name: ")
s2 = input("Enter the DOB: ")
s2 = s2.split()
people[s1]=s2
Output:
Enter the name: Steven Smith
Enter the DOB: 2 June 1989
Enter the name: Robert Downey Jr.
Enter the DOB: April 4 1965
Steven Smith has DOB 2,June,1989
Robert Downey Jr. has DOB April,4,1965
Exercise – 6 DS – Continued
list1=[1,2,'cse',4,5]
list2=['khit',7,'cse',9]
Output:
The dictionary is------> {0: 1, 1: 2, 2: 'cse', 3: 4, 4: 5, 5: 'khit', 6: 7, 7: 'cse', 8: 9}
b) Write a program to count frequency of characters in a given file. Can you use
character frequency to tell whether the given file is a Python program file, C program
file or a text file?
import os
count =0
file=open("D:/a.txt")
print("count:",count)
filename,file_extension = os.path.splitext("D:/a.txt");
print("file_extension==",file_extension);
if(file_extension=='.py'):
print("its python program file");
elif(file_extension==".txt"):
print("its a txt file");
elif(file_==extension==".c"):
print("its a c program file");
Output:
count: 2
file_extension== .txt
its a txt file
Exercise - 7 Files
input_file=open('D:/a.txt','r')
Output:
atiG
b) Write a program to compute the number of characters, words and lines in a file.
k=open('D:/a.txt','r')
char,wc,lc=0,0,0
for line in k:
for i in range(0,len(line)):
char +=1
if(line[i]==' '):
wc+=1
if(line[i]=='\n'):
wc = wc+1
lc=lc+1
a) Write a function ball_collide that takes two balls as parameters and computes if they
are colliding. Your function should return a Boolean representing whether or not the
balls are colliding. Hint: Represent a ball on a plane as a tuple of (x, y, r), r being the
radius If (distance between two balls centers) <= (sum of their radii), then (they are
colliding)
import math
def ball_collide(x1,y1,r1,x2,y2,r2):
dist=math.sqrt((x2-x1)**2+(y2-y1)**2);
print("Distance b/w two balls:",dist)
center=dist/2;
print("Collision point",center);
r=r1+r2;
print("Sum of radious",r)
if(center<=r):
print("They are Colliding")
return True;
else:
print("Not Colliding")
return False;
c=ball_collide(4,4,3,2,2,3)
print(c)
c=ball_collide(100,200,20,200,100,10)
print(c)
Output:
Distance b/w two balls: 2.8284271247461903
Collision point 1.4142135623730951
Sum of radious 6
They are Colliding
True
Distance b/w two balls: 141.4213562373095
Collision point 70.71067811865476
Sum of radious 30
Not Colliding
False
b) Find the mean, median, and mode for the given set of numbers in a list.
Output:
Mean 19.9
Median 13.5
Mode 18
Exercise - 9 Functions – Continued
a) Write a function nearly_equal to test whether two strings are nearly equal. Two
strings a and bare nearly equal when a single mutation on b can generate a.
if(c*100>80):
print("Both Strings are similar")
print("a is mutation on b")
else:
print("Both Strings are Different")
Output:
Both Strings are similar
a is mutation on b
def dups():
for i in a:
d[i]=0
for i in a:
d[i] = d[i]+1
for i in d:
if d[i]>1:
ans.add(i)
a = [2,3,6,4,78,4,65,2,4,5]
ans = set()
d={}
dups()
print(ans)
Output:
{2, 4}
c) Write a function unique to find all the unique elements of a list.
def unique():
for i in a:
d[i]=0
for i in a:
d[i] = d[i]+1
for i in d:
if d[i]==1:
ans.add(i)
a = [2,3,6,4,78,4,65,2,4,5]
ans = set()
d={}
unique()
print(ans)
Output:
{65, 3, 5, 6, 78}
Exercise - 10 - Functions –Problem-Solving
def product(list):
p =1
for i in list:
p *= i
print(p)
arr= [1,2,3,4,5,6,7,8,9,10]
product(arr)
Output:
1
2
6
24
120
720
5040
40320
362880
3628800
b) Write a function reverse to reverse a list. Without using the reverse function.
def reverse(list):
size = len(arr)
size = -size
i=-1
while i>=size:
rev.append(arr[i])
i= i-1
size = -size
for i in range(size):
arr[i] = rev[i]
arr= [1,2,3,4,5,9,10]
rev = []
reverse(arr)
print(arr)
Output:
[10, 9, 5, 4, 3, 2, 1]
c) Write a function to compute gcd, lcm of two numbers. Each function shouldn’t
exceed one line.
import math
n1 = int(input("Enter n1 value:"))
n2 = int(input("Enter n2 value:"))
Output:
Enter n1 value:12
Enter n2 value:18
GCD value is: 6
LCM value is: 36