0% found this document useful (0 votes)
105 views7 pages

Cycle-I Solutions

This document contains the lab manual for the Python Programming and Machine Learning lab course. It includes 7 programming exercises on Python fundamentals like I/O, loops, functions, files and exceptions. The exercises cover summarizing data from strings, wrapping strings, validating credit card numbers and calculating the sum of cubed elements in lists. Solutions to each exercise are provided in the Python language.

Uploaded by

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

Cycle-I Solutions

This document contains the lab manual for the Python Programming and Machine Learning lab course. It includes 7 programming exercises on Python fundamentals like I/O, loops, functions, files and exceptions. The exercises cover summarizing data from strings, wrapping strings, validating credit card numbers and calculating the sum of cubed elements in lists. Solutions to each exercise are provided in the Python language.

Uploaded by

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

SATHYABAMA INSTITUTE OF SCIENCE AND TECHNOLOGY

(DEEMED TO BE UNIVERSITY)
SCHOOL OF COMPUTING
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
LAB MANUAL
SCS4305 – Python Programming and Machine Learning Lab
Language: python 3.7

Python Programming: Cycle 1:


1. a)Handling Input and Output,b)Looping constructs c)Arrays, Lists, Sets and
Dictionaries
Solution:
a)
name = raw_input("Enter your name: ")
print("Your name is: ", name)
print(type(name))
age = raw_input("Enter your age: ")
print("Your name is: ", age)
print(type(age))
sal = raw_input("Enter your sal: ")
print("Your name is: ", sal)
print(type(sal))
age = 22
sal = 10.50
complex = 3+5j
print(type(age))
print(type(sal))
print(type(complex))

b)
courses = ['python', 'iot', 'uit']
print(courses)
courses.sort()
print(courses)
print(len(courses))
print(courses[1])
courses[1]='ml'
print(courses)
courses.append('dm')
courses.insert(1, 'sqat')
print(courses)
courses.remove('sqat')
print(courses)
if 'ml' in courses:
print('ml is part of courses')
else:
print('no')
courses.clear()
print(courses)

c)
dcourses = {
"python": "x",
"iot": "y",
"uit": "z"
}
print(dcourses)
print(dcourses["python"])
dcourses["python"] = "a"
print(dcourses)
for i in dcourses:
print(i)
for j in dcourses.values():
print(j)
for (i, j) in dcourses.items():
print(i, j)

2. a)Modules and Functions,b)File Handling,c)Exception Handling

Solution:
a)
import ex0_module as calc
num1 = raw_input("Enter Number 1: ")
num2 = raw_input("Enter Number 2: ")
result = add(int(num1), int(num2))
print("Sum of ", num1, " and ", num2, " is ", result)
result = calc.sub(int(num1), int(num2))
print("Subtraction of ", num1, " and ", num2, " is ", result)
result = calc.mul(int(num1), int(num2))
print("Multiplication of ", num1, " and ", num2, " is ", result)
result = calc.div(int(num1), int(num2))
print("Division of ", num1, " and ", num2, " is ", result)

ex0_module1:
def sub(a, b):
return a-b

def mul(a, b):


return a*b

def div(a, b):


return a/b

b)
fopen = open("ex0_module1.py", "r")
fwrite = open("filewrite.txt", "w")
fwrite.write("Line of text added to the file")
fwrite = open("filewrite.txt", "a")
fwrite.write("Line of text appended to the file")
fwrite.close()
fread = open("filewrite.txt", "r")
print(fread.read())
fread.close()

c)
try:
print(x)
except:
print("An exception occurred")
try:
print(x)
except NameError:
print("Variable X is not declared")
except:
print("An exception occurred")
try:
fopen = open("nofile.txt", "r")
fopen.write("test")
except:
print("Cannot write to file, as it is opened in read mode")
finally:
fopen.close()

3. From a given list, find the second highest value from the list.
Input: [6, 5, 2, 1, 6, 4]
Output: 5
Solution:
a=[]
a = [int(x) for x in input().split()]
print(sorted(a))
print(a[-1])

(OR)
a = []
b = []
a = [int(x) for x in input().split()]
for x in a:
if x not in b:
b.append(x)
b.sort()
length = len(b)
print("entered list:",a)
print("sorted list:",b)
print(b[length-2])

4. From the string input, count the special characters, alphabets, digits, lowercase and
uppercase characters.
Input: Sathyabama 2019 @
Output:
Digits: 4
Alphabets: 10
Special Characters: 1
Lowercase: 9
Uppercase: 1
Solution:
def Count(str):
upper, lower, number, special = 0, 0, 0, 0
for i in range(len(str)):
if ((int(ord(str)) >= 65 and int(ord(str)) <= 90)):
upper += 1
elif ((int(ord(str)) >= 97 and int(ord(str)) <= 122)):
lower += 1
elif (int(ord(str)) >= 48 and int(ord(str)) <= 57):
number += 1
else:
special += 1
print('Upper case letters:', upper)
print('Lower case letters:', lower)
print('Number:', number)
print('Special characters:', special)

str = "Sathyabama2019@"
Count(str)
(OR)
s = "Sathyabama2019@"
num = sum(c.isdigit() for c in s)
up = sum(c.isupper() for c in s)
lo = sum(c.islower() for c in s)
wor = sum(c.isalpha() for c in s)
oth = len(s)- num - wor

print("words:", wor)
print("number:", num)
print("upper:", up)
print("lower:", lo)
print("special characters:", oth)

5. Input String (s) and Width (w). Wrap the string into a paragraph of width w.
Input:
s = Sathyabama
w=3
Output:
Sat
hya
bam
a

Solution:
s=input("Enter String:")
n=int(input("Enter Width:")
i=0
while(i<len(s)):
print(s[i:i+n])
i+=n

6. Print of the String "Welcome". Matrix size must be N X M. ( N is an odd natural


number, and M is 3 times N.). The design should have 'WELCOME' written in the
center.The design pattern should only use |, .and - characters.
Input: N = 7, M = 21
Output:
---------.|.---------
------.|..|..|.------
---.|..|..|..|..|.---
-------welcome-------
---.|..|..|..|..|.---
------.|..|..|.------
---------.|.---------
Solution:
n, m = map(int,raw_input().split())
pattern = [('.|.'*(2*i + 1)).center(m, '-') for i in range(n//2)]
print('\n'.join(pattern + ['WELCOME'.center(m, '-')] + pattern[::-1]))

(OR)

N, M = map(int,raw_input().split())
for i in xrange(0,N/2):
print ('.|.'*i).rjust((M-2)/2,'-')+'.|.'+('.|.'*i).ljust((M-2)/2,'-')
print 'WELCOME'.center(M,'-')
for i in reversed(xrange(0,N/2)):
print ('.|.'*i).rjust((M-2)/2,'-')+'.|.'+('.|.'*i).ljust((M-2)/2,'-')

7. Consider a function f(X) = X3. Input is ‘N’ list. Each list contains ‘M’ elements. From
the list, find the maximum element. Compute: S = (f(X1) + f(X2) + f(X3) + … + f(XN))
Modulo Z
Input:
N=3
Z = 1000
N1 = 2 5 1
N2 = 1 2 4 6 9
N3 = 10 9 11 4 5
Procedure:
maxn1 = 5
maxn2 = 9
maxn3 = 11
S = ((maxn1)3 + (maxn2)3 + (maxn3)3) % Z
Output:
185
Solution:
N = int(raw_input("Enter N:"))
Z = int(raw_input("Enter Z:"))
s=0
a = {}
k=1
while k <= N:
#<dynamically create key>
key = k
#<calculate value>
print("enter numbers in list(",k,"):")
value = [int(x) for x in raw_input().split()]
a[key] = value
k += 1
for i in a:
x = max(a[i])
s = s + x**3
S = s%Z
print("S = (f(X1) + f(X2) + f(X3) + ----+ f(XN)) Modulo Z:",S)
8. Validate the Credit numbers based on the following conditions:
Begins with 4,5, or 6
Contain exactly 16 digits
Contains only numbers ( 0 to 9 )
For every 4 digits a hyphen (-) may be included (not mandatory). No other special
character permitted.
Must not have 4 or more consecutive same digits.

Input & Output:


4253625879615786 Valid
4424424424442444 Valid
5122-2368-7954-3214 Valid
42536258796157867 Invalid
4424444424442444 Invalid
5122-2368-7954 - 3214 Invalid
44244x4424442444 Invalid
0525362587961578 Invalid
61234-567-8912-3456 Invalid

Solution:
T = int(input('Enter the number of credit cards to be tested :'))
for _ in range(T):
cNum = input()
merge = ''.join(cNum.split('-'))
if cNum[0] in ['4', '5', '6']:
if (len(cNum) == 16) or (len(cNum) == 19 and cNum.count('-') == 3):
if all([len(each) == 4 for each in cNum.split('-')]) or cNum.isdigit():
if ((any(merge.count i * 4)) >= 1 for i in ('0123456789')):
pass
else:
print("Valid")
continue
print("Invalid")

You might also like