[go: up one dir, main page]

0% found this document useful (0 votes)
36 views23 pages

Document From SHIRSHA

Uploaded by

rrrroptv
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)
36 views23 pages

Document From SHIRSHA

Uploaded by

rrrroptv
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/ 23

PYTHON LAB ASSIGNMENT

By

Name: Dipankar Karmakar


Stream: Computer Science
Engineering
Roll No.: 11200218039
Registration No.: 181120110060
Subject: Programming with Python
Subject code: PCC-CS393

GOVERNMENT COLLEGE OF
ENGINEERING AND LEATHER
TECHNOLOGY
Problem 1: Write a method which can calculate square
value of number?
Code:
#question1
import math
num=int(input("Enter a number: "))
print(math.pow(num,2))
output:
Enter a number: 5
25.0

Problem 2: Define a function that can receive two integral


numbers in string form and compute their sum and then
print it in console?
Code:
#question2
def calculateSum (a,b):
s = int(a) + int(b)
return s
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
sum = calculateSum (num1, num2)
print ("Sum = ", sum)
Output:
Enter a number: 390
Enter another number: 650
Sum = 1040
Problem 3: Define a function that can accept two strings as
input and concatenate them and then print it in console.
Code:
#question3
def concatinate (a,b):
s = str(a) + str(b)
return s
str1 = input("Enter a string: ")
str2 = input("Enter another string: ")
con = concatinate(str1,str2)
print("Concatinated string= ",con)
Output:
Enter a string: 1 2
Enter another string: 3 4
Concatinated string= 1 2 3 4

Problem 4: Define a function that can accept two strings as


input and print the string with maximum length in console.
If two strings have the same length, then the function
should print all strings line by line.
Code:
#quetion4
def printLonger(a,b):
len1 = len(a)
len2 = len(b)
if len1>len2:
s = print(a)
elif len1<len2:
s = print(b)
else:
s = print(a)
s = print(b)
return s
str1 = input("Enter a string: ")
str2 = input("Enter another string: ")
print(printLonger(str1,str2))
Output:
Enter a string: 1 2 3
Enter another string: 1 2 3 4
1 2 3 4
None

Problem 5: Define a function that can accept an integer


number as input and print the “It is an even number” if the
number is even, otherwise print “It is an odd number”.
Code:
#question5
def isEvenorOdd(a):
if a%2 is 0:
s = print("It is an even number.")
else:
s = print("It is an odd number.")
return s
num = int(input("Enter a number: "))
print(isEvenorOdd(num))
Output:
Enter a number: 25
It is an odd number.
None
Problem 6: Define a function which can print a dictionary
where the keys are numbers between 1 and 3 (both
included) and the values are square of keys.
Code:
#question6
def dictionary(d):
d=dict()
for x in range(1,4):
d[x]=x**2
s = print(d)
return s
a = dict()
print(dictionary(a))
Output:
{1: 1, 2: 4, 3: 9}
None

Problem 7: Define a function which can print a dictionary


where the keys are numbers between 1 and 20 (both
included) and the values are square of keys.
Code:
#question7
def dictionary(d):
d=dict()
for x in range(1,21):
d[x]=x**2
s = print(d)
return s
a = dict()
print(dictionary(a))
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64,
9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196,
15: 225, 16: 256, 17: 289, 18: 324, 19: 361, 20: 400}
None

Problem 8: Define a function which can generate and print


a list where the values are square of numbers between 1
and 20 (both included).
Code:
#question8
def printValues():
l = list()
for i in range(1,21):
l.append(i**2)
print(l)
printValues()
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169,
196, 225, 256, 289, 324, 361, 400]

Problem 9: With a given tuple (1,2,3,4,5,6,7,8,9,10), write a


program to print the first half values in one line and the last
half values in one line.
Code:
#question9
t = (1,2,3,4,5,6,7,8,9,10)
print("The original tuple is= ",t[:10])
print("First half of the tuple is= ",t[0:5])
print("Second half of the tuple is= ",t[5:10])
Output:
The original tuple is= (1, 2, 3, 4, 5, 6, 7, 8, 9,
10)
First half of the tuple is= (1, 2, 3, 4, 5)
Second half of the tuple is= (6, 7, 8, 9, 10)

Problem 10: Write a program which can map() to make a


list whose elements are square of elements in
[1,2,3,4,5,6,7,8,9,10].
Code:
#question10
def square(n):
return n**2
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = map(square, numbers)
print(list(result))
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Problem 11: Write a program which can map() and filter() to


make a list whose elements are square of even number in
[1,2,3,4,5,6,7,8,9,10].
Code:
#question11
seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = filter(lambda x: x % 2 == 0, seq)
def square(n):
return n**2
res=map(square,result)
print(list(res))
Output:
[4, 16, 36, 64, 100]

Problem 12: Write a program which can filter() to make a


list whose elements are even number between 1 and 20
(both included).
Code:
#question12
res=filter(lambda i: i % 2 == 0, range(1,21))
print(list(res))
Output:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Problem 13: Define a class named Circle which can be


constructed by a radius. The Circle class has a method
which can compute the area.
Code:
#question13
class Circle():
def __init__(self, r):
self.radius = r
def area(self):
return self.radius**2*3.14
NewCircle = Circle(8)
print("Area of the circle is= ",NewCircle.area())
Output:
Area of the circle is= 200.96

Problem 14: Define a class named Rectangle which can be


constructed by a length and width. The Rectangle class has
a method which can compute the area.
Code:
#question14
class Rectangle():
def __init__(self, l, w):
self.length = l
self.width = w
def rectangle_area(self):
return self.length*self.width
newRectangle = Rectangle(12, 10)
print("Area of the rectangle is=
",newRectangle.rectangle_area())
Output:
Area of the rectangle is= 120

Problem 15: Define a class named Shape and its subclass


Square. The Square class has an init function which takes a
length as argument. Both classes have an area function
which can print the area of the shape where Shape's area
is 0 by default.
Code:
#question15
class shape:
def _init_(self,ar):
self.ar=0
def area(self):
print(ar)
class Square(shape):
def _init_(self,l):
self.l=l
def area(self):
ar=l**2
print(ar)
l=int(input("Enter length: "))
x=Square()
x.area()
Output:
Enter length: 8
64

Problem 16: Write a program which can compute the


factorial of a given numbers. The results should be printed
in a comma-separated sequence on a single line.
Code:
#question16
a=[]
b=[]
num=int(input("Enter the number of inputs: "))
for i in range(num):
a.append(int(input("Enter the number whose
factorial value is to be printed: ")))
def fact(a):
b=[]
for i in a:
f=1
for j in range(1,i+1):
f*=j
b.append(f)
return b
b=fact(a)
for i in b:
print(i,end=",")
Output:
Enter the number of inputs: 3
Enter the number whose factorial value is to be
printed: 8
Enter the number whose factorial value is to be
printed: 9
Enter the number whose factorial value is to be
printed: 12
40320,362880,479001600,

Problem 17: Write a program that calculates and prints the


value according to the given formula:
Q = Square root of [(2 * C * D)/H]
Following are the fixed values of C and H:
C is 50. H is 30.
D is the variable whose values should be input to your
program in a comma-separated sequence.
Code:
#question17
import math
val=input("Enter some comma seperated inputs: ")
l=[]
dup=[]
list=val.split(",")
for i in list:
l.append(int(i))
def fn(n,dup):
val=int(math.sqrt((2*50*n)/30))
dup.append(val)
for i in l:
fn(i,dup)
for i in dup:
print(i,end=",")
Output:
Enter some comma seperated inputs: 100,150,180
18,22,24,

Problem 18: With a given integral number n, write a


program to generate a dictionary that contains (i, i*i) such
that is an integral number between 1 and n (both included)
and then the program should print the dictionary.
Code:
#question18
n = int(input("Enter no. of inputs= "))
d = dict()
for i in range(1,n+1):
d[i] = i*i
print(d)
Output:
Enter no. of inputs= 8
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
Problem 19: Write a program which takes 2 digits, X,Y as
input and generates a 2-dimensional array. The element
value in the i-th row and j-th column of the array should be
i*j.
Code:
#question19
input_str = input()
dimensions=[int(x) for x in input_str.split(',')]
rowNum=dimensions[0]
colNum=dimensions[1]
multilist = [[0 for col in range(colNum)] for row in
range(rowNum)]
for row in range(rowNum):
for col in range(colNum):
multilist[row][col]= row*col
print(multilist)
Output:
3,5
[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]

Problem 20: Write a program that accepts a comma


separated sequence of words as input and prints the words
in a comma-separated sequence after sorting them
alphabetically.
Code:
#question20
items=[x for x in input("enter data to sort
").split(',')]
items.sort()
print ("Sorted data are ",','.join(items))
Output:
Enter data to sort without,hello,bag,world
Sorted data are bag,hello,without,world

Problem 21: Write a program which accepts a sequence of


comma separated 4 digit binary numbers as its input and
then check whether they are divisible by 5 or not. The
numbers that are divisible by 5 are to be printed in a
comma separated sequence.
Code:
#question21
items = []
num = [x for x in input().split(',')]
for p in num:
x = int(p, 2)
if not x%5:
items.append(p)
print(','.join(items))
Output:
0100,0011,1010,1001
1010

Problem 22: Write a program, which will find all such


numbers between 1000 and 3000 (both included) such that
each digit of the number is an even number.
Code:
#question22
values=[]
for x in range(1000,3000):
s=str(x)
if (int(s[0]) %2 == 0) and (int(s[1]) %2 == 0)
and (int(s[2]) %2 == 0) and (int(s[3]) %2 == 0):
values.append(s)
print (",".join(values))
Output:
2000,2002,2004,2006,2008,2020,2022,2024,2026,2028,204
0,2042,2044,2046,2048,2060,2062,2064,2066,2068,2080,2
082,2084,2086,2088,2200,2202,2204,2206,2208,2220,2222
,2224,2226,2228,2240,2242,2244,2246,2248,2260,2262,22
64,2266,2268,2280,2282,2284,2286,2288,2400,2402,2404,
2406,2408,2420,2422,2424,2426,2428,2440,2442,2444,244
6,2448,2460,2462,2464,2466,2468,2480,2482,2484,2486,2
488,2600,2602,2604,2606,2608,2620,2622,2624,2626,2628
,2640,2642,2644,2646,2648,2660,2662,2664,2666,2668,26
80,2682,2684,2686,2688,2800,2802,2804,2806,2808,2820,
2822,2824,2826,2828,2840,2842,2844,2846,2848,2860,286
2,2864,2866,2868,2880,2882,2884,2886,2888

Problem 23: The numbers obtained should be printed in a


comma-separated sequence on a single line. Write a
program that computes the value of a+aa+aaa+aaaa with
a given digit as the value of a.
Code:
#question23
a = input()
n1 = int( "%s" % a )
n2 = int( "%s%s" % (a,a) )
n3 = int( "%s%s%s" % (a,a,a) )
n4 = int( "%s%s%s%s" % (a,a,a,a) )
print(n1+n2+n3+n4)
Output:
9
11106
Problem 24: Use a list comprehension to square each odd
number in a list. The list is input by a sequence of comma-
separated numbers.
Code:
#question24
values = input()
numbers = [x for x in values.split(",") if
int(x)%2!=0]
print(",".join(numbers))
Output:
1,2,3,4,5,6,7,8,9
1,3,5,7,9

Problem 25: Write a program that computes the net amount


of a bank account based a transaction log from console
input. The transaction log format is shown as following:
D 100
W 200
D means deposit while W means withdrawal.
Code:
#question25
net_amount = 0
while True:
str = input ("Enter transaction: ")
transaction = str.split(" ")
type = transaction [0]
amount = int (transaction [1])
if type=="D" or type=="d":
net_amount += amount
elif type=="W" or type=="w":
net_amount -= amount
else:
pass
str = input ("want to continue (Y for yes) : ")
if not (str[0] =="Y" or str[0] =="y") :
break
print ("Net amount: ", net_amount)
Output:
Enter transaction: D 300
want to continue (Y for yes) : Y
Enter transaction: D 300
want to continue (Y for yes) : Y
Enter transaction: W 200
want to continue (Y for yes) : Y
Enter transaction: D 100
want to continue (Y for yes) : N
Net amount: 500

Problem 26: A website requires the users to input username


and password to register. Write a
program to check the validity of password input by users.
Following are the criteria for checking the password:
1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
1. At least 1 letter between [A-Z]
3. At least 1 character from [$#@]
4. Minimum length of transaction password: 6
5. Maximum length of transaction password: 12
Your program should accept a sequence of comma
separated passwords and will check them according to the
above criteria. Passwords that match the criteria are to be
printed, each separated by a comma.
Code:
#question26
import re
passwords = input("Type in: ")
passwords = passwords.split(",")
accepted_pass = []
for i in passwords:
if len(i) < 6 or len(i) > 12:
continue
elif not re.search("([a-z])+", i):
continue
elif not re.search("([A-Z])+", i):
continue
elif not re.search("([0-9])+", i):
continue
elif not re.search("([!@$%^&])+", i):
continue
else:
accepted_pass.append(i)
print((" ").join(accepted_pass))
Output:
Type in: ABd1234@1,a F1#,2w3E*,2We3345
ABd1234@1
Problem 27: You are required to write a program to sort the
(name, age, height) tuples by ascending order where name
is string, age and height are numbers. The tuples are input
by console. The sort criteria is:
1: Sort based on name;
2: Then sort based on age;
3: Then sort by score.
The priority is that name > age > score.
Code:
#question27
from operator import itemgetter
people_info = []
while True:
individual_info = input()
if individual_info == "":
break
else:
people_info.append(tuple((individual_info.split(","))
))
people_info.sort(key = itemgetter(0, 1, 2))
print(people_info)
Output:
Tom,19,80
John,20,90
Jony,17,91
Jony,17,93
Json,21,85

[('John', '20', '90'), ('Jony', '17', '91'), ('Jony',


'17', '93'), ('Json', '21', '85'), ('Tom', '19',
'80')]
Problem 28: Define a class with a generator which can
iterate the numbers, which are divisible by 7, between a
given range 0 and n.
Code:
#question28
class generator:
def _init_(self,mini=0):
self.mini=mini
def genSeven(self,max):
self.max=max
n=7
while(n<self.max):
yield n
n+=7
x = generator()
num=int(input("Enter a limit: "))
for i in x.genSeven(num):
print(i)
Output:
Enter a limit: 50
7
14
21
28
35
42
49

Problem 29: A robot moves in a plane starting from the


original point (0,0). The robot can move toward UP, DOWN,
LEFT and RIGHT with a given steps. The trace of robot
movement is shown as the following:
UP 5
DOWN 3
LEFT 3
RIGHT 2
The numbers after the direction are steps. Please write a
program to compute the
distance from current position after a sequence of
movement and original point. If
the distance is a float, then just print the nearest integer.
Example:
If the following tuples are given as input to the program:
UP 5
DOWN 3
LEFT 3
RIGHT 2
Then, the output of the program should be:
2
Code:
#question29
pos = {
"x": 0,
"y": 0
}
while True:
line = input("> ")
if not line:
break
direction, steps = line.split()
if direction == "UP":
pos["y"] += int(steps)
elif direction == "DOWN":
pos["y"] -= int(steps)
elif direction == "LEFT":
pos["x"] -= int(steps)
elif direction == "RIGHT":
pos["x"] += int(steps)
print (int(round((pos["x"]**2 + pos["y"]**2)**0.5)))
Output:
> UP 5
> DOWN 3
> LEFT 3
> RIGHT 2
>
2

Problem 30: Define a class, which have a class parameter


and have a same instance parameter.
Code:
#question30
class sampleclass:
count = 0
def increase(self):
sampleclass.count += 1
s1 = sampleclass()
s1.increase()
print (s1.count)
s2 = sampleclass()
s2.increase()
print (s2.count)
print (sampleclass.count)
Output:
1
2
2

You might also like