devu.in logo

Test paper 2

1. Name the python modules that has the following functions:

i. sin()
ii. search()
iii. basicConfig()
iv. chdir()
v. shuffle()
math.sin()
re.search()
logging.basicConfig()
os.chdir()
random.shuffle()

2. Rewrite the following code in Python after removing all syntax error(s).

var = int(input("Value:"))
size = 0
for i in range(1,size,3)
if i%2==0
var+=i
Else:
Var+=i**2
print var
In [1]:
var = int(input("Value:"))
size = 0
for i in range(1,size,3):
    if i%2==0:
        var+=i
    else:
        var+=i**2
print(var)
Value:10
10
  1. Consider the randomly ordered numbers in the following list. Filter numbers greater than 250 and return them in ascending order.
    [786, 234, 526, 132, 345, 467]
In [2]:
l = [786, 234, 526, 132, 345, 467]
print(sorted([i for i in l if i>250]))
[345, 467, 526, 786]

4. Write AddClient(Client) and DeleteClient(Client) methods in Python to add a new Client and delete a Client from a List of Client Names, considering them to act as insert and delete operations of the queue data structure.

In [1]:
# Queue is Last in First out
class MyClass:
    client = []
    def addClient(self, client):
        self.client.append(client)
    def deleteClient(self):
        if len(self.client)>=1:
            deleted_client = self.client.pop(0)
            print("Client deleted: ", deleted_client)
        else:
            print("Queue is empty")
        
obj1 = MyClass()
obj1.addClient("First Client")
print("Existing client list", obj1.client)

obj2 = MyClass()
obj2.addClient("Second Client")
print("Existing client list", obj2.client)

obj3 = MyClass()
obj3.deleteClient()
print("Existing client list", obj3.client)
Existing client list ['First Client']
Existing client list ['First Client', 'Second Client']
Client deleted:  First Client
Existing client list ['Second Client']

5. Write a definition of a method COUNTNOW(PLACES) to find and display those place names, in which there are more than 5 characters.

Example: If the list PLACES contains

["DELHI","LONDON","PARIS","NEW YORK","DUBAI"]

The following should get displayed :

LONDON 
NEW YORK
In [11]:
def countnow(places):
    for place in places:
        if len(place)>5:
            print(place)
            
countnow(["DELHI","LONDON","PARIS","NEW YORK","DUBAI"])
LONDON
NEW YORK

6. Write the python code to open a text file STORY.TXT so that new contents can be added at the end of it. Also check its writability and make sure to close the file using context manager after write operation.

In [13]:
with open('story.txt', 'a') as f:
    print("Is the file writable: ", f.writable())
print("IS the file closed: ", f.closed)
Is the file writable:  True
IS the file closed:  True

7. Considering the following definition of class MULTIPLEX, write a method in Python to search and display all the contents in a pickled file CINEMA.DAT, where MTYPE is matching with the value ‘Comedy’.

Example:

class MULTIPLEX :
    def __init__(self,mno,mname,mtype):
        self.MNO = mno
        self.MNAME = mname
        self.MTYPE = mtype
    def Show(self):
        print(self.MNO:"*",self.MNAME,"$",self.MTYPE)
In [75]:
def Search(self):
    file=open('CINEMA.DAT','rb')
    try:
        while True:
            M=pickle.load(file)
            if M.MTYPE=="Comedy":
                M.Show()
    except EOFError:
        pass
    file.close()

8. Write a program to reverse a dictionary consider both duplicate and non-duplicate values scenario.

In [21]:
d = eval(input("Enter a dictinary: "))
if len(d.values()) == len(set(d.values())):
    print({v:k for k, v in d.items()})
else:
    print({v:[i for i in d.keys() if d[i]==v] for k, v in d.items()})
Enter a dictinary: {1:'a', 2:'b', 3:'c', 4:'d'}
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
In [23]:
# Reexecuting same program with duplicate values
In [22]:
d = eval(input("Enter a dictinary: "))
if len(d.values()) == len(set(d.values())):
    print({v:k for k, v in d.items()})
else:
    print({v:[i for i in d.keys() if d[i]==v] for k, v in d.items()})
Enter a dictinary: {1:'a', 2:'b', 3:'c', 4:'b'}
{'a': [1], 'b': [2, 4], 'c': [3]}

9. Write a program to expand the dictionary to sparse vector with zero and non-zero values according to the given indexes.

Example:

I/P: {2:3, 5:1, 9:3}
O/P: [0, 0, 3, 0, 0, 1, 0, 0, 0, 3]
In [31]:
d = {2:3, 5:1, 9:3}
print([d[i] if i in d.keys() else 0 for i in range(max(d.keys())+1)])
[0, 0, 3, 0, 0, 1, 0, 0, 0, 3]

10. Write a program to convert CSV data to XML.

Name Phone Email Address
John 9999988888 john@gmail.com Bangalore
Ravi 9898989898 ravi@gmail.com Patna
In [66]:
import csv
with open('datasource.csv') as f:
    all_csv_data = list(csv.reader(f))
    
print("All csv data: ", all_csv_data)

csv_header = all_csv_data[0]
print("\nHeader: ",  csv_header)

csv_data = all_csv_data[1:]
print("\nRemaining csv data: ", csv_data)
All csv data:  [['Name', 'Phone', 'Email', 'Address'], ['John', '9999988888', 'john@gmail.com', 'Bangalore'], ['Ravi', '9898989898', 'ravi@gmail.com', 'Patna']]

Header:  ['Name', 'Phone', 'Email', 'Address']

Remaining csv data:  [['John', '9999988888', 'john@gmail.com', 'Bangalore'], ['Ravi', '9898989898', 'ravi@gmail.com', 'Patna']]
In [69]:
xml_file = open('destination.xml', 'w')
xml_file.write('<?xml version="1.0" encoding="utf-8" ?>' + "\n")
xml_file.write('<collection>' + "\n")

for row_data in csv_data:
    xml_file.write('    <element>' + "\n")
    for i in range(len(csv_header)):
        xml_file.write('        ' + '<' + csv_header[i] + '>' \
                      + row_data[i] + '</' + csv_header[i] + '>' + "\n")
    xml_file.write('    </element>' + "\n")

xml_file.write('</collection>' + "\n")
xml_file.close()

# To verify print destinaltion.xml
print(open('destination.xml').read())
<?xml version="1.0" encoding="utf-8" ?>
<collection>
    <element>
        <Name>John</Name>
        <Phone>9999988888</Phone>
        <Email>john@gmail.com</Email>
        <Address>Bangalore</Address>
    </element>
    <element>
        <Name>Ravi</Name>
        <Phone>9898989898</Phone>
        <Email>ravi@gmail.com</Email>
        <Address>Patna</Address>
    </element>
</collection>

  • For doubt clarification email your tutor: ram@devu.in
  • Admin helpline: +91 9986877711. All rights reserved by devU.in