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

Python 23

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Python 23

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

1.

Discuss advantages of Python over Java as an Object-Oriented


Programming Language. 10 [CO1]

Advantages of Python over Java:

1. Syntax Simplicity:
○ Python has simpler and more readable syntax compared to Java.

Example:
python
Copy code
# Python
print("Hello, World!")

// Java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}


2. Dynamic Typing:
○ Python uses dynamic typing, meaning variables can change types, reducing
verbosity.

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


3. Faster Development:
○ Python allows for rapid prototyping and development due to its concise syntax
and extensive libraries.
4. Interpreted Language:
○ Python is interpreted, allowing for immediate feedback and easier debugging.
5. Extensive Libraries:
○ Python has a rich set of libraries and frameworks for various applications (e.g.,
data science, web development).
6. Memory Management:
○ Python handles memory management automatically with garbage collection.

2. Why Python is called a dynamic language? Discuss the chr(), int(), oct(),
complex(), and float() type conversion functions with examples. 5+5=10
[CO1]

Dynamic Language:

● Python is called a dynamic language because the type of a variable is interpreted at


runtime. This means you can assign different types of values to the same variable
without declaring its type.

Type Conversion Functions:

chr(): Converts an integer to a character.


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

int(): Converts a string or number to an integer.


python
Copy code
print(int("123")) # Output: 123

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


python
Copy code
print(oct(10)) # Output: '0o12'

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


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

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


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

3. Write a program to create three dictionaries and concatenate them to


create a fourth dictionary. Check whether a dictionary is empty or not.
5+5=10 [CO1]
python
Copy code
# Creating three dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict3 = {'e': 5, 'f': 6}

# Concatenating dictionaries
dict4 = {**dict1, **dict2, **dict3}
print("Concatenated Dictionary:", dict4)

# Checking if a dictionary is empty


def is_empty(dictionary):
return len(dictionary) == 0

print("Is dict1 empty?", is_empty(dict1))


print("Is {} empty?", is_empty({}))

4. What is multithreading? How to create a multi-threading program in


Python? 5+5=10 [CO2]

Multithreading:

● Multithreading is the ability of a CPU to execute multiple threads concurrently. It helps in


performing multiple operations at once, making efficient use of CPU resources.

Creating a Multi-threading Program:

python
Copy code
import threading
def print_numbers():
for i in range(5):
print(i)

def print_letters():
for char in ['a', 'b', 'c', 'd', 'e']:
print(char)

# Creating threads
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)

# Starting threads
thread1.start()
thread2.start()

# Joining threads
thread1.join()
thread2.join()

print("Threads have finished execution")

5. 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()

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


sorted(). Write a program that receives a string containing a sequence of
white space separated words and returns a string after removing all
duplicate words and sorting them alphanumerically. 5+5=10 [CO4]

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]

Removing Duplicates and Sorting Words:

python
Copy code
def process_string(s):
words = s.split()
unique_words = list(set(words))
unique_words.sort()
return ' '.join(unique_words)

input_str = "apple banana apple orange banana"


output_str = process_string(input_str)
print(output_str) # Output: "apple banana orange"

7. How does Generalization differ from Encapsulation. Explain with


examples in Python. What is monkey patching in Python? 5+5=10 [CO1]

Generalization vs Encapsulation:

Generalization: The process of extracting shared characteristics from two or more classes and
combining them into a generalized superclass.
python
Copy code
class Animal:
def speak(self):
pass

class Dog(Animal):
def speak(self):
return "Woof"

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

Encapsulation: The bundling of data and methods that operate on that data within a single unit
or class, and restricting access to some of the object's components.
python
Copy code
class Person:
def __init__(self, name, age):
self.__name = name # Private attribute
self.__age = age # Private attribute

def get_name(self):
return self.__name

def get_age(self):
return self.__age

Monkey Patching:

Monkey patching refers to the dynamic modification of a class or module at runtime.


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

def patched_method():
print("Patched Method")

A.method = patched_method
obj = A()
obj.method() # Output: "Patched Method"

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 [CO4]

Functional Programming Features:

● First-Class Functions: Functions are treated as first-class citizens.


● Higher-Order Functions: Functions that take other functions as arguments or return
them as results.
● Lambda Functions: Small anonymous functions defined using the lambda keyword.
● Map, Filter, Reduce: Functions to process data collections.
● Immutability: Preference for immutable data structures.

Stack Implementation:

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

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()

# 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

You might also like