0% found this document useful (0 votes)
5 views10 pages

Python-Ece Lab Manual

The document is a lab manual for Python programming at the Universal College of Engineering & Technology, covering various programming tasks across eight weeks. Each week includes multiple programming exercises, such as generating even numbers, ASCII value calculations, sorting strings, and implementing algorithms like round robin and binary search. The manual emphasizes practical coding skills and problem-solving in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views10 pages

Python-Ece Lab Manual

The document is a lab manual for Python programming at the Universal College of Engineering & Technology, covering various programming tasks across eight weeks. Each week includes multiple programming exercises, such as generating even numbers, ASCII value calculations, sorting strings, and implementing algorithms like round robin and binary search. The manual emphasizes practical coding skills and problem-solving in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIVERSAL COLLEGE OF ENGINEERING & TECHNOLOGY

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

PYTHON ROGRAMMING LAB


LAB MANUAL

[Link] – I semester

UNIVERSAL COLE-LEGE OF ENGINEERING AND TECHNOLOGY


(Approved by A.I.C.T.E, Affiliated to JNTUK, Kakinada)
PERECHERLA, GUNTUR-522438.
WEEK-I:
A) Write a program to get the list of even numbers upto a given number.

n = int(input('Enter your limit? \n'))


for x in range(0, n):
if (x % 2 == 0):
print(x)

out put:
Enter your limit?
10
0
2
4
6
8

B) Write a program to get the ASCII distance between two characters.


a=input("enter first character")
print("The ASCII value of '" + a + "' is", ord(a))
b=input("enter second character")
print("The ASCII value of '" + b + "' is", ord(b))

out put:
enter first character: a
The ASCII value of 'a' is 97
enter second character: y
The ASCII value of 'y' is 121

C) Write a program to get the binary form of a given number.

def binary(num):
returnint(bin(num).split('0b')[1])
if __name__ == "__main__" :
x = int(input("enter any number"))
binary_x = binary(x)
print(binary_x)

out put:
enter any number10
1010

D) Write a program to convert base 36 to octal.

n=int(input("enter any value"))


print("The decimal value of", n, "is:")
print(bin(n), "in binary.")
print(oct(n), "in octal.")
print(hex(n), "in hexadecimal.")
out put:
enter any value10
The decimal value of 10 is:
0b1010 in binary.
0o12 in octal.
0xa in hexadecimal.
WEEK-II:
a)Write a program to get the number of vowels in the input string (No control flow allowed)

defCheck_Vow(string, vowels):

final = [each for each in string if each in vowels]

print(len(final))

print(final)

string = input("enter the string")

vowels = "AaEeIiOoUu"

Check_Vow(string, vowels);

out put:
enter the stringwelcome
3
['e', 'o', 'e']

b)Write a program to check whether a given number has even number of 1's in its binary representation (No
control flow, thenumbercanbein any base)

def test(num):

ones = bin(num). replace("0b", "").count('1')

zeros = bin(num). replace("0b", "").count('0')

return "Number of zeros: " + str(zeros) + ", Number of ones: " + str(ones);

n = int(input("enter number"));

print("Original number: ",n);

print("Number of ones and zeros in the binary representation of the said number:");

print(test(n));

n = 1234;

print("\nOriginal number: ",n);

print("Number of ones and zeros in the binary representation of the said number:");

print(test(n));

out put:
enter number10
Original number: 10
Number of ones and zeros in the binary representation of the said number:
Number of zeros: 2, Number of ones: 2

Original number: 1234


Number of ones and zeros in the binary representation of the said number:
Number of zeros: 6, Number of ones: 5
c)Write a program to sort given list of strings in the order of their vowel counts.

defisVowel(ch):
ch = [Link]();
return (ch == 'A' or ch == 'E'orch == 'I' or ch == 'O'orch == 'U');
defcountVowels(string):
count = 0;
for i in range(len(string)):
if (isVowel(string[i])):
count += 1;
return count;
defsortArr(arr, n):
vp = [];
for i in range(n):
[Link]((countVowels(arr[i]),arr[i]));
[Link]()
for i in range(len(vp)):
print(vp[i][1], end= " ");
if __name__ == "__main__":
arr = [ "lmno", "pqrst","aeiou", "xyz" ];
n = len(arr);
sortArr(arr, n);
output:
======================== RESTART: D:/siva parvathi/[Link] =======================
pqrst xyz lmnoaeiou

WEEK-III:
a). Write a program to return the top 'n' most frequently occurring chars and their respectivecounts.( E.g.
aaaaaabbbbcccc, 2 should return [(a5) (b 4)])

text = "abbbaaaa"
dict = {}
for lines in text:
for char in lines:
dict[char] = [Link](char, 0) + 1
print(dict)

output:
RESTART: D:/siva parvathi/[Link] ==============
{'a': 5, 'b': 3}
b) Write a program to convert a given number into a given base.
Note: Convert the given number into a string in the given base. Valid baseis 2<=base <=36 Raise exceptions
similar to how int ("XX", YY) does (play in the console to find what errors it raises). Handle negative
numbers just like binandoct do.

n = int(input("enter a number in decimal : "))

b = int(input("enter base between 2, 36 : "))

d= {0:"0", 1:"1", 2:"2", 3:"3", 4:"4", 5:"5", 6:"6", 7:"7", 8:"8", 9:"9", 10:"A", 11:"B",

12:"C", 13:"D", 14:"E", 15:"F", 16:"G", 17:"H", 18:"I", 19:"J", 20:"K", 21:"L", 22:"M", 23:"N",

24:"O", 25:"P", 26:"Q", 27:"R", 28:"S", 29:"T", 30:"U", 31:"V", 32:"W", 33:"X", 34:"Y", 35:"Z"}
def base_number(n, b):

s = ""

print("number and base are : ",n,b)

if(b==10):

return str(n)

while(n>0):

#print(n)

s+=d[n%b]

n=n//b

return s[::-1]

print(base_number(n, b))

out put:
enter a number in decimal : 1500

enter base between 2, 36 : 20

number and base are : 1500 20

3F0

WEEK-IV:
a) Write a program to convert a given iterable into a list. (Using iterator)
a=input('enter string')
list=[i for i in a]
print(list)
output:
enter string hai how are u

[' ', 'h', 'a', 'i', ' ', 'h', 'o', 'w', ' ', 'a', 'r', 'e', ' ', 'u']

b)Write a program to implement user defined map() function.


Note: This function implements a map. It goes through the iterable and applies funcon each of the elements
and returns a list of results.
Don't use a for loop or the built-in map function. Use exceptions, while loop and iter.

def square(n):
return n*n
my_list = [2,3,4,5,6,7,8,9]
updated_list = map(square, my_list)
print(updated_list)
print(list(updated_list))

output:
<map object at 0x00000257E360A9B0>
[4, 9, 16, 25, 36, 49, 64, 81]
c)Write a program to generate an infinite number of even numbers (Use generator)

defall_even():
n=0
while True:
yield n
n += 2
evenNums = all_even()
n = int(input("Enter the even numbers range : "))
for i in range(n):
print(next(evenNums))

output:
Enter the even numbers range : 10
0
2
4
6
8
10
12
14
16
18

d)Write a program to generate an infinite number of even numbers(use only comprehension)

num_list = list(map(int,input("enter space seperated numbers : ").split()))


even_nums = [n for n in num_list if n%2 == 0]
print(even_nums)

output:
enter space seperated numbers : 2 1 4 5 6 3 45 44 23 36 76 56
[2, 4, 6, 44, 36, 76, 56]

WEEK-V:
Write a program to implement round robin. Note: This routine to take a variable number of sequences and
return elements from them in round robin till each sequence is exhausted. I fone of the input sequences is
infinite, this is also infinite.
e.g if input is [1,2,3], (4,5) -> yield 1,4,2,5,3 one after the other. Use exception control and comprehensions to
write elegant code.
Hint: This requires you to use understand variable arguments, lists, listcopy, comprehensions, iterators,
generators, exception handling, control

if __name__ == '__main__':
print("Enter Total Process Number: ")
total_p_no = int(input())
total_time = 0
total_time_counted = 0
proc = []
wait_time = 0
turnaround_time = 0
for _ in range(total_p_no):
print("Enter process arrival time and burst time")
input_info = list(map(int, input().split(" ")))
arrival, burst, remaining_time = input_info[0], input_info[1], input_info[1]
[Link]([arrival, burst, remaining_time, 0])
total_time += burst
print("Enter time quantum")
time_quantum = int(input())
whiletotal_time != 0:
for i in range(len(proc)):
ifproc[i][2] <= time_quantum and proc[i][2] >= 0:
total_time_counted += proc[i][2]
total_time -= proc[i][2]
proc[i][2] = 0
elifproc[i][2] > 0:
proc[i][2] -= time_quantum
total_time -= time_quantum
total_time_counted += time_quantum
ifproc[i][2] == 0 and proc[i][3] != 1:
wait_time += total_time_counted - proc[i][0] - proc[i][1]
turnaround_time += total_time_counted - proc[i][0]
proc[i][3] = 1
print("\nAvg Waiting Time is ", (wait_time * 1) / total_p_no)
print("Avg Turnaround Time is ", (turnaround_time * 1) / total_p_no)

output:
Enter Total Process Number:
3
Enter process arrival time and burst time
23
Enter process arrival time and burst time
23
Enter process arrival time and burst time
12
Enter time quantum4

Avg Waiting Time is 1.3333333333333333


Avg Turnaround Time is 4.0

WEEK-VI:
a) Write a program to sort words in a file and put them in another file. The output file shouldhave only lower
case words, so any upper case words from source must be lowered. (Handle exceptions)

s=input("enter input text: ")


input_file = open(r'C:\Users\ucet\Desktop\[Link]','w')
input_file.write(s)
input_file.close()
input_file = open(r'C:\Users\ucet\Desktop\[Link]','r')
output_file = open(r'C:\Users\ucet\Desktop\[Link]','w')
input_file_contents = sorted(input_file.read().split())
for word in input_file_contents:
output_file.write([Link]())
output_file.write(" ")
input_file.close()
output_file.close()
output:
>>>
enter input text: welcome to ucet
>>>
Input file

welocme to ucet
output file

to ucet welocme

b) Write a program return a list in which the duplicates are removed and the items are sorted from a given
input list of strings.

strs = input("enter the list")


print ("The original list is :\n " + str(strs))
res = []
for i in strs:
if i not in res:
[Link](i)
print ("The list after removing duplicates :\n " + str(res))
[Link]()
print("the sorted list after the removing duplicates:\n"+str(res))
output:
>>>
enter the list welcome to ucet
The original list is :
welcome to ucet
The list after removing duplicates :
['w', 'e', 'l', 'c', 'o', 'm', ' ', 't', 'u']
the sorted list after the removing duplicates:
[' ', 'c', 'e', 'l', 'm', 'o', 't', 'u', 'w']
>>>

WEEK-VII:
a. Write a program to test whether given strings are anagrams are not.
def check(s1, s2):
if(sorted(s1)== sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")
s1 ="listen"
s2 ="silent"
check(s1, s2)
output:
>>>
=============================== RESTART: D:/[Link] ==============================
The strings are anagrams.
>>>

b. Write a program to implement left binary search.


Note: Left binary search returns the left mostelement when a search key repeats.
[Link] inputis [1,2,3,3,4,4,5] and I search 3, it should return 2 as index 2 is the left most occurrence of 3.

def left_binary_search(arr, a, low, high):


if high >= low:
mid = low + (high - low)//2
# If found at mid, then return it
if arr[mid] == a:
while(mid>=0 and arr[mid-1]==a):
mid-=1
return mid
# Search the left half
elif arr[mid] > a:
return left_binary_search(arr, a, low, mid-1)
# Search the right half
elif arr[mid] < a:
return left_binary_search(arr, a, mid + 1, high)
else:
return -1
arr = list(map(int, input("enter space seperated sorted list elements : ").split()))
ele = int(input("enter element to be searched : "))
print("the element is present at index : {}".format(left_binary_search(arr, ele, 0, len(arr)-1)))

output:
enter space seperated sorted list elements : 1 2 2 3 3 3 4 5 6
enter element to be searched : 3
the element is present at index : 3

WEEK-VIII:
a. Write a class Person with attributes name, age, weight (kgs), height (ft) and takes them through the
constructor and exposes a method get_bmi_result() which returns one of "underweight", "healthy", "obese".

class Person:
def __init__(self, name, age, weight, height):
[Link] = name
[Link] = age
[Link] = weight
[Link] = height

def get_bmi_result(self):
height_to_meters = [Link]/3.28
#BMI = weight/(height*height)
val = [Link]/(height_to_meters**2)
if(18.5 <= val <= 25):
return "healthy"
elif(val>25):
return "obese"
return "underweight"

name = input("enter person name : ")


age = int(input("enter person age : "))
weight = float(input("enter person weight in KGs : "))
height = float(input("enter person height Feet : "))

person_obj = Person(name, age, weight, height)


print("The person BMI is : ",person_obj.get_bmi_result())

output:
enter person name : siva
enter person age : 40
enter person weight in KGs : 55
enter person height Feet : 5.3
The person BMI is : healthy
b. Write a program to convert the passed in positive integer number into its prime factorization form.
Note: If number = a1 ^ p1 * a2 ^ p2 ... where a1, a2 are primes and p1, p2 are powers >=1 then were
present that using lists and tuples in python as [(a1,p1),(a2,p2), ...] e.g.[(2,1),(5,1)] is the correct prime
factorization of 10.

# n is the number to be factorized


# this list holds your desired answer
# this variable iterates over prime
n=int(input("enter n value"))
prime_factors=[]
start = 2
while start*start <= n:
if n % start == 0:
expo = 0
while n % start == 0:
expo = expo + 1
n = n / start
prime_factors.append([start,expo])
start=start+1
if n > 1:
prime_factors.append([n,1])
print(prime_factors))
out put:
enter n value10
[[2, 1], [5, 1]]

You might also like