0% found this document useful (0 votes)
15 views24 pages

Understanding Algorithms and Computer Basics

This document provides an introduction to algorithms, their applications in various fields, and their characteristics. It also explains the distinction between computer hardware and software, detailing their definitions, types, and differences. Additionally, it covers Python dictionaries and sets, including their creation, manipulation, and key features.

Uploaded by

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

Understanding Algorithms and Computer Basics

This document provides an introduction to algorithms, their applications in various fields, and their characteristics. It also explains the distinction between computer hardware and software, detailing their definitions, types, and differences. Additionally, it covers Python dictionaries and sets, including their creation, manipulation, and key features.

Uploaded by

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

UNIT-1

What is an Algorithm | Introduction to Algorithms

The word Algorithm means "A set of finite rules or instructions to be followed in calculations
or other problem-solving operations" Or "A procedure for solving a mathematical problem in
a finite number of steps that frequently involves recursive operations".

Therefore Algorithm refers to a sequence of finite steps to solve a particular problem.

Use of the Algorithms:

Algorithms play a crucial role in various fields and have many applications. Some of the key
areas where algorithms are used include:

1. Computer Science: Algorithms form the basis of computer programming and are
used to solve problems ranging from simple sorting and searching to complex tasks
such as artificial intelligence and machine learning.

2. Mathematics: Algorithms are used to solve mathematical problems, such as finding


the optimal solution to a system of linear equations or finding the shortest path in a
graph.

3. Operations Research: Algorithms are used to optimize and make decisions in fields
such as transportation, logistics, and resource allocation.

4. Artificial Intelligence: Algorithms are the foundation of artificial intelligence and


machine learning, and are used to develop intelligent systems that can perform tasks
such as image recognition, natural language processing, and decision-making.

5. Data Science: Algorithms are used to analyze, process, and extract insights from large
amounts of data in fields such as marketing, finance, and healthcare.
These are just a few examples of the many applications of algorithms. The use of algorithms
is continually expanding as new technologies and fields emerge, making it a vital component
of modern society.

Algorithms can be simple and complex depending on what you want to achieve.

It can be understood by taking the example of cooking a new recipe. To cook a new recipe,
one reads the instructions and steps and executes them one by one, in the given sequence.
The result thus obtained is the new dish is cooked perfectly. Every time you use your phone,
computer, laptop, or calculator you are using Algorithms. Similarly, algorithms help to do a
task in programming to get the expected output.

The Algorithm designed are language-independent, i.e. they are just plain instructions that
can be implemented in any language, and yet the output will be the same, as expected.

What is the need for algorithms?

1. Algorithms are necessary for solving complex problems efficiently and effectively.

2. They help to automate processes and make them more reliable, faster, and easier to
perform.

3. Algorithms also enable computers to perform tasks that would be difficult or


impossible for humans to do manually.

4. They are used in various fields such as mathematics, computer science, engineering,
finance, and many others to optimize processes, analyze data, make predictions, and
provide solutions to problems.

What are the Characteristics of an Algorithm?

As one would not follow any written instructions to cook the recipe, but only the standard
one. Similarly, not all written instructions for programming are an algorithm. For some
instructions to be an algorithm, it must have the following characteristics:
 Clear and Unambiguous: The algorithm should be unambiguous. Each of its steps
should be clear in all aspects and must lead to only one meaning.

 Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined


inputs. It may or may not take input.

 Well-Defined Outputs: The algorithm must clearly define what output will be yielded
and it should be well-defined as well. It should produce at least 1 output.

 Finite-ness: The algorithm must be finite, i.e. it should terminate after a finite time.

 Feasible: The algorithm must be simple, generic, and practical, such that it can be
executed with the available resources. It must not contain some future technology or
anything.

 Language Independent: The Algorithm designed must be language-independent, i.e.


it must be just plain instructions that can be implemented in any language, and yet
the output will be the same, as expected.

 Input: An algorithm has zero or more inputs. Each that contains a fundamental
operator must accept zero or more inputs.

 Output: An algorithm produces at least one output. Every instruction that contains a
fundamental operator must accept zero or more inputs.

 Definiteness: All instructions in an algorithm must be unambiguous, precise, and


easy to interpret. By referring to any of the instructions in an algorithm one can
clearly understand what is to be done. Every fundamental operator in instruction
must be defined without any ambiguity.

 Finiteness: An algorithm must terminate after a finite number of steps in all test
cases. Every instruction which contains a fundamental operator must be terminated
within a finite amount of time. Infinite loops or recursive functions without base
conditions do not possess finiteness.

 Effectiveness: An algorithm must be developed by using very basic, simple, and


feasible operations so that one can trace it out by using just paper and pencil.

Properties of Algorithm:

 It should terminate after a finite time.

 It should produce at least one output.

 It should take zero or more input.

 It should be deterministic means giving the same output for the same input case.

 Every step in the algorithm must be effective i.e. every step should do some work.
Advantages of Algorithms:

 It is easy to understand.

 An algorithm is a step-wise representation of a solution to a given problem.

 In an Algorithm the problem is broken down into smaller pieces or steps hence, it is
easier for the programmer to convert it into an actual program.

Disadvantages of Algorithms:

 Writing an algorithm takes a long time so it is time-consuming.

 Understanding complex logic through algorithms can be very difficult.

 Branching and Looping statements are difficult to show in Algorithms(imp).

How to Design an Algorithm?

To write an algorithm, the following things are needed as a pre-requisite:

1. The problem that is to be solved by this algorithm i.e. clear problem definition.

2. The constraints of the problem must be considered while solving the problem.

3. The input to be taken to solve the problem.

4. The output is to be expected when the problem is solved.

5. The solution to this problem is within the given constraints.

COMPUTER HARDWARE AND SOFTWARE


A computer system consists of two main parts: Hardware and Software.
Hardware refers to the physical components, like the CPU and RAM, while
Software includes the programs and applications that control these components.
Both are essential for the computer to function properly, and they work together
to ensure smooth performance.
What is the Computer Hardware?
Computer hardware refers to the physical components of a computer that you can
touch and see. These parts work together to process data and perform tasks. Examples
include the Processor, Memory Devices, Monitor, Printer, Keyboard, Mouse,
and Central Processing Unit (CPU).
Different Types of Computer Hardware
Here is a list of the main types of computer hardware:
1. Input Devices
Input devices allow users to enter data and instructions into the computer. These
devices enable interaction with the system by providing information for processing.
Examples: Keyboard, Mouse, Scanner, Microphone.
2. Output Devices
Output devices display or produce the results of computer processing, allowing users
to see or hear the information processed by the computer.
Examples: Monitor, Printer, Speakers.s.
3. Storage Devices
Storage devices are used to store data either temporarily or permanently. They allow
the computer to save information for later retrieval.
Examples: Hard Disk Drive (HDD), Solid-State Drive (SSD), USB Drives, CDs,
DVDs.
4. Internal Components
Internal components are essential hardware parts inside the computer that process and
manage data, enabling the system to run efficiently.
Examples: CPU (Central Processing Unit), Motherboard, RAM (Random Access
Memory), GPU (Graphics Processing Unit).
What is the Computer Software?
Software is a collection of instructions, procedures, and documentation that performs
different tasks on a computer system. We can say also Computer Software is a
programming code executed on a computer processor. The code can be machine-level
code or code written for an operating system.
Examples of software are MS- Word, Excel, PowerPoint, Google Chrome, Photoshop,
MySQL, etc.
Different Types of Computer Software
Here is a list of the main types of computer software:
1. System Software
System software is responsible for directly interacting with computer hardware and
managing its internal functions. It helps control hardware devices such as printers,
storage devices, and more.
Examples of System Software: Operating Systems, Language Processors, Device
Drivers.
2. Application Software
Application software is designed to perform specific tasks for users. It operates on top
of system software and supports everyday computer functions.
Examples of Application Software: Word Processors, Spreadsheets, and more
specialized software like graphic design tools or database management systems.
Also read, Software and Types.

Difference Between Hardware and Software

Paramet Hardware Software


ers
Basic Hardware is Software is a set of instructions
Definition a physical that tells a computer exactly what
part of the to do.
computer
that causes
the
processing
of data.
Develop It is It is developed and engineered.
ment manufacture
d.
Depende Hardware The software can not be executed
ncy cannot without hardware.
perform any
task without
software.
Process Electronic Created by utilizing a computer
of and other language to write instructions.
creating materials are
used to
create
hardware.
Tangible Hardware is Software is intangible as we can
tangible as see and also use the software but
hardware is can’t touch them.
a physical
electronic
device, that
can be
touched.
Durabili Hardware The software does not wear out
ty typically with time. However, it may
wears out contain flaws and glitches.
over time.
Types It has four It is mainly divided into
main  System software
categories:  Application software.
 Input
Devices
 Output
Devices
 Storage
Devices
 Internal
Components
.
Virus Hardware is Software is affected by computer
effect not affected viruses.
by computer
viruses.
Transfer It cannot be It can be transferred via a network
transferred means.
from one
place to
another
electrically
through the
network.
Machine Only The program accepts human-
-Level machine- readable input, interprets it in
languag level machine-level language, and sends
e language is it to hardware for additional
known to be processing.
understood
by
hardware.
Replace If the If the software is damaged, its
ment hardware is backup copy can be reinstalled.
damaged, it
is replaced
with a new
one.
Failures Dust, Overloading, systematic error,
overheating, major-minor version error, and
humidity, other factors are commonly
and other responsible for software failures.
factors are
commonly
responsible
for hardware
failures.
Exampl Ex: Ex: MS
es Keyboard, Word, Excel, PowerPoint, Photosh
Mouse, op, MySQL, etc.
Monitor,
Printer, CPU
, Hard
disk, RAM,
ROM, etc.
Conclusion
In conclusion, Hardware refers to the physical component of any
computer whereas Software is the set of instructions that let the computer
know what to execute and when to execute. Both Hardware and Software
are different, but their inter-dependencies help the entire execution of any
operating system.

UNIT-V

Dictionaries and Sets

Python Dictionaries

Python dictionary is a data structure that stores the value in key: value pairs. Values in
a dictionary can be of any data type and can be duplicated, whereas keys can't be
repeated and must be immutable.
 Keys are case sensitive which means same name but different cases of Key will be
treated distinctly.
 Keys must be immutable which means keys can be strings, numbers or tuples but not
lists.
 Duplicate keys are not allowed and any duplicate key will overwrite the previous
value.
 Internally uses hashing. Hence, operations like search, insert, delete can be performed
in Constant Time.
 From Python 3.7 Version onward, Python dictionary are Ordered.
How to Create a Dictionary
Dictionary can be created by placing a sequence of elements within curly {}
braces, separated by a 'comma'.
d1 = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d1)

# create dictionary using dict() constructor


d2 = dict(a = "Geeks", b = "for", c = "Geeks")
print(d2)

Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{'a': 'Geeks', 'b': 'for', 'c': 'Geeks'}
Accessing Dictionary Items
We can access a value from a dictionary by using the key within square brackets
or get() method.
d = { "name": "Prajjwal", 1: "Python", (1, 2): [1,2,4] }

# Access using key


print(d["name"])

# Access using get()


print([Link]("name"))

Output
Prajjwal
Prajjwal
Adding and Updating Dictionary Items
We can add new key-value pairs or update existing keys by using assignment.
d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
# Adding a new key-value pair
d["age"] = 22

# Updating an existing value


d[1] = "Python dict"

print(d)

Output
{1: 'Python dict', 2: 'For', 3: 'Geeks', 'age': 22}
Removing Dictionary Items
We can remove items from dictionary using the following methods:
 del: Removes an item by key.
 pop(): Removes an item by key and returns its value.
 clear(): Empties the dictionary.
 popitem(): Removes and returns the last key-value pair.
d = {1: 'Geeks', 2: 'For', 3: 'Geeks', 'age':22}

# Using del to remove an item


del d["age"]
print(d)

# Using pop() to remove an item and return the value


val = [Link](1)
print(val)

# Using popitem to removes and returns


# the last key-value pair.
key, val = [Link]()
print(f"Key: {key}, Value: {val}")
# Clear all items from the dictionary
[Link]()
print(d)

Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Geeks
Key: 3, Value: Geeks
{}
Iterating Through a Dictionary
We can iterate over keys [using keys() method] , values [using values() method]
or both [using item() method] with a for loop.
d = {1: 'Geeks', 2: 'For', 'age':22}

# Iterate over keys


for key in d:
print(key)

# Iterate over values


for value in [Link]():
print(value)

# Iterate over key-value pairs


for key, value in [Link]():
print(f"{key}: {value}")

Output
1
2
age
Geeks
For
22
1: Geeks
2: For
age: 22
Nested Dictionaries

Python Collections (Arrays)

There are four collection data types in the Python programming language:

 List is a collection which is ordered and changeable. Allows duplicate members.

 Tuple is a collection which is ordered and unchangeable. Allows duplicate


members.

 Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate


members.

 Dictionary is a collection which is ordered** and changeable. No duplicate


members.

Python Set Data Type

A set in Python is a built-in data type used to store unordered, unique, and
mutable collections of elements. Sets are particularly useful when you need to
eliminate duplicates or perform mathematical set operations like union,
intersection, and difference.

Key Features of Sets


1. Unordered: The elements in a set do not have a defined order, and their
arrangement may change.

2. Unique Elements: A set automatically removes duplicate elements.

3. Mutable: You can add or remove elements from a set (except for frozen sets, which
are immutable).

4. Heterogeneous: A set can contain elements of different data types (e.g., integers,
strings, booleans).

Creating a Set

You can create a set using curly braces {} or the set() constructor.

Python

# Example 1: Using curly braces

my_set = {1, 2, 3, 4, 5}

# Example 2: Using set() constructor

another_set = set([1, 2, 3, 3, 4]) # Duplicates are removed

Common Set Methods

Here are some commonly used methods:

 Adding Elements:

Python

my_set.add(6) # Adds 6 to the set

 Removing Elements:

Python

my_set.remove(3) # Removes 3; raises KeyError if not found

my_set.discard(3) # Removes 3; does nothing if not found

 Set Operations:

Python
set1 = {1, 2, 3}

set2 = {3, 4, 5}

union_set = [Link](set2) # {1, 2, 3, 4, 5}

intersection_set = [Link](set2) # {3}

difference_set = [Link](set2) # {1, 2}

 Checking Membership:

Python

print(2 in my_set) # True

print(10 in my_set) # False

Frozen Sets

A frozen set is an immutable version of a set. Once created, its elements cannot be
modified.

Python

frozen = frozenset([1, 2, 3])

# [Link](4) # Raises AttributeError

Use Cases

 Removing duplicates from a list.

 Performing mathematical set operations.

 Checking membership efficiently.

Sets are a powerful and efficient tool for managing collections of unique items in
Python!

OPENING, READING, AND WRITING TEXT FILES IN


PYTHON:

📁 1. Opening a Text File


Use the built-in open() function:

file = open("[Link]", "r") # "r" = read mode

Modes:

Mode Description

"r" Read (default). File must exist.

"w" Write. Creates file or overwrites it.

"a" Append. Creates file or appends to existing.

"r+" Read and write. File must exist.

📖 2. Reading a Text File

file = open("[Link]", "r")

content = [Link]()

print(content)

[Link]()

Other ways to read:

[Link]() # Reads one line

[Link]() # Returns a list of all lines

✅ Always close the file after you're done using .close() or use a with block.

✅ Using with Statement

with open("[Link]", "r") as file:

content = [Link]()

print(content)

# File is automatically closed here

✍️3. Writing to a Text File

with open("[Link]", "w") as file:

[Link]("Hello, world!\n")
[Link]("This is a new line.")

 This overwrites the file.

 Use "a" to append instead:

with open("[Link]", "a") as file:

[Link]("\nAppended line.")

📝 4. Reading and Writing Together

with open("[Link]", "r+") as file:

content = [Link]()

[Link]("\nAdding more after reading.")

🧠 Summary

Action Code Example

Open file open("[Link]", "r")

Read file [Link]()

Write file [Link]("text")

Append to file open("[Link]", "a")

Auto-close with open(...) as file:

PYTHON EXCEPTION HANDLING:

Python Exception Handling allows a program to gracefully handle unexpected events


(like invalid input or missing files) without crashing. Instead of terminating abruptly,
Python lets you detect the problem, respond to it, and continue execution when

possible.

EXAMPLE:

Basic Example: Handling Simple Exception

Here’s a basic example demonstrating how to catch an exception and handle it


gracefully:

n = 10

try:

res = n / 0

except ZeroDivisionError:

print("Can't be divided by zero!")

Output

Can't be divided by zero!

Explanation: Dividing a number by 0 raises a ZeroDivisionError. The try block


contains code that may fail and except block catches the error, printing a safe
message instead of stopping the program.

DIFFERENCE BETWEEN ERRORS AND EXCEPTIONS

Errors and exceptions are both issues in a program, but they differ in severity and
handling.

 Error: Serious problems in the program logic that cannot be handled. Examples
include syntax errors or memory errors.

 Exception: Less severe problems that occur at runtime and can be managed using
exception handling (e.g., invalid input, missing files).

Example: This example shows the difference between a syntax error and a runtime
exception.

# Syntax Error (Error)

print("Hello world" # Missing closing parenthesis

# ZeroDivisionError (Exception)

n = 10
res = n / 0

Explanation: A syntax error stops the code from running at all, while an exception
like ZeroDivisionError occurs during execution and can be caught with exception
handling.

Syntax and Usage

Python provides four main keywords for handling exceptions: try, except, else and
finally each plays a unique role. Let's see syntax:

try:
# Code
except SomeException:
# Code
else:
# Code
finally:
# Code

 try: Runs the risky code that might cause an error.

 except: Catches and handles the error if one occurs.

 else: Executes only if no exception occurs in try.

 finally: Runs regardless of what happens useful for cleanup tasks like closing files.

Example: This code attempts division and handles errors gracefully using try-
except-else-finally.

try:

n=0

res = 100 / n

except ZeroDivisionError:

print("You can't divide by zero!")

except ValueError:

print("Enter a valid number!")


else:

print("Result is", res)

finally:

print("Execution complete.")

Output

You can't divide by zero!

Execution complete.

Explanation: try block attempts division, except blocks catch specific errors, else
block executes only if no errors occur, while finally block always runs, signaling end
of execution.

Please refer Python Built-in Exceptions for some common exceptions.

Python Catching Exceptions

When working with exceptions in Python, we can handle errors more efficiently by
specifying the types of exceptions we expect. This can make code both safer and
easier to debug.

1. Catching Specific Exceptions

Catching specific exceptions makes code to respond to different exception types


differently. It precisely makes your code safer and easier to debug. It avoids
masking bugs by only reacting to the exact problems you expect.

Example: This code handles ValueError and ZeroDivisionError with different


messages.

try:

x = int("str") # This will cause ValueError

inv = 1 / x # Inverse calculation

except ValueError:

print("Not Valid!")
except ZeroDivisionError:

print("Zero has no inverse!")

Output

Not Valid!

Explanation: A ValueError occurs because "str" cannot be converted to an integer. If


conversion had succeeded but x were 0, a ZeroDivisionError would have been
caught instead.

2. Catching Multiple Exceptions

We can catch multiple exceptions in a single block if we need to handle them in the
same way or we can separate them if different types of exceptions require different
handling.

Example: This code attempts to convert list elements and handles ValueError,
TypeError and IndexError.

a = ["10", "twenty", 30] # Mixed list of integers and strings

try:

total = int(a[0]) + int(a[1]) # 'twenty' cannot be converted to int

except (ValueError, TypeError) as e:

print("Error", e)

except IndexError:

print("Index out of range.")

Output

Error invalid literal for int() with base 10: 'twenty'

Explanation: The ValueError is raised when trying to convert "twenty" to an integer.


A TypeError could occur if incompatible types were used, while IndexError would
trigger if the list index was out of range.
3. Catch-All Handlers and Their Risks

Sometimes we may use a catch-all handler to catch any exception, but it can hide
useful debugging info.

Example: This code tries dividing a string by a number, which causes a TypeError.

try:

res = "100" / 20 # Risky operation: dividing string by number

except ArithmeticError:

print("Arithmetic problem.")

except:

print("Something went wrong!")

Output

Something went wrong!

Explanation: A TypeError occurs because you can’t divide a string by a number. The
bare except catches it, but this can make debugging harder since the actual error
type is hidden. Use bare except only as a last-resort safety net.

Raise an Exception

We raise an exception in Python using the raise keyword followed by an instance of


the exception class that we want to trigger. We can choose from built-in exceptions
or define our own custom exceptions by inheriting from Python's built-in Exception
class.

Basic Syntax:

raise ExceptionType("Error message")

Example: This code raises a ValueError if an invalid age is given.

def set(age):

if age < 0:

raise ValueError("Age cannot be negative.")


print(f"Age set to {age}")

try:

set(-5)

except ValueError as e:

print(e)

Output

Age cannot be negative.

Explanation: The function checks if age is invalid. If it is, it raises a ValueError. This
prevents invalid states from entering the program.

Custom Exceptions

You can also create custom exceptions by defining a new class that inherits from
Python’s built-in Exception class. This is useful for application-specific errors. Let's
see an example to understand how.

Example: This code defines a custom AgeError and uses it for validation.

class AgeError(Exception):

pass

def set(age):

if age < 0:

raise AgeError("Age cannot be negative.")

print(f"Age set to {age}")

try:

set(-5)

except AgeError as e:

print(e)

Output
Age cannot be negative.

Explanation: Here, AgeError is a custom exception type. This makes error messages
more meaningful in larger applications.

Advantages

Below are some benefits of using exception handling:

 Improved reliability: Programs don’t crash on unexpected input.

 Separation of concerns: Error-handling code stays separate from business logic.

 Cleaner code: Fewer conditional checks scattered in code.

 Helpful debugging: Tracebacks show exactly where the problem occurred.

Disadvantages

Exception handling have some cons as well which are listed below:

 Performance overhead: Handling exceptions is slower than simple condition checks.

 Added complexity: Multiple exception types may complicate code.

 Security risks: Poorly handled exceptions might leak sensitive details.

You might also like