Application Development using Python (18CS55) VTU Questions and Solutions - 2
1. Explain in and not operator in string with suitable examples.
Ans : in and not in are membership operators. in operator. The in operator in Python
checks whether a specified value is a constituent element of a sequence like string, array,
list, or tuple etc. When used in a condition, the statement returns a Boolean result
evaluating into either True or False. When the specified value is found inside the
sequence, the statement returns True. Whereas when it is not found, we get a False.
The ‘not in’ operator is the complement of in. [02]
a in calendar z in calendar a not in calendar z not in calendar
True False False True
2. Write a Python program to read a string of multiple words. Extract each word from the string. For each extracted word find the length of the word. If the length of the word is less than or equal to 3 then keep the word unchanged. If the length of the word is greater than three add ‘ing’ at the end of the word. If the given word already ends with ‘ing’ then add ‘ly’ instead.
Sample Input: ‘Hello Om how are you doing? I am playing with
Sara.’
3. With example code explain join and split string methods.
#The join() and split() String Methods
print(', '.join(['cats', 'rats', 'bats']))
print(' '.join(['My', 'name', 'is', 'Simon']))
print('ABC'.join(['My', 'name', 'is', 'Simon']))
spam = '''Dear Alice,
How have you been? I am fine.
There is a container in the fridge
that is labeled "Milk Experiment".
Please do not drink it.
Sincerely,
Bob'''
print(spam.split('\n'))
output:
cats, rats, bats
My name is Simon
MyABCnameABCisABCSimon
['Dear Alice,', 'How have you been? I am fine.', 'There is a container in the fridge', 'that is labeled "Milk Experiment".', 'Please do not drink it.', 'Sincerely,', 'Bob']
4. Write a
Python program to read a string of multiple words. Extract each word from the
string. For each extracted word check whether the word is palindrome or not for
the string length greater than 1. Count the number of palindrome words
appearing in the input string and print palindrome words.
Sample Input: ‘Stack is a structure in which madam can push and pop
items’
Sample Output: Count : 2
Palindrome words are: madam pop
print('Enter string with multiple words')
s='Stack is a structure in which madam can push and pop items' #=input()
w=s.split(' ')
c=0
for i in range(len(w)):
if len(w[i])<2:
continue
if w[i][::-1]==w[i]:
print('Palindrome detected ',w[i])
c=c+1
print('number of palindrome detected ',str(c))
5. With example code snippets explain use of following symbols in regex (), ?, +, .
phonenum = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
mo=phonenum.search('Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.')
print(mo.group(0))
print(mo.group(1))
print(mo.group(2))
print(mo.group())
print(mo.groups())
#Optional Matching with the Question Mark
batRegex = re.compile(r'Bat(wo)?man')
mo1 = batRegex.search('The Adventures of Batman')
print(mo1.group())
mo2 = batRegex.search('The Adventures of Batwoman')
print(mo2.group())
#Optional Matching with the Question Mark
batRegex = re.compile(r'Bat(wo)?man')
mo1 = batRegex.search('The Adventures of Batman')
print(mo1.group())
mo2 = batRegex.search('The Adventures of Batwoman')
print(mo2.group())
#The Wildcard Character
atRegex = re.compile(r'.at')
atRegex.findall('The cat in the hat sat on the flat mat.')
6. Using appropriate python library, write a python program to read password from user. Design a regular expression to check if the password is strong or not with following conditions. Strong password should have at least one digit, one uppercase alphabet, one lowercase alphabet, one special character(@#$%^!) and the length of the password should be between 6 to 10 characters. If the password is weak, ask the user to reenter the password.
import re
passRegEx = re.compile(r'^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^!]).{6,10}$')
str=input('Enter Password')
mo=passRegEx.search(str)
if(mo == None):
print("Weak Pass word")
else:
print("mo.group() ", mo.group())
print("Strong Pass word")
7. Explain the difference between search() and findall() methods in python with supporting examples.
phonenum=re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo=phonenum.search('Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.')
print('Phone number found '+mo.group())
#The findall() Method
phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo = phoneNumRegex.search('Cell: 415-555-9999 Work: 212-555-0000')
print(mo.group())
print(phoneNumRegex.findall('Cell: 415-555-9999 Work: 212-555-0000'))
phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d)-(\d\d\d\d)') # has groups
print(phoneNumRegex.findall('Cell: 415-555-9999 Work: 212-555-0000'))
8. Using appropriate python library, write a python program to check the validity of an email address. An email address should start with an alphabet. It can have multiple alphanumeric characters and underscore(_). It should have a single ‘@’ character, followed by a domain name like gmail/yahoo/rediff. Domain name is followed by single dot(.) and then followed by top level domain name like com/in/net/edu etc.
import re
emailRegEx = re.compile(r'''^([a-zA-Z]) #Beginning starts with alphabet
(\w)* # Multiple alphanumeric characters
@ #Followed by @
[a-z]+ #Domain Name
\. # Single Dot
[a-z]{2,4} # top level domain
$''',re.VERBOSE)
email = input()
mo = emailRegEx.search(email)
if(mo==None):
print('Valid Email Address')
else:
print('InValid Email Address')
9. Develop a python program that prompts the user to enter a filename. If a file exists in the current working directory, the program should print the frequency of each word in the file. If file does not exist, print recursively names of files and folders in the current working directory.
import os
fileName = input('Enter file name')
if(os.path.isfile(fileName)):
print('File exist in current working directory')
fhand = open(fileName)
wordFreqDictionary ={}
for line in fhand:
words = line.split()
for word in words:
if word not in wordFreqDictionary:
wordFreqDictionary[word] = 1
else:
wordFreqDictionary[word] = wordFreqDictionary[word] + 1
for word,freq in wordFreqDictionary.items():
print(word ,' ',freq)
else : #If file does not exist, print recursively names of files and folders in the current working directory
for folderName, subfolders, filenames in
os.walk(os.getcwd()):
print('The current folder is ' + folderName)
for subfolder in subfolders:
print('SUBFOLDER OF ' + folderName + ': ' + subfolder)
for filename in filenames:
print('FILE INSIDE ' + folderName + ': ' + filename)
print('')
10. Consider a file "IA1.txt" containing 10 rows where each row consists of USN, Internal marks and Endterm marks separated by space.
I. Write a python program
“p1.py” to create a dictionary with key as USN and value as total marks
(Internal + External) from the "IA1.txt" text file and save the
dictionary variable using shelve module in file "dict_data".
II. Write a python program “p2.py” to read the variable from "dict_data" file using shelve module and print the USN numbers whose total marks are greater than 90.
p1.py
import shelve
f=open('IA1.txt')
line=f.readlines()
print(line)
d={}
for v in line:
key=v[0:10]
val=v[11:16]
print(val)
d[key]=val
sf=shelve.open('dictdata')
sf['d']=d
Comments
Post a Comment