Vous êtes sur la page 1sur 9

SATHYABAMA INSTITUTE OF SCIENCE AND TECHNOLOGY

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

1. From a given list, find the second highest value from the list.
Input: [6, 5, 2, 1, 6, 4]
Output: 5
Code:
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])
2. 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
Code:
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)

3. 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
Code:
s=input("Enter String:")
n=int(input("Enter Width:")
i=0
while(i<len(s)):
print(s[i:i+n])
i+=n

4. 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-------
---.|..|..|..|..|.---
------.|..|..|.------
---------.|.---------

Code:
s="welcome"
length=len(s)
i=1
wleft=int((length*3)/2-1)
wright=wleft
w='.|.'
while(i!=length):
print('-'*wleft+w*i+'-'*wright)
wleft=wleft-3
wright=wright-3
i=i+2
if(i==length):
print('-'*i+s+'-'*i)
wleft=wleft+3
wright=wright+3
i=i-2
while(i>0):
print('-'*wleft+w*i+'-'*wright)
wleft=wleft+3
wright=wright+3
i=i-2

5. 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
Code:
N = int(input("Enter N:"))
Z = int(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 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)

6. 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

Code:
import math
n = int(input("enter a 16 digit credit card no: "))
digits = int(math.log10(n))+1
first = int(str(n)[0])
if((digits>16) or (first not in (4,5,6))):
print(n,"----Invalid")
else:
print(n,"----Valid")
print(digits)

(OR)
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")

7. Read a CSV File. Print column wise output.


Input: filename.csv
Col1 Col2 Col3 Col4
r1c1 r1c2 r1c3 r1c4
r2c1 r2c2 r2c3 r2c4
r3c1 r3c2 r3c3 r3c4
Output:
Col1 r1c1 r2c1 r3c1
Col2 r1c2 r2c2 r3c2
Col3 r1c3 r2c3 r3c3
Col4 r1c4 r2c4 r3c4

Code:
import pandas as pd
df = pd.read_csv('test4.csv')
print(df)
print(df.T)
8. Write a python function evenDigits(lower, upper), which will find
all such numbers between lower limit and upper limit (both included)
such that each digit of the number is an even number.The numbers
obtained should be printed in a comma-separated sequence on a
single line.
Example: evenDigits(2000, 3000)
Output:
2, 2, 2, 2
2, 4, 6, 8

Code:

def evendigit(l,u):
items = [ ]
for i in range(2000, 3000):
s = str(i)
if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and
(int(s[3])%2==0):
items.append(s)
print( ",".join(items))

l=input('enter the lower limit')


u=input('enter the upper limit')
evendigit(l,u)
9. Write a Python program to read last n lines of a file.

Code:

def lastline(f,n):
with open(f) as file:
print('The last',n,'lines from file:',f)
for line in(file.readlines()[-n:]):
print(line,end=' ')

fname=input('enter file name')


n=int(input('no.of last lines to read'))
try:
lastline(fname,n)
except:
print('Error:no such File')
10.Write a Python program to count the frequency of words in a file.
Output: (Assume the words are in the file)
Number of words in the file : Counter({'the': 2, 'and': 5, 'cse': 5,
'infosys': 2, 'campus': 1, 'to': 1, 'sathyabama': 1})
Code:

from collections import Counter


def word_count(fname):
with open(fname) as f:
return Counter(f.read().split())

print("Number of words in the file :",word_count("file.txt"))

Vous aimerez peut-être aussi