Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Lab Part 1

The document contains a series of Python programming exercises covering various topics such as calculating averages, checking for palindromes, implementing Fibonacci sequences, converting number bases, string analysis, sorting algorithms, Roman numeral conversion, and validating phone numbers. Each exercise includes code snippets, example outputs, and explanations of the expected functionality. The exercises are designed to help users practice and enhance their Python programming skills.

Uploaded by

manju15062019
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lab Part 1

The document contains a series of Python programming exercises covering various topics such as calculating averages, checking for palindromes, implementing Fibonacci sequences, converting number bases, string analysis, sorting algorithms, Roman numeral conversion, and validating phone numbers. Each exercise includes code snippets, example outputs, and explanations of the expected functionality. The exercises are designed to help users practice and enhance their Python programming skills.

Uploaded by

manju15062019
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 8

1a) Write a python program to find the best of two test average marks out of three

test’s marks
accepted from the user.
m1 = int (input("Enter the marks in the first test: "))
m2 = int (input("Enter the marks in second test: "))
m3 = int (input("Enter the marks in third test: "))

if (m1 > m2):


if (m2 > m3):
total = m1 + m2
else:
total = m1 + m3
elif (m1 > m3):
total = m1 + m2
else:
total = m2 + m3

Avg = total / 2
print ("The average of the best two test marks is: ",Avg)

Output:
Enter the marks in the first test: 40
Enter the marks in second test: 52
Enter the marks in third test: 89
The average of the best two test marks is: 70.5

1 b) Develop a Python program to check whether a given number is palindrome or not


and
also count the number of occurrences of each digit in the input number.

val = int(input("Enter a value : "))


str_val = str(val)
if str_val == str_val[::-1]:
print("Palindrome")
else:
print("Not Palindrome")

for i in range(10):
if str_val.count(str(i)) > 0:
print(str(i),"appears", str_val.count(str(i)), "times");
Output:
Enter a value : 565
Palindrome
5 appears 2 times
6 appears 1 times

2a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program which


accepts a
value for N (where N >0) as input and pass this value to the function. Display
suitable
error message if the condition for input value is not followed.

def fn(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fn(n-1) + fn(n-2)

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

if num > 0:
print("fn(", num, ") = ",fn(num) , sep ="")
else:
print("Error in input")

Output:
Enter a number : 5
fn(5) = 3

2b) Develop a python program to convert binary to decimal, octal to hexadecimal


using
functions.

def bin2Dec(val):
rev=val[::-1]
dec = 0
i = 0
for dig in rev:
dec += int(dig) * 2**i
i += 1

return dec

def oct2Hex(val):
rev=val[::-1]
dec = 0
i = 0

for dig in rev:


dec += int(dig) * 8**i
i += 1
list=[]
while dec != 0:
list.append(dec%16)
dec = dec // 16

nl=[]
for elem in list[::-1]:
if elem <= 9:
nl.append(str(elem))
else:
nl.append(chr(ord('A') + (elem -10)))
hex = "".join(nl)

return hex

num1 = input("Enter a binary number : ")


print(bin2Dec(num1))
num2 = input("Enter a octal number : ")
print(oct2Hex(num2))
Output:
Enter a binary number : 10111001
185
Enter a octal number : 64
34

Or

def decimal_into_binary(decimal_1):
decimal = int(decimal_1)
print ("The given decimal number", decimal, "in Binary number is:
", bin(decimal))
def decimal_into_octal(decimal_1):
decimal = int(decimal_1)
print ("The given decimal number", decimal, "in Octal number is:
", oct(decimal))
def decimal_into_hexadecimal(decimal_1):
decimal = int(decimal_1)

print ("The given decimal number", decimal, " in Hexadecimal number


is: ", hex(decimal))
decimal_1 = int (input (" Enter the Decimal Number: "))
decimal_into_binary(decimal_1)
decimal_into_octal(decimal_1)
decimal_into_hexadecimal(decimal_1)

Output:
Enter the Decimal Number: 12
The given decimal number 12 in Binary number is: 0b1100
The given decimal number 12 in Octal number is: 0o14
The given decimal number 12 in Hexadecimal number is: 0xc

3 a) Write a Python program that accepts a sentence and find the number of words,
digits,
uppercase letters and lowercase letters.

s = input("Enter a sentence: ")


w, d, u, l = 0, 0, 0, 0
l_w = s.split()

w = len(l_w)
for c in s:
if c.isdigit():
d = d + 1
elif c.isupper():
u = u + 1
elif c.islower():
l = l + 1

print ("No of Words: ", w)


print ("No of Digits: ", d)
print ("No of Uppercase letters: ", u)
print ("No of Lowercase letters: ", l)

Output:
Enter a sentence: hai how are u hdfdggxcFSfjKSJSKF
No of Words: 5
No of Digits: 0
No of Uppercase letters: 8
No of Lowercase letters: 20

3 b) Write a Python program to find the string similarity between two given
strings.

str1 = input("Enter String 1 \n")


str2 = input("Enter String 2 \n")

if len(str2) < len(str1):


short = len(str2)

long = len(str1)
else:
short = len(str1)
long = len(str2)

matchCnt = 0
for i in range(short):
if str1[i] == str2[i]:
matchCnt += 1

print("Similarity between two strings:")


print(matchCnt/long)

Output:
Enter String 1
hai
Enter String 2
haii
Similarity between two strings:
0.75

4a) Write a python program to implement insertion sort and merge sort using lists.
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r - m

L = [0] * (n1)

R = [0] * (n2)

for i in range(0, n1):


L[i] = arr[l + i]

for j in range(0, n2):


R[j] = arr[m + 1 + j]

# Merge the temp arrays back into arr[l..r]


i = 0 # Initial index of first subarray
j = 0 # Initial index of second subarray
k = l # Initial index of merged subarray
while i < n1 and j < n2:
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1

# Copy the remaining elements of L[], if there


# are any
while i < n1:
arr[k] = L[i]
i += 1
k += 1

# Copy the remaining elements of R[], if there


# are any
while j < n2:
arr[k] = R[j]
j += 1
k += 1

# l is for left index and r is right index of the


# sub-array of arr to be sorted

def insertion_sort(alist):
for i in range(1, len(alist)):
temp = alist[i]
j = i - 1
while (j >= 0 and temp < alist[j]):
alist[j + 1] = alist[j]
j = j - 1
alist[j + 1] = temp

alist = input('Enter the insertion list of numbers: ').split()


alist = [int(x) for x in alist]
insertion_sort(alist)
print('Sorted list: ', end='')
print(alist)

def mergeSort(arr, l, r):

if l < r:

# Same as (l+r)//2, but avoids overflow for


# large l and h
m = l+(r-l)//2

# Sort first and second halves


mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)

# Driver code to test above


arr = input('Enter the merge list of numbers: ').split()
arr = [int(x) for x in arr]
n = len(arr)

mergeSort(arr, 0, n-1)
print("\n\nSorted array is")
for i in range(n):
print("%d" % arr[i],end=" ")

Output:
Enter the insertion list of numbers: 12 02 65 86 75 45
Sorted list: [2, 12, 45, 65, 75, 86]
Enter the merge list of numbers: 23 25 81 01
Sorted array is
1 23 25 81

4 b) Write a program to convert roman numbers in to integer values using


dictionaries.

def r2d(rs):
roman_dict ={'I': 1, 'V': 5, 'X': 10, 'L': 50,
'C': 100, 'D': 500, 'M': 1000}
romanBack = list(rs)[::-1]
value = 0

rightVal = roman_dict[romanBack[0]]
for numeral in romanBack:
leftVal = roman_dict[numeral]

if leftVal < rightVal:


value -= leftVal
else:
value += leftVal
rightVal = leftVal
return value

rs = input("Enter a Roman Number : ")


print(r2d(rs))
Output:
Enter a Roman Number : III
3

5 a) Write a function called isphonenumber () to recognize a pattern 415-555-4242


without using regular expression and also write the code to recognize the same
pattern
using regular expression.

With Regular Expression:


import re
def phno(numStr):
ph_no_pattern = re.compile(r'^\d{3}-\d{3}-\d{4}$')
if ph_no_pattern.match(numStr):
return True
else:
return False
ph_num = input("Enter a phone number : ")
if phno(ph_num):
print("Valid phone number")
else:
print("Invalid phone number")
Without Regular Expression:
def pn(numStr):
if len(numStr) != 12:
return False
for i in range(len(numStr)):
if i==3 or i==7:
if numStr[i] != "-":
return False
else:
if numStr[i].isdigit() == False:
return False
return True
ph_num = input("Enter a phone number : ")
if pn(ph_num):
print("Valid phone number")

else:
print("Invalid phone number")

Output:
Enter a phone number : 781-140-6868
Valid phone number
5 b) Develop a python program that could search the text in a file for phone
numbers
(+919900889977) and email addresses (sample@gmail.com).
Procedure:
 At first step create a txt file in the directory where your python files are
saving in a
directory .
 give the exact url for file name where actually file is situated.
import re

# Define the regular expression for phone numbers


phone_regex = re.compile(r'\+\d{2}-\d{10}')
email_regex = re.compile(r'[A-Za-z0-9._]+@[A-Za-z0-9]+\.[A-Z|a-z]{2,}')
# Open the file for reading
with open("C:\\Users\\Student\\info.txt","r") as f:
# Loop through each line in the file
for line in f:
# Search for phone numbers in the line
matches = phone_regex.findall(line)
# Print any matches found
for match in matches:
print(match)

matches = email_regex.findall(line)
# Print any matches found

for match in matches:


print(match)
Output:
+91-7894561230
abcd123@gmail.com

You might also like