Binary Search

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

Tower of Hanoi:

def tower_of_hanoi(n, source, auxiliary, target):


if n == 1:
print(f"Move disk 1 from {source} to {target}")
return
tower_of_hanoi(n-1, source, target, auxiliary)
print(f"Move disk {n} from {source} to {target}")
tower_of_hanoi(n-1, auxiliary, source, target)
# Example usage:
num_disks = int(input("Enter the number of disks: "))
tower_of_hanoi(num_disks, 'A', 'B', 'C')
----------------------------------------------------------------------------------------------------------------
binary search:
Binary search is an efficient algorithm for finding an element in a sorted array. The
idea is to repeatedly divide the search interval in half until the target element is found
or the search interval is empty. Here's a simple Python program to perform binary
search using recursion:
def binary_search_recursive(arr, target, low, high):
if low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid # Element found, return its index
elif arr[mid] < target:
return binary_search_recursive(arr, target, mid + 1, high) # Search the right
half
else:
return binary_search_recursive(arr, target, low, mid - 1) # Search the left half
else:
return -1 # Element not foun
# Example usage:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
target_element = int(input("Enter the target element to search: "))
result = binary_search_recursive(arr, target_element, 0, len(arr) - 1)
if result != -1:
print(f"Element {target_element} found at index {result}")
else:
print(f"Element {target_element} not found in the array")
Tuples in Python are immutable sequences, meaning their elements cannot be
modified after creation.
Tuples can be created using parentheses () or the tuple() constructor:
# Using parentheses
my_tuple = (1, 2, 3, 'a', 'b')
# Using tuple() constructor
another_tuple = tuple([4, 5, 6])
Elements of a tuple can be accessed using indexing:
print(my_tuple[0]) # Output: 1
print(my_tuple[3]) # Output: 'a'

Slicing:
Tuples support slicing to extract sub-tuples:
sub_tuple = my_tuple[1:4]
print(sub_tuple) # Output: (2, 3, 'a')

Concatenation:
Tuples can be concatenated using the + operator:
combined_tuple = my_tuple + another_tuple
print(combined_tuple) # Output: (1, 2, 3, 'a', 'b', 4, 5, 6)

Repetition:
Tuples can be repeated using the * operator:
repeated_tuple = my_tuple * 2
print(repeated_tuple) # Output: (1, 2, 3, 'a', 'b', 1, 2, 3, 'a', 'b')

Length:
The len() function returns the length of a tuple:
print(len(my_tuple)) # Output: 5
----------------------------------------------------------------------------------------------------------------
list:
Lists in Python are mutable sequences, allowing various operations to be performed
on them. Here are some common operations on lists:
1. Creation:
Lists can be created using square brackets []:
my_list = [1, 2, 3, 'a', 'b']
2. Accessing Elements:
Elements of a list can be accessed using indexing:
print(my_list[0]) # Output: 1 print(my_list[3]) # Output: 'a'
3. Slicing:
Lists support slicing to extract sub-lists:
sub_list = my_list[1:4] print(sub_list) # Output: [2, 3, 'a']
4. Modification:
Lists can be modified by changing elements, adding, or removing elements:
my_list[0] = 'updated' my_list.append('c') my_list.extend([4, 5, 6]) my_list.insert(2,
'new_element')
5. Deletion:
Elements can be removed by using the del statement or the remove() method:
del my_list[1] my_list.remove('a')
6. Concatenation:
Lists can be concatenated using the + operator:
another_list = [7, 8, 9] combined_list = my_list + another_list print(combined_list) #
Output: ['updated', 3, 'new_element', 'b', 'c', 4, 5, 6, 7, 8, 9]
7. Repetition:
Lists can be repeated using the * operator:
repeated_list = my_list * 2 print(repeated_list) # Output: ['updated', 3,
'new_element', 'b', 'c', 4, 5, 6, 'updated', 3, 'new_element', 'b', 'c', 4, 5, 6]
8. Length:
The len() function returns the length of a list:
print(len(my_list)) # Output: 9
-------------------------------------------------------------------------------------------------------------
exception handling:
Handling exceptions in Python involves using try, except, else, and finally blocks.
def divide_numbers(x, y):
try:
result = x / y
print(f"The result of {x} divided by {y} is: {result}")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Invalid input. Please provide valid numeric values.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
else:
print("The division operation completed successfully.")
finally:
print("This block will always be executed, regardless of whether an exception
occurred.")
# Example usage:
try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
divide_numbers(numerator, denominator)
except ValueError:
print("Invalid input. Please enter numeric values for the numerator and
denominator.")
In this program, we define a function divide_numbers that attempts to perform
division and handle specific exceptions.
----------------------------------------------------------------------------------------------------------------
Multilevel inheritance:
Multi-level inheritance in Python involves creating a chain of classes where each class
extends the previous one.
class Animal:
def __init__(self, species):
self.species = species
def speak(self):
print(f"I am an {self.species}")
class Mammal(Animal):
def __init__(self, species, sound):
super().__init__(species)
self.sound = sound
def make_sound(self):
print(f"{self.species} says {self.sound}")
class Dog(Mammal):
def __init__(self, breed, sound):
super().__init__('Dog', sound)
self.breed = breed
def display_info(self):
print(f"I am a {self.breed} dog")
# Example usage:
dog_instance = Dog('Labrador', 'Woof')
dog_instance.display_info() # Output: I am a Labrador dog
dog_instance.make_sound() # Output: Dog says Woof
dog_instance.speak() # Output: I am an Dog
OPENING MODES:
Python requires file handling for various reasons, such as reading data from files,
writing data to files, and manipulating file content. File handling is essential for tasks
like data storage, data analysis, and communication with external resources. Python
provides built-in functions and methods to open, read, write, and manipulate files
easily.
Opening Files in Python with Modes:
The open() function is used to open files in Python. It takes two arguments: the file
name and the mode in which the file should be opened. The mode specifies the
purpose of opening the file, such as reading, writing, or appending.
1. Read Mode ('r'):
• Open the file for reading.
• If the file doesn't exist, it raises a FileNotFoundError.
• Example: open('filename.txt', 'r')
2. Write Mode ('w'):
• Open the file for writing.
• If the file already exists, it truncates its content.
• If the file doesn't exist, it creates a new file.
• Example: open('filename.txt', 'w')
3. Append Mode ('a'):
• Open the file for appending (writing at the end of the file).
• If the file doesn't exist, it creates a new file.
• Example: open('filename.txt', 'a')
4. Binary Read Mode ('rb'):
• Open the file in binary mode for reading.
• Example: open('filename.bin', 'rb')
5. Binary Write Mode ('wb'):
• Open the file in binary mode for writing.
• Example: open('filename.bin', 'wb')
6. Text Read Mode ('rt' or 'r'):
• Open the file in text mode for reading. (Default)
• Example: open('filename.txt', 'rt') or open('filename.txt', 'r')
7. Text Write Mode ('wt' or 'w'):
• Open the file in text mode for writing. (Default)
• Example: open('filename.txt', 'wt') or open('filename.txt', 'w')
8. Text Append Mode ('at' or 'a'):
• Open the file in text mode for appending. (Default)
• Example: open('filename.txt', 'at') or open('filename.txt', 'a')
OS.PATH.JOIN() is a function in Python's os.path module that is used for
joining one or more path components intelligently. It takes care of handling the
differences in path separators ('/' or '') between operating systems, making it
especially useful for creating platform-independent file paths during directory
traversal.
Significance of os.path.join() in Directory Traversal:

1.Platform Independence:
Different operating systems use different path separators (e.g., '/' on Unix-like
systems and '\' on Windows).
os.path.join() abstracts these differences and generates a path using the correct
separator based on the underlying operating system.

2.Readable and Concise Code:


Manually concatenating paths using string manipulation can lead to errors and is less
readable.
os.path.join() provides a more concise and readable way to create paths, improving
code maintainability.

3.Avoid Hardcoding Separator Characters:


Hardcoding separator characters in paths can make code less adaptable to different
platforms.
os.path.join() ensures that your code is not tied to a specific platform's path
conventions.

Example of os.path.join() in Directory Traversal:


import os
# Example: Traversing directories and creating file paths
base_directory = '/home/user' # Example base directory on Unix-like systems
# Subdirectories
subdir1 = 'documents'
subdir2 = 'photos'
# File name
file_name = 'example.txt
# Using os.path.join() to create a platform-independent file path
file_path = os.path.join(base_directory, subdir1, subdir2, file_name)
# Display the result
print("File Path:", file_path)
THE THREADING module in Python provides a way to create and manage threads.
A thread is a lightweight process that runs independently within a program, allowing
concurrent execution of tasks. Threading is particularly useful for scenarios where
tasks can be executed concurrently, improving program efficiency and
responsiveness.
1. Concurrency:
• Threads allow multiple tasks to run concurrently, making efficient use of
CPU resources.
• Particularly beneficial in I/O-bound tasks where threads can overlap I/O
operations with other computations.
2. Parallelism:
• Although Python's Global Interpreter Lock (GIL) restricts true parallelism
for CPU-bound tasks, threading can still be useful for tasks involving I/O
operations.
• Enables parallel execution of I/O-bound tasks without blocking other
threads.
3. Responsiveness:
• Threading can be employed to keep a program responsive, ensuring that
time-consuming tasks, such as I/O operations, do not block the entire
application.
import requests
import concurrent.futures
def fetch_url(url):
response = requests.get(url)
print(f"Fetched {url}, content length: {len(response.text)}")
urls = [
'https://example.com/page1',
'https://example.com/page2',
'https://example.com/page3',
# Add more URLs as needed
]
with concurrent.futures.ThreadPoolExecutor() as executor:
future_to_url = {executor.submit(fetch_url, url): url for url in urls}
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
try:
future.result()
except Exception as e:
print(f"Error fetching {url}: {e}")
print("All fetches completed.")
----------------------------------------------------------------------------------------------------------------
dictionary operator:
Dictionary Operations in Python:
1. Creating a Dictionary:
To create a dictionary, you can use curly braces {} and specify key-value pairs.
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

2. Accessing Values:
Use square brackets [] and the key to access the value associated with that key.
print(my_dict['name']) # Output: John

3. Adding/Modifying Entries:
To add a new key-value pair or modify an existing one:
my_dict['gender'] = 'Male' # Adding a new entry
my_dict['age'] = 31 # Modifying an existing entry

4. Removing Entries:
To remove a key-value pair, you can use the del statement or the pop() method.
del my_dict['city'] # Removing a specific entry
value = my_dict.pop('age') # Removing and getting the value

5. Dictionary Methods:
Various built-in methods are available for dictionaries:
keys(): Returns a list of all keys.
values(): Returns a list of all values.
items(): Returns a list of key-value pairs as tuples.
keys_list = my_dict.keys()
values_list = my_dict.values()
items_list = my_dict.items()
6. Checking Key Existence:
You can check if a key exists in a dictionary using the in keyword.
if 'name' in my_dict:
print("Key 'name' exists.")
7. Length:
The len() function returns the number of key-value pairs in a dictionary.
length = len(my_dict)
1. Threading:
Using the threading module to create separate threads for handling individual
connections. Each thread can manage its own connection, allowing concurrent
execution.
import threading
import socket
def handle_client(connection, address):
pass
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 8080))
server_socket.listen(5)
while True:
client_socket, client_address = server_socket.accept()
client_thread = threading.Thread(target=handle_client, args=(client_socket,
client_address))
client_thread.start()

. Forking
#A Forking Server
from socketserver import TCPServer, ForkingMixIn, StreamRequestHandler
class Server(ForkingMixIn, TCPServer): pass
class Handler(StreamRequestHandler):
def handle(self):
addr = self.request.getpeername()
print('Got connection from', addr)
self.wfile.write('Thank you for connecting')
server = Server(('', 1234), Handler)
server.serve_forever()

Define URLib:
urllib is a Python module that provides a set of modules for working with URLs. It
includes modules such as urllib.request for opening and reading URLs, urllib.parse for
parsing URLs, urllib.error for exception classes raised by urllib, and urllib.robotparser
for parsing robots.txt files. urllib is part of the Python standard library and is
commonly used for web-related tasks
• Common Gateway Interface (also known as CGI) is a specification(set of
rules) that helps to establish a dynamic interaction between a web
application and the browser (or the client application).
• The CGI programs make possible communication between client and web
servers.
• Whenever the client browser sends a request to the webserver the CGI
programs send the output back to the web server based on the input
provided by the client-server.
▪ CGI is the standard for programs to interface with HTTP servers.
▪ CGI programming is written dynamically generating webpages that respond
to user input or webpages that interact with software on the sector.
Here's an example of a CGI script written in Python. This script will handle a simple
HTML form, receive user input, and display a personalized greeting on a web page.

cgi_example.py (Python CGI Script):


#!/usr/bin/env python
print("Content-type: text/html\n") # HTTP header indicating the content type

# HTML code for the web page


html_content = """
<!DOCTYPE html>
<html>
<head>
<title>CGI Example</title>
</head>
<body>
<h1>CGI Example</h1>
<form method="post" action="">
<label for="name">Enter your name:</label>
<input type="text" id="name" name="name">
<input type="submit" value="Submit">
</form>
<hr>
<p>Output:</p>
<p>{output}</p>
</body>
</html>
import cgi
form = cgi.FieldStorage()
user_name = form.getvalue("name", "Guest") # Default to "Guest" if not provided
output_content = f"Hello, {user_name}! Welcome to CGI Example."
print(html_content.format(output=output_content))
----------------------------------------------------------------------------------------------------------------
socket and email architecture:
Sockets are fundamental building blocks for network communication. They provide a
means for applications on different machines to establish connections and exchange
data over a network. This ability to create interconnected systems is crucial for
various applications, including:
• Web browsing: The client's browser connects to the web server's socket on port
80 to request and receive web pages.
• Email: Email clients and servers use sockets to send and receive email
messages.
• Messaging apps: Chat applications use sockets to connect users and exchange
messages in real-time.
• File sharing: File transfer applications use sockets to transfer files between
devices.
• Online gaming: Games create connections between players using sockets to
enable multiplayer experiences.
Here's a Python program illustrating a simple client-server architecture:
Server-side (server.py):
Python
import socket

HOST = '127.0.0.1' # Standard loopback interface address (localhost)


PORT = 65432 # Port to listen on (non-privileged ports are > 1023)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:


s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
print('Received:', data.decode())
conn.sendall(data) # Echo back the received data
-----------------------------------------------------------------------------------------------------------------
Client-side (client.py):
Python
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
message = 'Hello, world!'.encode()
s.sendall(message)
data = s.recv(1024)
print('Received:', data.decode())
-------------------------------------------------------------------------------------------------------------
Below is an example of a simple Python program using the Tkinter library to create
a window with a menu, text widget, and scroll bars:
import tkinter as tk
from tkinter import scrolledtext
def open_file():
# Dummy function for opening a file
file_content.delete(1.0, tk.END) # Clear existing content
file_content.insert(tk.END, "File content goes here.")
def save_file():
content = file_content.get(1.0, tk.END)
window = tk.Tk()
window.title("Text Editor with Menu")
menu_bar = tk.Menu(window)
file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="Open", command=open_file)
file_menu.add_command(label="Save", command=save_file)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=window.destroy)
menu_bar.add_cascade(label="File", menu=file_menu)
window.config(menu=menu_bar)
file_content = scrolledtext.ScrolledText(window, width=40, height=10,
wrap=tk.WORD)
file_content.pack(padx=10, pady=10)
window.mainloop()
Tkinter
Tkinter is the standard GUI (Graphical User Interface) toolkit that comes bundled
with Python. It provides a set of Python interfaces to the Tk GUItoolkit, a widely used
and powerful library for building graphical user interfaces. Tkinter allows
developersto create interactive and visually appealing desktop applications with
ease.
To create a tkinter Python app:
1. Importing the module– tkinter
2. Create the main window (container)
3. Add any number of widgets to the main window
4. Apply the event Trigger on the widgets.
Significance of Tkinter:
1. Ease of Use
2. Integration with Python
Role in Building Graphical User Interfaces:
1. WIDGET LIBRARY:
Tkinter provides a rich set of built-in GUI elements or widgets, such as buttons,
labels, textboxes, and more. These widgets can be easily incorporated into
applications, allowing developers to create responsive and feature-rich user
interfaces.
2. Cross-Platform Compatibility:
It is platform-independent, meaning that applications developedusing Tkinter can
run on various operating systems without modification. This cross-platform
compatibility enhances the portability of Tkinter-based applications.
Key Features or Characteristics Distinguishing Tkinter:
1. Standard library inclusion
2. Simplicity and Readability
Tkinter is a significant and widely used GUI toolkit in Python programming due to its
ease of use, seamless integration with Python, and the ability to create cross
platform graphical user interfaces. Its standard library inclusion and simplicity set it
apart from other GUI toolkits, making it a popular choice for developers seeking to
buildinteractive applications with Python.There are two main methods used which
the user needs to rememberwhile creating the Python application with GUI.
1. Tk(screenName=None, baseName=None, className=’Tk’,
useTk=1):
This method is used to create a main window. To change the name of the window,
you can change the className to the desired one. The basic code used to create
themain window of the application is:
m=tkinter.Tk() where m is the name of the main window object
2. mainloop():
There is a method known by the name mainloop() is used whenyour application is
ready to run. mainloop() is an infinite loop used to run the application, wait for an
event to occur and process the event as long as the window is not closed.
m.mainloop()
Example:
import tkinter
m=tkinter.Tk()
'''
widgets are added here
'''
m.mainloop()
-----------------------------------------------------------------------------------------------------------------
To perform Insert, Delete, and Update operations on a database in Python, you can
use the SQLite database and the sqlite3 module, which is part of the Python
standard library. Here's an example code demonstrating these operations:
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER,
department TEXT
)''')
def insert_employee(name, age, department):
cursor.execute('''INSERT INTO employees (name, age, department)
VALUES (?, ?, ?)''', (name, age, department))
conn.commit()
def delete_employee(employee_id):
cursor.execute('''DELETE FROM employees WHERE id = ?''', (employee_id,))
conn.commit()
def update_employee(employee_id, name, age, department):
cursor.execute('''UPDATE employees SET name = ?, age = ?, department = ?
WHERE id = ?''', (name, age, department, employee_id))
conn.commit()
def display_employees():
cursor.execute('''SELECT * FROM employees''')
employees = cursor.fetchall()
print("ID\tName\t\tAge\tDepartment")
print("-" * 40)
for employee in employees:
print(f"{employee[0]}\t{employee[1]}\t\t{employee[2]}\t{employee[3]}")
insert_employee('John Doe', 30, 'IT')
insert_employee('Jane Smith', 25, 'HR')
print("Employees before any changes:")
display_employees()
update_employee(1, 'John Smith', 32, 'IT')
print("\nEmployee information updated:")
display_employees()
delete_employee(2)
print("\nEmployee deleted:")
display_employees()
cursor.close()
conn.close()

List Boxes in Tkinter:

In Tkinter, a Listbox is a widget that displays a list of items from which the user can
make selections. It provides a user-friendly way to present a list of options, allowing
users to choose one or more items. List boxes are commonly used in GUI
applications to offer selection choices in a clear and organized manner.
Purpose of List Boxes:

Selection: List boxes allow users to select one or more items from a predefined list.
Display: They provide a visible list of options, making it easy for users to see
available choices.
Organization: List boxes help organize and present choices in a structured way,
improving the user experience.

Here's a simple example of creating a Tkinter window with a Listbox, adding items
to it, and retrieving the selected item:
import tkinter as tk
def on_select(event):
selected_index = listbox.curselection()
if selected_index:
selected_item = listbox.get(selected_index[0])
result_label.config(text=f"Selected Item: {selected_item}")
window = tk.Tk()
window.title("List Box Example")
listbox = tk.Listbox(window, selectmode=tk.SINGLE)
listbox.pack(pady=10)
items = ["Item 1", "Item 2", "Item 3", "Item 4"]
for item in items:
listbox.insert(tk.END, item)
listbox.bind("<<ListboxSelect>>", on_select)
result_label = tk.Label(window, text="Selected Item: None")
result_label.pack(pady=10)
window.mainloop()
squares_of_evens = [x ** 2 for x in range(1, 21) if x % 2 == 0]
print(squares_of_evens)

Parallel programming in Python can be achieved using various approaches. One


common method is to use the concurrent.futures module, which provides a high-
level interface for asynchronously executing functions in parallel. Here's a simple
example using the ThreadPoolExecutor class to parallelize a task:
import concurrent.futures
import time
def simulate_task(task_id):
print(f"Task {task_id} started.")
time.sleep(2) # Simulating a time-consuming task
print(f"Task {task_id} completed.")
return f"Result of Task {task_id}"
def main():
tasks = [1, 2, 3, 4, 5]
with concurrent.futures.ThreadPoolExecutor() as executor:
# Using the map function to parallelize the task execution
results = list(executor.map(simulate_task, tasks))
print("All tasks completed.")
for result in results:
print(result)
if __name__ == "__main__":
main()
1]In what ways Parallel processing is achieved in Python?
• Multiprocessing Module

• Threading Module

• Asyncio Module

• Parallel computing libraries

2] Define URLError:
• URLError is an exception class in Python's urllib.error module.
• It is raised when a URL-related error occurs during the execution of a
program using urllib. This can include errors such as a failed connection to
the server, inability to resolve the host, or other network-related issues.
• Handling URLError allows a program to respond appropriately to problems
encountered when working with URLs.

3] Essential Features of Python Tkinter:


• Simplicity
• Platform Independence
• Wide Range of Widgets
• Event-Driven Programming
• Integration with Python

4] Differentiate Insert and Update Operations in Database:


• Insert Operation:
• Inserts new records or rows into a database table.

• If the specified primary key or unique constraint already exists, the

insertion might fail or be ignored.


• Typically used to add new data to a table.

• Update Operation:
• Modifies existing records or rows in a database table.

• Requires specifying a condition (e.g., using WHERE clause) to

identify the records to be updated.


• Allows changing values of one or more columns in the identified

records.
• Used to update existing data in a table.

You might also like