0% found this document useful (0 votes)
36 views

Python 22

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Python 22

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

1.

Discuss advantages of Python over Java as an Object Oriented


Programming Language. 10 [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.

2. Why Python is called a dynamic and strongly typed language? Discuss


the ord(), hex(), oct(), complex(), and float() type conversion functions with
examples. 5+5=10 [CO1]

Dynamic Typing:

● Variables in Python are not bound to a specific data type and can change types during
execution.

Example:
python
Copy code
x = 10
x = "Hello"

Strongly Typed:

● Even though Python is dynamically typed, it enforces type constraints during operations.

Example:
python
Copy code
x = "10"
y = 5
print(x + y) # Raises a TypeError

Type Conversion Functions:

ord(): Converts a character to its corresponding ASCII value.


python
Copy code
print(ord('A')) # Output: 65

hex(): Converts an integer to a hexadecimal string.


python
Copy code
print(hex(255)) # Output: '0xff'

oct(): Converts an integer to an octal string.


python
Copy code
print(oct(8)) # Output: '0o10'

complex(): Creates a complex number from real and imaginary parts.


python
Copy code
print(complex(1, 2)) # Output: (1+2j)

float(): Converts a number or string to a float.


python
Copy code
print(float('3.14')) # Output: 3.14


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

@classmethod
def is_palindrome(cls, 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()
return list(set(words))

text = "madam arora teaches malayalam"


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

4. Create a GUI application in Python that provides an Entry field where the
user can provide the name of a text file. Open the file and read it, displaying
its contents in a Label. You can also replace the Entry widget with a menu
that has a File Open option that pops up a window to allow the user to
specify the file to read. Also add an Exit or Quit option to the menu rather
than having a QUIT button. 10 [CO3]
python
Copy code
import tkinter as tk
from tkinter import filedialog, messagebox

def open_file():
file_path = filedialog.askopenfilename()
if file_path:
with open(file_path, 'r') as file:
content = file.read()
text_area.config(state=tk.NORMAL)
text_area.delete(1.0, tk.END)
text_area.insert(tk.END, content)
text_area.config(state=tk.DISABLED)

def quit_app():
root.quit()

root = tk.Tk()
root.title("File Reader")

menu_bar = tk.Menu(root)
file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="Open", command=open_file)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=quit_app)
menu_bar.add_cascade(label="File", menu=file_menu)
root.config(menu=menu_bar)

text_area = tk.Text(root, state=tk.DISABLED, wrap=tk.WORD)


text_area.pack(expand=True, fill=tk.BOTH)

root.mainloop()

5. Write a Python program to design a simple connection-oriented server,


explaining the connection-oriented service. 10 [CO2]

Connection-Oriented Service Example (TCP Server):

python
Copy code
import socket

def tcp_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 12345))
server_socket.listen(5)
print("TCP server up and listening")

while True:
client_socket, client_address = server_socket.accept()
print(f"Connection from {client_address}")
message = client_socket.recv(1024).decode()
print(f"Message from client: {message}")
client_socket.send("Hello, TCP client!".encode())
client_socket.close()

tcp_server()

6. Discuss the following list functions - a) len() b) sum() c) any() d) all() e)


sorted(). Write first seven Fibonacci numbers using generator next
function/yield in Python. Trace and memorize the function. 5+5=10 [CO1]

List Functions:

len(): Returns the length of a list.


python
Copy code
my_list = [1, 2, 3]
print(len(my_list)) # Output: 3

sum(): Returns the sum of elements in a list.


python
Copy code
my_list = [1, 2, 3]
print(sum(my_list)) # Output: 6

any(): Returns True if any element in the list is True.


python
Copy code
my_list = [0, 0, 1]
print(any(my_list)) # Output: True

all(): Returns True if all elements in the list are True.


python
Copy code
my_list = [1, 2, 3]
print(all(my_list)) # Output: True

sorted(): Returns a sorted list.


python
Copy code
my_list = [3, 1, 2]
print(sorted(my_list)) # Output: [1, 2, 3]

First Seven Fibonacci Numbers Using Generator:

python
Copy code
def fibonacci_gen():
a, b = 0, 1
for _ in range(7):
yield a
a, b = b, a + b

gen = fibonacci_gen()
for num in gen:
print(num)

7. Create a list of Tuples. Each Tuple should contain an item and its price in
float. Write a program to sort the tuples in descending order by price. Use
operator.itemgetter(). Write a program that proves that the dictionary
returned by globals() can be used to manipulate values of variables in it.
5+5=10 [CO2]

Sorting Tuples by Price:

python
Copy code
from operator import itemgetter

items = [("apple", 1.5), ("banana", 0.5), ("cherry", 2.0)]


sorted_items = sorted(items, key=itemgetter(1), reverse=True)
print(sorted_items)

Using globals() to Manipulate Variables:

python
Copy code
x = 10
y = 20

def manipulate_globals():
globals()['x'] = 15
globals()['y'] = 25

manipulate_globals()
print(x, y) # Output: 15 25

8. Explain different functional programming features in Python. Write a


program that implements a stack data structure of specific size. If the stack
is full and we are trying to push an item, then an IndexError exception
should be raised. Similarly, if the stack is empty, then an IndexError
exception should be raised. 5+5=10 [CO3]

Functional Programming Features:

● First-Class Functions: Functions can be assigned to variables, passed as arguments,


and returned from other functions.
● Higher-Order Functions: Functions that can take other functions as arguments or
return them.
● Lambda Functions: Anonymous functions defined using the lambda keyword.
● Map, Filter, Reduce: Functional tools to apply functions over collections.

Stack Implementation:

python
Copy code
class Stack:
def __init__(self, size):
self.size = size
self.stack = []

def push(self, item):


if len(self.stack) >= self.size:
raise IndexError("Stack is full")
self.stack.append(item)

def pop(self):
if not self.stack:
raise IndexError("Stack is empty")
return self.stack.pop()

# Example usage
s = Stack(3)
s.push(1)
s.push(2)
s.push(3)
try:
s.push(4)
except IndexError as e:
print(e) # Output: Stack is full

print(s.pop()) # Output: 3
try:
s.pop()
s.pop()
s.pop()
except IndexError as e:
print(e) # Output: Stack is empty

These answers cover the provided questions comprehensively, addressing each with code
examples and brief explanations.

You might also like