Python 21
Python 21
Python 21
5 = 7
Lists:
Tuples:
b. Discuss the following methods associated with the file object. 3.5 [CO1]
python
Copy code
with open('file.txt', 'r') as file:
content = file.read()
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()
python
Copy code
with open('file.txt', 'r') as file:
file.seek(0) # Move to the beginning of 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:
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
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)
Python:
● 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 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)
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
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)
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")
c = C()
c.method_a()
c.method_b()
c.method_c()
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
# 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]
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()
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()
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()