Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python 21

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

8. Answer the following questions: 2 X 3.

5 = 7

a. Compare List and Tuple sequences in Python. 3.5 [CO1]

Lists:

● Mutable: Lists can be modified after their creation.


● Syntax: Defined using square brackets, e.g., my_list = [1, 2, 3].
● Performance: Slower compared to tuples due to extra overhead.
● Use Case: Suitable for collections that need to be changed frequently.

Tuples:

● Immutable: Tuples cannot be modified after their creation.


● Syntax: Defined using parentheses, e.g., my_tuple = (1, 2, 3).
● Performance: Faster due to immutability.
● Use Case: Suitable for fixed collections where data should not change.

b. Discuss the following methods associated with the file object. 3.5 [CO1]

a) read(): Reads the entire file and returns it as a string.

python
Copy code
with open('file.txt', 'r') as file:
content = file.read()

b) readline(): Reads a single line from the file.

python
Copy code
with open('file.txt', 'r') as file:
line = file.readline()

c) readlines(): Reads all the lines in the file and returns them as a list.

python
Copy code
with open('file.txt', 'r') as file:
lines = file.readlines()
d) tell(): Returns the current position of the file pointer.

python
Copy code
with open('file.txt', 'r') as file:
position = file.tell()

e) seek(): Moves the file pointer to a specified location.

python
Copy code
with open('file.txt', 'r') as file:
file.seek(0) # Move to the beginning of the file

f) write(): Writes a string to the file.

python
Copy code
with open('file.txt', 'w') as file:
file.write("Hello, World!")

c. How does Generalization differ from Encapsulation? Explain with examples in Python.
3.5 [CO1]

Generalization:

● Generalization is the process of extracting shared characteristics from two or more


classes and combining them into a generalized superclass.
● Example:

python
Copy code
class Animal:
def speak(self):
pass

class Dog(Animal):
def speak(self):
return "Bark"
class Cat(Animal):
def speak(self):
return "Meow"

Encapsulation:

● Encapsulation is the bundling of data with the methods that operate on that data.
● Example:

python
Copy code
class Employee:
def __init__(self, name, salary):
self.__name = name
self.__salary = salary

def get_name(self):
return self.__name

def set_salary(self, salary):


self.__salary = salary

d. Explain try, catch, and finally block with an example in Python. 3.5 [CO1]
python
Copy code
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
finally:
print("This block is always executed.")

e. Write a Python program to read lines from a file, break into tokens, and convert the
tokens to unique numerical values using Python dictionary. 3.5 [CO1]
python
Copy code
token_dict = {}
token_counter = 1
with open('file.txt', 'r') as file:
for line in file:
tokens = line.split()
for token in tokens:
if token not in token_dict:
token_dict[token] = token_counter
token_counter += 1

print(token_dict)

9. Discuss different mutable and immutable data types in Python. 7 [CO1]

Mutable Data Types:

● Lists: my_list = [1, 2, 3]


● Dictionaries: my_dict = {'a': 1, 'b': 2}
● Sets: my_set = {1, 2, 3}
● bytearray: my_bytearray = bytearray([1, 2, 3])

Immutable Data Types:

● Tuples: my_tuple = (1, 2, 3)


● Strings: my_string = "hello"
● Integers: my_int = 42
● Floats: my_float = 3.14
● Booleans: my_bool = True
● Bytes: my_bytes = bytes([1, 2, 3])

Discuss advantages of Python over Java as an Object-Oriented


Programming Language. 7 [CO1]

Python:

● Ease of Use: Python has simpler syntax and is more beginner-friendly.


● Dynamic Typing: Python uses dynamic typing, which allows for more flexibility in writing
code.
● Rapid Development: Python’s simplicity and large standard library enable faster
development.
● Interpreted Language: Python is interpreted, which makes debugging easier.
● Memory Management: Automatic memory management and garbage collection.
Java:

● Static Typing: Java uses static typing, which can catch type errors at compile time.
● Performance: Generally faster execution due to Just-In-Time (JIT) compiler.
● Robustness: Strong type checking, which helps in building large applications.
● Multithreading: Built-in support for multithreaded programming.
● Platform Independence: Java bytecode can run on any platform with a JVM.

10. Search for palindrome and unique words in a text using class method
and string method. 4+3 = 7 [CO4]
python
Copy code
class TextProcessor:
def __init__(self, text):
self.text = text

def is_palindrome(self, word):


return word == word[::-1]

def find_palindromes(self):
words = self.text.split()
return [word for word in words if self.is_palindrome(word)]

def find_unique_words(self):
words = self.text.split()
unique_words = set(words)
return list(unique_words)

text = "madam arora teaches malayalam"


processor = TextProcessor(text)
print("Palindromes:", processor.find_palindromes())
print("Unique words:", processor.find_unique_words())

Write first seven Fibonacci numbers using generator next function/yield


with a class in Python. Trace and memorize the function. Define pickling
and unpickling in Python. 4+3 = 7 [CO4]
python
Copy code
class Fibonacci:
def __init__(self):
self.a, self.b = 0, 1

def __iter__(self):
return self

def __next__(self):
fib = self.a
self.a, self.b = self.b, self.a + self.b
return fib

def fibonacci_gen():
a, b = 0, 1
while True:
yield a
a, b = b, a + b

fib = Fibonacci()
for _ in range(7):
print(next(fib))

gen = fibonacci_gen()
for _ in range(7):
print(next(gen))

# Pickling and Unpickling


import pickle

data = {"a": 1, "b": 2}

# Pickling
with open('data.pkl', 'wb') as file:
pickle.dump(data, file)

# Unpickling
with open('data.pkl', 'rb') as file:
loaded_data = pickle.load(file)
print(loaded_data)

11. In Python, explain the accessibility of the members of a class across


other classes within and outside the package. Explain multiple inheritance
in Python with an example. 3+4 = 7 [CO1]

Accessibility of Class Members:

● Public Members: Accessible from anywhere.


● Protected Members: Prefixed with a single underscore (_), accessible within the class
and its subclasses.
● Private Members: Prefixed with double underscores (__), accessible only within the
class.

Example:

python
Copy code
class MyClass:
def __init__(self):
self.public = "Public"
self._protected = "Protected"
self.__private = "Private"

class SubClass(MyClass):
def __init__(self):
super().__init__()
print(self.public) # Accessible
print(self._protected) # Accessible
# print(self.__private) # Not Accessible

obj = MyClass()
print(obj.public) # Accessible
print(obj._protected) # Accessible
# print(obj.__private) # Not Accessible

Multiple Inheritance:

python
Copy code
class A:
def method_a(self):
print("Method A")

class B:
def method_b(self):
print("Method B")

class C(A, B):


def method_c(self):
print("Method C")

c = C()
c.method_a()
c.method_b()
c.method_c()

What is operator overloading? Write a class in Python to represent


complex numbers with necessary constructors. Write methods or functions
for the following: Overloading the operator +, *, <<, and >. 3+4 = 7 [CO1]

Operator Overloading:

● Operator overloading allows custom definitions for operators to work with user-defined
types.

python
Copy code
class Complex:
def __init__(self, real, imag):
self.real = real
self.imag = imag

def __add__(self, other):


return Complex(self.real + other.real, self.imag + other.imag)

def __mul__(self, other):


return Complex(self.real * other.real - self.imag *
other.imag, self.real * other.imag + self.imag * other.real)
def __str__(self):
return f"{self.real}+{self.imag}i"

def __gt__(self, other):


return (self.real**2 + self.imag**2) > (other.real**2 +
other.imag**2)

# Example usage
c1 = Complex(3, 2)
c2 = Complex(1, 7)

print("Addition:", c1 + c2)
print("Multiplication:", c1 * c2)
print("String Representation:", c1)
print("Comparison:", c1 > c2)

12. How multiple threads are created and ended in Python? How will they
synchronize? Discuss these with an example to solve the
producer-consumer problem. 7 [CO2]

Creating and Ending Threads:

python
Copy code
import threading

def print_numbers():
for i in range(5):
print(i)

thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()

Synchronization Example (Producer-Consumer Problem):

python
Copy code
import threading
import time
import random

buffer = []
buffer_size = 5
condition = threading.Condition()

class Producer(threading.Thread):
def run(self):
global buffer
while True:
condition.acquire()
if len(buffer) == buffer_size:
condition.wait()
num = random.randint(1, 10)
buffer.append(num)
print(f"Produced {num}")
condition.notify()
condition.release()
time.sleep(random.random())

class Consumer(threading.Thread):
def run(self):
global buffer
while True:
condition.acquire()
if not buffer:
condition.wait()
num = buffer.pop(0)
print(f"Consumed {num}")
condition.notify()
condition.release()
time.sleep(random.random())

producer = Producer()
consumer = Consumer()
producer.start()
consumer.start()
producer.join()
consumer.join()

Write a Python program to design a simple connectionless server,


explaining the connectionless service. 7 [CO2]

Connectionless Service Example (UDP Server):

python
Copy code
import socket

def udp_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('localhost', 12345))
print("UDP server up and listening")

while True:
message, address = server_socket.recvfrom(1024)
print(f"Message from {address}: {message.decode()}")
server_socket.sendto(b"Hello, UDP client!", address)

udp_server()

In a connectionless service, there is no need to establish a connection before data transfer.


Instead, data is sent as individual packets using the UDP protocol, which does not guarantee
delivery but is faster and more efficient for certain use cases.

You might also like