Unit I
Unit I
The straightforward meaning of a computer is a machine that can calculate. However, modern
computers are not just a calculating device anymore. They can perform a variety of tasks. In
simple terms, a computer is a programmable electronic machine used to store, retrieve, and
process data.
According to the definition, "A computer is a programmable electronic device that takes
data, perform instructed arithmetic and logical operations, and gives the output."
Whatever is given to the computer as input is called 'data', while the output received after
processing is called 'information'
. The term 'Computer' was first introduced in 1640 and referred to as 'one who
calculates'. It was derived from the Latin word 'computare', which meant 'to calculate'.
. In 1897, it was known as the 'calculating machine'. Later in 1945, the term
'computer' was introduced as 'programmable digital electronic computer, which is now
called a 'computer'.
. When the computers were introduced, they were large and could fill an entire room.
Some computers were operated using large-sized vacuum tubes.
. In 1833, Charles Babbage (known as the father of the computer) invented an early
calculator, which was named as the 'difference engine'.
. Later in 1837, he introduced the first mechanical, general-purpose computer 'Analytical
Engine'. Overtime, computers became powerful in performance and small in size.
SRINIVASARAO G (PROF)-VITAP 1
PROBLEM SOLVING USING PYTHON
Generations of Computer
There are five generations of the computer, which can be classified as below:
First Generation (1946 - 1959): During the first generation, computers were based on electronic
valves (Vacuum Tubes). Some popular computers of first-generation are ENIAC, EDVAC,
UNIVAC, etc.
Second Generation (1959 - 1965): During the second generation, computers were based on
Transistors. Some popular computers of second-generation are IBM 1400, IBM 1620, IBM 7000
series, etc.
Third Generation (1965 - 1971): During the third generation, computers were based on
Integrated Circuits (ICs). Some popular computers of the third generation are IBM 360, IBM
370, PDP, etc.
Fourth Generation (1971 - 1980): During the fourth generation, computers were based on very
large scale integrated (VLSI) circuits. Some popular computers of fourth-generation are STAR
1000, CRAY- 1, CRAY-X-MP, DEC 10, etc.
Fifth Generation (1980 - Present): The fifth generation is still ongoing. The computers are
based on multiple technologies, such as ultra large scale integration (ULSI), artificial
intelligence (AI) , and parallel processing hardware. The fifth generation of computers includes
Desktop, Laptop, NoteBook, etc.
System Software: System software help establish communication between hardware components
so that the user can interact with the computer. These types of software are necessary for the
computer to operate correctly. They provide an interface to run additional third party programs
or utility tools. Operating systems, drivers, utility software, and firmware are typical examples of the
system software.
Application Software: Application software is designed to help users to perform specific tasks,
such as online surfing, setting the alarm, listening to music, playing videos, photo designing,
editing, etc. This type of software mostly runs in the frontend and allows end-users to work on.
Web browsers, Photoshop software, multimedia software and word processors are the example of
the application software.
Hardware
The physical parts attached to a computer that form a whole computer are calledhardwareor
hardware components. There can be different types of hardware, depending on the structure. Some
most common hardware aremouse,keyboard,monitor,printer, etc. These are the parts that can
be seen and touched by humans.
SRINIVASARAO G (PROF)-VITAP 2
PROBLEM SOLVING USING PYTHON
Input Unit: Input Units or devices are used to input the data or instructions into the computers.
Some most common input devices are mouse and keyword.
Output Unit: Output Units or devices are used to provide output to the user in the desired format.
The most popular examples of output devices are the monitor and the printer.
Control Unit: As its name states, this unit is primarily used to control all the computer
functions and functionalities. All the components or devices attached to a computer interact with
each other through the control unit. In short, the control unit is referred to as 'CU'.
Arithmetic Logic Unit: The arithmetic logic unit helps perform all the computer system's arithmetic
and logical operations. In short, the arithmetic logic unit is referred to as 'ALU'.
Memory: Memory is used to store all the input data, instructions, and output data. Memory usually
has two types: Primary Memory and Secondary Memory. The memory found inside the CPUis
called the primary memory, whereas the memory that is not the integral part of theCPUis
called secondary memory.
SRINIVASARAO G (PROF)-VITAP 3
PROBLEM SOLVING USING PYTHON
Functions of Computer
There are four core functions of the computer, as explained below:
Input: Whatever is given to acomputer is called the input. The input data is given to the
computer using the input devices. The computer only takes data in a binary form (raw format).
The input devices help convert the entered data in the binary form to be understandable by the
computer. Data can be inputted in various forms, such as letters, numbers, images, etc.
Processing: Processing is the primary function of the computer. CPU helps to process the
data according to the instructions entered into the computer system. The processing of data is
an internal process of the computer system, and the data is executed in a queue. After the
processing has been completed, the data is further transferred as the output. The processor
(CPU) is the computer's brain, and it is a microchip. The processor's speed varies in different
computers because it depends on several factors, such as the type of CPU, memory, and
motherboard.
Typically, the following operations are performed on the data during the processing:
o Arithmetic Operations, such as addition, subtraction, multiplication , differentials, square root,
etc.
o Logical Operations, such as equal to, not equal to, greater than, less than, opposite, etc.
Output: Anything that comes out from the computer is called the output. It is the human-readable
data anddisplayed on the computer screen (monitor). Output can be stored in the storage devices
if desired. The output devices help convert the processed data of the CPU into the human-
understandable form.
Storage: The device used to store the data of a computer system is called the storage. Storage
devices help to store digital data. They can store the data while the computer is operating and
after processing. There are volatile and non-volatile storage options. The volatile storage can store
SRINIVASARAO G (PROF)-VITAP 4
PROBLEM SOLVING USING PYTHON
the data as long as the power source is connected, whereas non-volatile can store the data
permanently even after the power source is disconnected.
SRINIVASARAO G (PROF)-VITAP 4
PROBLEM SOLVING USING PYTHON
Characteristics of Computer
The essential characteristics of the computer make it such an important part of human lives.
Let's understand the basic characteristics of computers:
Speed: Computers are a high-speed electronic machine. They can carry around 3-4 million
instruction per second. Even advanced computers can handle trillions of instructions per second,
cutting down the time to perform any digital tasks.
Accuracy: Computers are also known for their accurate performance. They can complete the
given jobs at almost 100% accuracy. Although errors may occur in computers, they are usually
caused by incorrect input, incorrect instructions, or bugs in chips. All of these are human errors.
Storage Capacity: Computers can easily store a massive size of data. Modern computers come
inbuilt with high storage features compared to older days. Additional data can be stored on
secondary devices like external hard disks, or flash memory, etc. Due to incredible speed, data
can be retrieved from storage in no time.
Reliability: Computers are reliable and consistent; they can process the same tasks any number
of times without throwing any error. Computers don't get tired like humans, so they are superior to
perform rule- based, repetitive tasks.
Versatility: The variety of tasks that a computer can perform are almost infinite. That means
computers can perform different tasks back to back without making errors; they are no longer
just a computing machine. For one moment, a computer can be used to perform data entry tasks
or ticket booking, and the very next moment, it can be used for complex mathematical calculations
or continuous astronomical observations, etc.
Classification of Computer
According to physical size, computers are classified into the following types:
Supercomputer: Supercomputers are the fastest and the most expensive type of computer. They
are large and require more space for installation. These types of computers are mainly designed to
perform massive data-based and complex tasks. Supercomputers are capable enough to
handle trillions of instructions at the sametime.
Mainframe Computer: Mainframe computers are comparatively smaller in size as compared
to supercomputers. However, they are not much small. These types of computers are designed to
perform hundreds or thousands of jobs at a time simultaneously. These computers can handle
heavy tasks, including complex calculations and can store vast amounts of data. They are
best suited for big organizations such as banking, telecom, and educational sectors.
Microcomputer: Microcomputers are cheap in price and support multi-user platform. These are
the general-purpose computers designed to handle all the necessary tasks of individual needs.
Since they are comparatively slower than mainframe computers, thereby are suitable for small
organizations. They
SRINIVASARAO G (PROF)-VITAP 5
PROBLEM SOLVING USING PYTHON
are best suited for internet café, schools, universities, offices, etc. A microcomputer is also referred
to as the 'Personal Computer (PC)' in general life. Laptop and desktop are examples of
microcomputers.
Minicomputer: Minicomputers are also referred to as Miniframe computers. These are the
midsize multiprocessing computer designed purposely for easy carry. These types of computers are
light-weight and can fit in a small space. They are suitable for billing, accounting, education, and
business purposes. Since these minicomputers are easy to carry, they are the best option for
those who need a computer while traveling. Tablet PC, Notebooks, and cellphones are examples
of minicomputers.
o Computers can automatically perform routine tasks with automation, making humans
available for more intelligent tasks.
o Computers cannot work on their own. They need instructions from humans to complete
tasks. Moreover, computers follow the given instructions blindly without thinking about the
outcomes.
o Computers need a power supply to work. Without a power supply, they are just useless.
o Working on a computer continuously for along period can cause several health issues.
o Wastage of computers and their parts leave a negative impact on the environment.
SRINIVASARAO G (PROF)-VITAP 6
PROBLEM SOLVING USING PYTHON
o Computers are taking human jobs in many sectors. They are replacing human work and
thus increasing unemployment.
SRINIVASARAO G (PROF)-VITAP 6
PROBLEM SOLVING USING PYTHON
ALGORITHM
SRINIVASARAO G (PROF)-VITAP 7
PROBLEM SOLVING USING PYTHON
. Clear and Unambiguous: The algorithm should be clear and unambiguous. Each of
its steps should be clear in all aspects and must lead to only one meaning.
. Well-Defined Outputs: The algorithm must clearly define what output will be yielded
and it should be well-defined as well. It should take atleast 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.
Properties of Algorithm:
SRINIVASARAO G (PROF)-VITAP 8
PROBLEM SOLVING USING PYTHON
Types of Algorithms:
There are several types of algorithms available. Some important algorithms are:
1.Brute Force Algorithm: It is the simplest approach for a problem. A brute force algorithm is
the first approach that comes to finding when we see a problem.
2.Recursive Algorithm: A recursive algorithm is based onrecursion. In this case, a problem is
broken into several sub-parts and called the same function again and again.
4.Searching Algorithm: Searching algorithms are the ones that are used for searching
elements or groups of elements from a particular data structure. They can be of different types
based on their approach or the data structure in which the element should be found.
6.Hashing Algorithm: Hashing algorithms work similarly to the searching algorithm. But they
contain an index with a key ID. In hashing, a key is assigned to specific data.
7.Divide and Conquer Algorithm: This algorithm breaks a problem into sub-problems, solves a
single sub-problem and merges the solutions together to get the final solution. It consists of the
following three steps:
. Divide
. Solve
. Combine
8.Greedy Algorithm: In this type of algorithm the solution is built part by part. The solution of
the next part is built based on the immediate benefit of the next part. The one solution giving the
most benefit will be chosen as the solution for the next part.
9.Dynamic Programming Algorithm: This algorithm uses the concept of using the already
found solution to avoid repetitive calculation of the same part of the problem. It divides the
problem into smaller overlapping subproblems and solves them.
Advantages of Algorithms:
. It is easy to understand.
SRINIVASARAO G (PROF)-VITAP 9
PROBLEM SOLVING USING PYTHON
. An algorithm is astep-wise representation of a solution to a given problem.
SRINIVASARAO G (PROF)-VITAP 9
PROBLEM SOLVING USING PYTHON
. In 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).
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 betaken to solve the problem.
4. The output to be expected when the problem is solved.
5. The solution to this problem, is within the given constraints.
Example
Algorithm to print whether entered number is positive or negative or Zero:
1. START
2. Print “Give any number”
3. Read num
4. if(num==0) print “you entered 0”
5. if(num>0) print “you entered a positive number”
6. if(num<0) print “you entered a negative number”
7. END
SRINIVASARAO G (PROF)-VITAP 10
PROBLEM SOLVING USING PYTHON
Flow Chart
• Flowchart is the most widely used graphical representation of an algorithm
Flowchart symbols
The different flowchart symbols have different conventional meanings.
Terminal Symbol: In the flowchart, it is represented with the help of a circle for denoting the start
and stop symbol. The symbol given below is used to represent the terminal symbol.
Input/output Symbol: The input symbol is used to represent the input data, and the output
symbol is used to display the output operation. The symbol given below is used for representing
the Input/output symbol.
SRINIVASARAO G (PROF)-VITAP 11
PROBLEM SOLVING USING PYTHON
Processing Symbol: It is represented in a flowchart with the help of a rectangle box used to
represent the arithmetic and data movement instructions. The symbol given below is used to
represent the processing symbol.
Decision Symbol: Diamond symbol is used for represents decision-making statements. The
symbol given below is used to represent the decision symbol.
Connector Symbol: The connector symbol is used if flows discontinued at some point and
continued again at another place. The following symbol is the representation of the connector
symbol.
SRINIVASARAO G (PROF)-VITAP 12
PROBLEM SOLVING USING PYTHON
Flow lines: It represents the exact sequence in which instructions are executed. Arrows are
used to represent the flow lines in a flowchart. The symbol given below is used for representing
the flow lines:
Hexagon symbol (Flat): It is used to create a preparation box containing the loop setting
statement. The symbol given below is used for representing the Hexagon symbol.
On-Page Reference Symbol: This symbol contains a letter inside that indicates the flow continues
on a matching symbol containing the same letters somewhere else on the same page. The symbol
given below is used for representing the on-page reference symbol.
SRINIVASARAO G (PROF)-VITAP 13
PROBLEM SOLVING USING PYTHON
SRINIVASARAO G (PROF)-VITAP 13
PROBLEM SOLVING USING PYTHON
Off-Page Reference: This symbol contains a letter inside indicating that the flow continues on a
matching symbol containing the same letter somewhere else on a different page. The symbol given
below is used to represent the off-page reference symbol.
Document Symbol: This symbol is used in a flowchart to indicate a document or report. The
symbol given below is used to represent the document symbol.
Internal storage symbol: The symbol given below is used to represent the internal storage
symbol.
Advantages of flowchart
SRINIVASARAO G (PROF)-VITAP 14
PROBLEM SOLVING USING PYTHON
Efficient Coding: Flowcharts act as a guide for a programmer in writing the actual code in a
high-level language.
Proper Debugging: Flowcharts help in the debugging process.
Effective Analysis: Effective analysis of logical programs can be easily done with the help of a
related flowchart.
Proper Documentation: Flowchart provides better and proper documentation. It consists of
various activities such as collecting, organizing, storing, and maintaining all related program
records.
Testing: A flowchart helps in the testing process.
Efficient program maintenance: The maintenance of the program becomes easy with the help
of a flowchart.
Disadvantages of flowchart
> Time-consuming
> Complex
> Difficult to modify
Example 1
> Draw a flowchart to calculate the average of two numbers.
SRINIVASARAO G (PROF)-VITAP 15
PROBLEM SOLVING USING PYTHON
SRINIVASARAO G (PROF)-VITAP 15
PROBLEM SOLVING USING PYTHON
In this method, thenaïve approach will store the value of the P variable in a temporary variable,
and then it will assign the variable P with the value of the Q variable. Then, it will assign the
value of the temporary variable to the Q variable, which will result in swapping the values of both
the variable.
Example:
SRINIVASARAO G (PROF)-VITAP 16
PROBLEM SOLVING USING PYTHON
Output:
We can use the comma operator. We do not need to use a third variable for swapping the values
of two variables for this method.
Example:
Output:
In this method, we can swap values of both the variable in two ways:
SRINIVASARAO G (PROF)-VITAP 17
PROBLEM SOLVING USING PYTHON
Example:
Output:
Example:
Output:
SRINIVASARAO G (PROF)-VITAP 18
PROBLEM SOLVING USING PYTHON
Counting
Given a number N, the task is to return the count of digits in this number.
count = 0
while n != 0:
n //= 10
count += 1
return count
# Driver Code
n = 345289467
print("Number of digits : % d" % (countDigit(n)))
Output
SRINIVASARAO G (PROF)-VITAP 19
PROBLEM SOLVING USING PYTHON
Number of digits : 9
Syntax:
• sum(iterable, start)
• iterable : iterable can be anything list , tuples or dictionaries , but most importantly it
should be numbers.
• start : this start is added to the sum of numbers in the iterable.
• If start is not given in the syntax , it is assumed to be 0.
# sum()
numbers = [1,2,3,4,5,1,4,5]
# start parameter is not provided
Sum = sum(numbers)
print(Sum)
# start = 10
Sum = sum(numbers, 10)
print(Sum)
SRINIVASARAO G (PROF)-VITAP 20
PROBLEM SOLVING USING PYTHON
Output:
25
35
Factorial Computation
The factorial is always found for a positive integer by multiplying all the integers starting from 1
till the given number. There can be three approaches to find this as shown below.
Using a For Loop
We can use a for loop to iterate through number 1 till the designated number and keep
multiplying at each step. In the below program we ask the user to enter the number and convert
the input to an integer before using it in the loop. This way we ensure we get positive integers in
the calculation.
Example
n = input("Enter a number: ")
factorial = 1
if int(n) >= 1:
for i in range (1,int(n)+1):
factorial = factorial * i
print("Factorial of ",n , " is : ",factorial)
Output
Enter a number: 5
Factorial of 5 is : 120
Using Recursion
num = input("Enter a number: ")
def recur_factorial(n):
if n == 1:
return n
elifn < 1:
SRINIVASARAO G (PROF)-VITAP 21
PROBLEM SOLVING USING PYTHON
return ("NA")
SRINIVASARAO G (PROF)-VITAP 21
PROBLEM SOLVING USING PYTHON
else:
return n*recur_factorial(n-1)
print (recur_factorial(int(num)))
Output:
#Run1:
Enter a number: 5
120
#Run2:
Enter a number: -2
NA
Using math.factorial()
In this case we can directly use factorial function which is available in math module. We need not
write the code for factorial functionality rather directly use the math.factorial(). That also takes care
of negative numbers and fractional numbers scenario.
import math
num = input("Enter a number: ")
print(math.factorial(int(num)))
print("The factorial of ", num, " is : ")
Output
Enter a number: 5
Factorial of 5 is : 120
SRINIVASARAO G (PROF)-VITAP 22
PROBLEM SOLVING USING PYTHON
Parameters
Output:
sin(3) : 0.14112000806
sin(-3) : -0.14112000806
sin(0) : 0.0
sin(math.pi) : 1.22464679915e-16
sin(math.pi/2) : 1.0
Fibonacci Sequence
n = int(input(‘enter n value’))
n1 = 0
n2 = 1
Count=0
If(n<=0)
print(‘enter a valid number’)
elif(n==1):
print(‘Fibonacci series of 1 is 0’)
else:
while(count<n):
SRINIVASARAO G (PROF)-VITAP 23
PROBLEM SOLVING USING PYTHON
print(n1)
SRINIVASARAO G (PROF)-VITAP 23
PROBLEM SOLVING USING PYTHON
count = count+1
Output
Enter n value 5
0
1
1
2
3
Program
number = int(input("Enter the integer number: "))
revs_number = 0
while (number > 0):
SRINIVASARAO G (PROF)-VITAP 24
PROBLEM SOLVING USING PYTHON
remainder = number % 10
revs_number = (revs_number * 10) + remainder
number = number // 10
print("The reverse number is : {}".format(revs_number))
Output:
Enter the integer number: 12345
Electronic and Digital systems may use a variety of different number systems, (e.g.
Decimal, Hexadecimal, Octal, Binary).
A number N in base or radix b can be written as:
(N)b = dn-1 dn-2 -- -- -- -- d1 d0 . d-1 d-2 -- -- -- -- d-m
In the above, dn-1 to d0 is the integer part, then follows a radix point, and then d-1 to d-m is the
fractional part.
dn-1 = Most significant bit (MSB)
d-m = Least significant bit (LSB)
SRINIVASARAO G (PROF)-VITAP 25
PROBLEM SOLVING USING PYTHON
Note: Keep multiplying the fractional part with 2 until decimal part 0.00 is obtained.
(0.25)10 = (0.01)2
Answer: (10.25)10 = (1010.01)2
2. Binary to Decimal
(1010.01)2
1x23 + 0x22 + 1x21+ 0x20 + 0x2 -1 + 1x2 -2 = 8+0+2+0+0+0.25 = 10.25
(1010.01)2 = (10.25)10
3. Decimal to Octal
(10.25)10
(10)10 = (12)8
Fractional part:
0.25 x 8 = 2.00
Note: Keep multiplying the fractional part with 8 until decimal part .00 is obtained.
(.25)10 = (.2)8
Answer: (10.25)10 = (12.2)8
SRINIVASARAO G (PROF)-VITAP 26
PROBLEM SOLVING USING PYTHON
4. Octal to Decimal
(12.2)8
1 x 81 + 2 x 80 +2 x 8-1 = 8+2+0.25 = 10.25
(12.2)8 = (10.25)10
5. Hexadecimal to Binary
To convert from Hexadecimal to Binary, write the 4-bit binary equivalent of hexadecimal.
(3A)16 = (00111010)2
6. Binary to Hexadecimal
To convert from Binary to Hexadecimal, start grouping the bits in groups of 4 from the right-end
and write the equivalent hexadecimal for the 4-bit binary. Add extra 0’son the left to adjust the
groups.
1111011011
0011 1101 1011
(001111011011 )2 = (3DB)16
SRINIVASARAO G (PROF)-VITAP 27
PROBLEM SOLVING USING PYTHON
def decimalToBinary(N):
B_Number = 0
cnt = 0
while (N != 0):
rem = N % 2
c = pow(10, cnt)
B_Number += rem * c
N //= 2
cnt += 1
return B_Number
# Driver code
N = 17
print(decimalToBinary(N))
Output
10001
SRINIVASARAO G (PROF)-VITAP 28
PROBLEM SOLVING USING PYTHON
# binary to decimal
# Function to convert
# binary to decimal
def binaryToDecimal(n):
num = n;
dec_value = 0;
# Initializing base
# value to 1, i.e 2 ^ 0
base = 1;
temp = num;
while(temp):
last_digit = temp % 10;
base = base * 2;
return dec_value;
# Driver Code
num = 10101001;
print(binaryToDecimal(num));
Output:
169
SRINIVASARAO G (PROF)-VITAP 29
PROBLEM SOLVING USING PYTHON
# decimal number
def decimaltoOctal(deciNum):
# initializations
octalNum = 0
countval = 1
dNo = deciNum
countval = countval * 10
deciNum //= 8
print(octalNum)
# Driver Code
if __name__ == '__main__':
n = 33
# Function Call
decimaltoOctal(n)
Output
41
SRINIVASARAO G (PROF)-VITAP 30
PROBLEM SOLVING USING PYTHON
# octal to decimal
# Function to convert
# octal to decimal
def octalToDecimal(n):
num = n
dec_value = 0
base = 1
temp = num
while (temp):
last_digit = temp % 10
temp = int(temp / 10)
base = base * 8
return dec_value
SRINIVASARAO G (PROF)-VITAP 31
PROBLEM SOLVING USING PYTHON
# Driver Code
num = 67
print(octalToDecimal(num))
Output
55
SRINIVASARAO G (PROF)-VITAP 32