Guess - Solutions - Python
Guess - Solutions - Python
Guess - Solutions - Python
Python
Programming
1. Define Strings, Dictionaries, lists and tuples along with their functions.
2. Explain looping statements in python.
3. Explain functions and lambda functions.
4. Explain packages and modules.
5. List and explain different file handling functions.
6. How to perform Password, email, url validation using regular expression.
7. What is Exception handling in python.
8. How to connect SQL database in python? Perform basic operations.
9. What is Artificial Intelligence? Explain features and applications.
10. Differentiate between informed and uninformed search?
11. Differentiate between supervised and unsupervised learning?
12. Write short notes:
a. Task planning
b. Robot motion planning.
c. Reinforcement Learning
d. Min-max game playing.
Strings: A string is a sequence of characters enclosed within single (' '), double (" "), or
triple quotes (''' ''' or """ """). Strings are immutable, meaning their content cannot be
changed after creation.
Functions of stings:
split(separator) Splits string into a list. "Hello World".split(" ") ['Hello', 'World']
Functions:
get(key) Returns the value for the specified key. student.get("name") 'Alice'
keys() Returns all keys as a view object. student.keys() dict_keys(['name', 'age', 'grade'])
values() Returns all values as a view object. student.values() dict_values(['Alice', 20, 'A'])
pop(key) Removes and returns the value of the key. student.pop("grade") 'A' (Remaining: {'name': ...})
popitem() Removes and returns the last key-value student.popitem() Last item as tuple.
pair.
Example
A list is an ordered, mutable collection in Python that can store elements of any data
type. Lists are defined using square brackets [ ].
pop(index) Removes and returns an element by index. my_list.pop(2) 3 (List: [1, 2, 4, 5])
Functions:
Example:
Looping statements in Python are used to execute a block of code repeatedly as long
as a condition is true or for a specific number of iterations. Python provides two primary
looping statements: for loop and while loop.
1. for Loop: The for loop iterates over a sequence (like a list, tuple, dictionary, string, or
range) and executes the block of code for each element.
2. while Loop: The while loop continues to execute a block of code as long as the
specified condition is True.
Types of Functions:
Advantages:
Code reusability.
Improved readability.
Easier to debug and maintain.
Lambda Functions: A lambda function is a small, anonymous function that can have
any number of arguments but only one expression. It is often used for short, simple
operations.
Key Characteristics:
Creating a Module: Save a Python file with a .py extension, e.g., mymodule.py.
Using a Module: Import the module into your program using the import statement.
Types of Modules:
Structure of a Package:
mypackage/
├── __init__.py
├── module1.py
├── module2.py
Example:
Module (module1.py):
Package (mypackage):
File handling in Python refers to the process of working with files in a program. Python
provides built-in functions to read from and write to files, manage file contents, and
perform various operations on files, such as creating, opening, closing, and modifying
them.
File Operations: Common file operations include:
Opening a file: Before performing any action on a file, it must be opened.
Reading from a file: Extracting content from a file.
Writing to a file: Adding or modifying content in a file.
Closing a file: Closing the file once operations are completed.
File deletion/renaming: Removing or renaming files.
1: open(): The open() function is used to open a file in a specified mode (read, write,
append, etc.).
Syntax:
2: read(): The read() function is used to read the content of the file. It reads the entire
file or a specific number of bytes.
Syntax:
size: The number of bytes to read. If not specified, it reads the entire file.
4: close(): The close() function is used to close the file after performing the required
operations, ensuring resources are released.
5: readline() The readline() function is used to read one line at a time from the file. It’s
useful when working with large files that you want to read line by line.
Syntax:
File Functions
readline() Reads one line at a time from the file line = file.readline()
In Python, the re module is used to work with regular expressions (regex). You can use
regex patterns to validate various inputs, such as passwords, email addresses, and
URLs. Below are examples of how to validate passwords, emails, and URLs using regular
expressions:
Key Components:
try block: The code that may raise an exception is placed inside the try block.
except block: The except block contains the code that should execute if an
exception occurs. You can catch specific exceptions (e.g., ZeroDivisionError,
FileNotFoundError) or use a general Exception to catch any error.
else block (Optional): If no exception occurs in the try block, the else block runs.
finally block (Optional): The finally block will always execute, regardless of
whether an exception occurs. It is often used for cleanup tasks (e.g., closing files,
releasing resources).
Example:
Create Table CREATE TABLE table_name (columns) cursor.execute('CREATE TABLE users (id INTEGER
PRIMARY KEY, name TEXT)')
Insert Data INSERT INTO table_name (columns) cursor.execute('INSERT INTO users (name, email)
VALUES (values) VALUES (?, ?)', ('Alice', 'alice@example.com'))
Update Data UPDATE table_name SET column = cursor.execute('UPDATE users SET name = "Bob" WHERE
value WHERE condition id = 1')
Delete Data DELETE FROM table_name WHERE cursor.execute('DELETE FROM users WHERE id = 1')
condition
Efficiency More efficient as it narrows down the Less efficient as it explores the entire
search space using heuristics. search space without guidance.
Optimality Can find the optimal solution if the May not find the optimal solution
heuristic is admissible (A*). depending on the search strategy.
Space May require more memory for storing Typically has lower space complexity
Complexity nodes with heuristic values. compared to informed search.
1. Supervised learning
Supervised learning is a type of machine learning where the model is trained on
labeled data. In this approach, the algorithm learns from the input-output pairs, where
the input data is associated with the correct output (label). The model tries to predict
the output based on the input during training and is evaluated on its ability to correctly
predict the output for unseen data.
Characteristics:
Labeled data: The training dataset consists of input-output pairs where the
correct answer is provided.
Goal: The aim is to learn a mapping function that can predict the output for new,
unseen data.
Model feedback: The model is trained by adjusting its parameters based on the
error between predicted and actual values.
Examples of Supervised Learning Algorithms:
Linear Regression: Used for predicting continuous values (e.g., predicting house
prices).
Logistic Regression: Used for binary classification (e.g., spam vs. non-spam
email).
Decision Trees: Used for both classification and regression.
Support Vector Machines (SVM): Used for classification and regression tasks.
Neural Networks: Can be used for complex classification and regression
problems.
Applications:
Email spam detection (classifying emails as spam or not).
Image classification (e.g., classifying photos into categories like "dog" or "cat").
Fraud detection (predicting whether a transaction is fraudulent).
Feedback Model is trained using feedback from No direct feedback or labels; the model tries
correct labels. to find patterns.
1. Task Planning
Task planning in artificial intelligence involves creating a sequence of actions that a
system or robot must follow to achieve a specific goal. The system is tasked with
deciding which actions to perform and in what order to accomplish the desired
outcome, given certain constraints and resources.
Key Concepts:
Goal State: The desired outcome that needs to be achieved.
Actions: The individual operations or steps that bring the system closer to the
goal.
Constraints: Limitations or conditions that must be met during the task execution.
Plan Execution: After generating a plan, it is executed step by step.
Applications:
Automated scheduling.
Task execution in robotics and virtual assistants.
Workflow automation in software systems.
2. Robot Motion Planning
Robot motion planning is the process of determining the path that a robot must follow
to move from a start position to a goal position while avoiding obstacles and
minimizing certain costs (e.g., time, energy). It involves computing a feasible trajectory
in the robot's environment.
Key Concepts:
Configuration Space (C-space): Represents all possible positions and
orientations of the robot.
Pathfinding Algorithms: Algorithms like A* or Dijkstra are used to find the shortest
or optimal path.
Obstacle Avoidance: Ensuring that the path does not collide with any obstacles.
Trajectory Planning: Determining not just the path but also the speed and timing
of movements.
Applications:
Autonomous vehicles.
Industrial robots in manufacturing.
Drones navigating through complex environments.
Key Concepts:
Agent: The entity that performs actions.
Environment: The external system with which the agent interacts.
State: A snapshot of the environment at a given time.
Action: The choices the agent can make.
Reward: A feedback signal indicating the quality of the agent’s action.
Policy: A strategy or mapping from states to actions.
Value Function: A measure of the long-term reward expected from each state.
Applications:
Game playing (e.g., AlphaGo, Chess).
Robotics (e.g., learning to walk or manipulate objects).
Autonomous vehicles (e.g., path planning).
Key Concepts:
Maximizing Player: The player trying to maximize their score.
Minimizing Player: The opponent trying to minimize the maximizing player's score.
Game Tree: A tree representing all possible moves and outcomes of the game.
Minimax Strategy: The maximizing player chooses the move that maximizes the
minimum payoff, while the minimizing player chooses the move that minimizes
the maximum payoff.
Applications:
Chess and other strategy games.
Decision-making in competitive environments with two players.
AI-based game engines (e.g., for tic-tac-toe, checkers).
Team Harshit